test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // httpbingo.org intermittently answers with gateway errors unrelated to the
  145. // client under test.
  146. static bool is_gateway_error(const Result &res) {
  147. return res && (res->status == StatusCode::BadGateway_502 ||
  148. res->status == StatusCode::ServiceUnavailable_503 ||
  149. res->status == StatusCode::GatewayTimeout_504);
  150. }
  151. template <typename F> static Result retry_gateway_errors(F &&send) {
  152. auto res = send();
  153. for (auto wait : {1, 2}) {
  154. if (!is_gateway_error(res)) { break; }
  155. std::this_thread::sleep_for(std::chrono::seconds(wait));
  156. res = send();
  157. }
  158. return res;
  159. }
  160. #define SKIP_ON_GATEWAY_ERROR(res) \
  161. do { \
  162. if (is_gateway_error(res)) { \
  163. GTEST_SKIP() << "gateway error " << (res)->status; \
  164. } \
  165. } while (0)
  166. class UnixSocketTest : public ::testing::Test {
  167. protected:
  168. void TearDown() override { std::remove(pathname_.c_str()); }
  169. void client_GET(const std::string &addr) {
  170. httplib::Client cli{addr};
  171. cli.set_address_family(AF_UNIX);
  172. ASSERT_TRUE(cli.is_valid());
  173. const auto &result = cli.Get(pattern_);
  174. ASSERT_TRUE(result) << "error: " << result.error();
  175. const auto &resp = result.value();
  176. EXPECT_EQ(resp.status, StatusCode::OK_200);
  177. EXPECT_EQ(resp.body, content_);
  178. }
  179. static std::string make_sock_path() {
  180. const char *shard = getenv("GTEST_SHARD_INDEX");
  181. return shard ? std::string("./httplib-server-") + shard + ".sock"
  182. : "./httplib-server.sock";
  183. }
  184. const std::string pathname_{make_sock_path()};
  185. const std::string pattern_{"/hi"};
  186. const std::string content_{"Hello World!"};
  187. };
  188. TEST_F(UnixSocketTest, pathname) {
  189. httplib::Server svr;
  190. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  191. res.set_content(content_, "text/plain");
  192. });
  193. std::thread t{[&] {
  194. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  195. }};
  196. auto se = detail::scope_exit([&] {
  197. svr.stop();
  198. t.join();
  199. ASSERT_FALSE(svr.is_running());
  200. });
  201. svr.wait_until_ready();
  202. ASSERT_TRUE(svr.is_running());
  203. client_GET(pathname_);
  204. // ".//x.sock", which is not taken for a URL
  205. client_GET("./" + pathname_.substr(1));
  206. }
  207. #if defined(__linux__) || \
  208. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  209. TEST_F(UnixSocketTest, PeerPid) {
  210. httplib::Server svr;
  211. std::string remote_port_val;
  212. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  213. res.set_content(content_, "text/plain");
  214. remote_port_val = std::to_string(req.remote_port);
  215. });
  216. std::thread t{[&] {
  217. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  218. }};
  219. auto se = detail::scope_exit([&] {
  220. svr.stop();
  221. t.join();
  222. ASSERT_FALSE(svr.is_running());
  223. });
  224. svr.wait_until_ready();
  225. ASSERT_TRUE(svr.is_running());
  226. client_GET(pathname_);
  227. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  228. }
  229. #endif
  230. #ifdef __linux__
  231. TEST_F(UnixSocketTest, abstract) {
  232. constexpr char svr_path[]{"\x00httplib-server.sock"};
  233. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  234. httplib::Server svr;
  235. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  236. res.set_content(content_, "text/plain");
  237. });
  238. std::thread t{[&] {
  239. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  240. }};
  241. auto se = detail::scope_exit([&] {
  242. svr.stop();
  243. t.join();
  244. ASSERT_FALSE(svr.is_running());
  245. });
  246. svr.wait_until_ready();
  247. ASSERT_TRUE(svr.is_running());
  248. client_GET(abstract_addr);
  249. }
  250. #endif
  251. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  252. httplib::Server svr;
  253. std::string received_host_header;
  254. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  255. // Capture the Host header sent by the client
  256. auto host_iter = req.headers.find("Host");
  257. if (host_iter != req.headers.end()) {
  258. received_host_header = host_iter->second;
  259. }
  260. res.set_content(content_, "text/plain");
  261. });
  262. std::thread t{[&] {
  263. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  264. }};
  265. auto se = detail::scope_exit([&] {
  266. svr.stop();
  267. t.join();
  268. ASSERT_FALSE(svr.is_running());
  269. });
  270. svr.wait_until_ready();
  271. ASSERT_TRUE(svr.is_running());
  272. // Test that Host header is automatically set to "localhost" for Unix socket
  273. // connections
  274. httplib::Client cli{pathname_};
  275. cli.set_address_family(AF_UNIX);
  276. ASSERT_TRUE(cli.is_valid());
  277. const auto &result = cli.Get(pattern_);
  278. ASSERT_TRUE(result) << "error: " << result.error();
  279. const auto &resp = result.value();
  280. EXPECT_EQ(resp.status, StatusCode::OK_200);
  281. EXPECT_EQ(resp.body, content_);
  282. // Verify that Host header was automatically set to "localhost"
  283. EXPECT_EQ(received_host_header, "localhost");
  284. }
  285. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  286. // Another socket in the working directory, which a Location can name as
  287. // its host
  288. const auto other_path = "other-" + pathname_.substr(2);
  289. httplib::Server svr;
  290. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  291. // An absolute Location naming the Host this client sends
  292. res.set_redirect("http://localhost" + pattern_);
  293. });
  294. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  295. res.set_redirect("http://" + other_path + pattern_);
  296. });
  297. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  298. res.set_redirect("http://mapped.test" + pattern_);
  299. });
  300. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  301. res.set_header("X-Auth", req.get_header_value("Authorization"));
  302. res.set_content(content_, "text/plain");
  303. });
  304. httplib::Server other;
  305. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  306. res.set_content("other", "text/plain");
  307. });
  308. std::thread t{[&] {
  309. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  310. }};
  311. std::thread t2{[&] {
  312. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  313. }};
  314. auto se = detail::scope_exit([&] {
  315. svr.stop();
  316. other.stop();
  317. t.join();
  318. t2.join();
  319. std::remove(other_path.c_str());
  320. });
  321. svr.wait_until_ready();
  322. other.wait_until_ready();
  323. httplib::Client cli{pathname_};
  324. cli.set_address_family(AF_UNIX);
  325. cli.set_follow_location(true);
  326. cli.set_bearer_token_auth("token");
  327. // Another host: the same socket, without the credentials
  328. auto res = cli.Get("/cross");
  329. ASSERT_TRUE(res) << "error: " << res.error();
  330. EXPECT_EQ(StatusCode::OK_200, res->status);
  331. EXPECT_EQ(content_, res->body);
  332. EXPECT_EQ("", res->get_header_value("X-Auth"));
  333. // localhost is this client's own host
  334. res = cli.Get("/redirect");
  335. ASSERT_TRUE(res) << "error: " << res.error();
  336. EXPECT_EQ(StatusCode::OK_200, res->status);
  337. EXPECT_EQ(content_, res->body);
  338. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  339. // A host the caller mapped to a socket goes there
  340. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  341. res = cli.Get("/mapped");
  342. ASSERT_TRUE(res) << "error: " << res.error();
  343. EXPECT_EQ(StatusCode::OK_200, res->status);
  344. EXPECT_EQ("other", res->body);
  345. }
  346. #ifndef _WIN32
  347. TEST(SocketStream, wait_writable_UNIX) {
  348. int fds[2];
  349. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  350. const auto asSocketStream = [&](socket_t fd,
  351. std::function<bool(Stream &)> func) {
  352. return detail::process_client_socket(
  353. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  354. };
  355. asSocketStream(fds[0], [&](Stream &s0) {
  356. EXPECT_EQ(s0.socket(), fds[0]);
  357. EXPECT_TRUE(s0.wait_writable());
  358. EXPECT_TRUE(s0.is_peer_alive());
  359. EXPECT_EQ(0, close(fds[1]));
  360. EXPECT_FALSE(s0.is_peer_alive());
  361. return true;
  362. });
  363. EXPECT_EQ(0, close(fds[0]));
  364. }
  365. TEST(SocketStream, wait_writable_INET) {
  366. sockaddr_in addr;
  367. memset(&addr, 0, sizeof(addr));
  368. addr.sin_family = AF_INET;
  369. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  370. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  371. int disconnected_svr_sock = -1;
  372. std::thread svr{[&] {
  373. const int s = socket(AF_INET, SOCK_STREAM, 0);
  374. ASSERT_LE(0, s);
  375. // PORT + 1 is shared with the SSL redirect tests and with
  376. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  377. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  378. // because that happens on a worker thread the ASSERT does not stop the
  379. // test: it runs on and fails at the disconnected_svr_sock check instead.
  380. default_socket_options(s);
  381. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  382. ASSERT_EQ(0, listen(s, 1));
  383. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  384. ASSERT_EQ(0, close(s));
  385. }};
  386. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  387. std::thread cli{[&] {
  388. const int s = socket(AF_INET, SOCK_STREAM, 0);
  389. ASSERT_LE(0, s);
  390. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  391. ASSERT_EQ(0, close(s));
  392. }};
  393. cli.join();
  394. svr.join();
  395. ASSERT_NE(disconnected_svr_sock, -1);
  396. const auto asSocketStream = [&](socket_t fd,
  397. std::function<bool(Stream &)> func) {
  398. return detail::process_client_socket(
  399. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  400. };
  401. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  402. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  403. // wait_writable() returns true because select_write() only checks if the
  404. // send buffer has space. Peer disconnection is detected later by send().
  405. EXPECT_TRUE(ss.wait_writable());
  406. return true;
  407. });
  408. ASSERT_EQ(0, close(disconnected_svr_sock));
  409. }
  410. #endif // #ifndef _WIN32
  411. TEST(SetSocketOptTest, TcpNoDelay) {
  412. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  413. ASSERT_NE(sock, INVALID_SOCKET);
  414. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  415. int val = 0;
  416. socklen_t len = sizeof(val);
  417. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  418. reinterpret_cast<char *>(&val), &len));
  419. EXPECT_NE(val, 0);
  420. detail::close_socket(sock);
  421. }
  422. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  423. // accept() reports failures through WSAGetLastError() on Windows and through
  424. // errno everywhere else. Asking the wrong one is what made the accept loop
  425. // treat every recoverable failure as fatal on Windows.
  426. struct Classification {
  427. bool resource;
  428. bool transient;
  429. };
  430. auto classify = [](int err) {
  431. #ifdef _WIN32
  432. WSASetLastError(err);
  433. #else
  434. errno = err;
  435. #endif
  436. // Read both before asserting: an assertion may clobber the error slot.
  437. Classification c;
  438. c.resource = detail::is_accept_resource_error();
  439. c.transient = detail::is_accept_transient_error();
  440. return c;
  441. };
  442. #ifdef _WIN32
  443. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  444. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  445. WSAECONNRESET, WSAECONNABORTED};
  446. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  447. #else
  448. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  449. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  450. ECONNABORTED};
  451. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  452. #endif
  453. for (auto err : resource_errors) {
  454. const auto c = classify(err);
  455. EXPECT_TRUE(c.resource) << "error " << err;
  456. EXPECT_FALSE(c.transient) << "error " << err;
  457. }
  458. for (auto err : transient_errors) {
  459. const auto c = classify(err);
  460. EXPECT_TRUE(c.transient) << "error " << err;
  461. EXPECT_FALSE(c.resource) << "error " << err;
  462. }
  463. for (auto err : fatal_errors) {
  464. const auto c = classify(err);
  465. EXPECT_FALSE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. #ifdef _WIN32
  469. WSASetLastError(0);
  470. #else
  471. errno = 0;
  472. #endif
  473. }
  474. TEST(ClientTest, MoveConstructible) {
  475. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  476. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  477. }
  478. TEST(ClientTest, MoveAssignable) {
  479. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  480. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  481. }
  482. #ifdef _WIN32
  483. TEST(StartupTest, WSAStartup) {
  484. WSADATA wsaData;
  485. int ret = WSAStartup(0x0002, &wsaData);
  486. ASSERT_EQ(0, ret);
  487. }
  488. #endif
  489. TEST(DecodePathTest, PercentCharacter) {
  490. EXPECT_EQ(
  491. decode_path_component(
  492. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  493. U8("descrip=Gastos áéíóúñÑ 6"));
  494. }
  495. TEST(DecodePathTest, PercentCharacterNUL) {
  496. string expected;
  497. expected.push_back('x');
  498. expected.push_back('\0');
  499. expected.push_back('x');
  500. EXPECT_EQ(decode_path_component("x%00x"), expected);
  501. }
  502. TEST(DecodePathTest, UnicodeEncoding) {
  503. // %u0041 = 'A' (1-byte UTF-8)
  504. EXPECT_EQ("A", decode_path_component("%u0041"));
  505. // %u00E9 = 'é' (2-byte UTF-8)
  506. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  507. // %u3042 = 'あ' (3-byte UTF-8)
  508. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  509. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  510. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  511. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  512. // neighbours)
  513. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  514. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  515. }
  516. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  517. // A sign or whitespace inside the two-character escape window must not be
  518. // accepted as a valid percent-encoding; the sequence is passed through
  519. // literally, matching decode_uri_component / decode_path_component.
  520. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  521. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  522. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  523. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  524. // Well-formed escapes still decode.
  525. EXPECT_EQ("-", decode_query_component("%2D", false));
  526. EXPECT_EQ("A", decode_query_component("%41", false));
  527. }
  528. TEST(SanitizeFilenameTest, VariousPatterns) {
  529. // Path traversal
  530. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  531. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  532. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  533. // Normal and edge cases
  534. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  535. EXPECT_EQ("filename.txt",
  536. httplib::sanitize_filename("/path/to/filename.txt"));
  537. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  538. EXPECT_EQ("", httplib::sanitize_filename(".."));
  539. EXPECT_EQ("", httplib::sanitize_filename(""));
  540. // Null bytes stripped
  541. EXPECT_EQ("safe.txt",
  542. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  543. // Whitespace-only rejected
  544. EXPECT_EQ("", httplib::sanitize_filename(" "));
  545. }
  546. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  547. // before it is dropped; anywhere else it is an ordinary file name character.
  548. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  549. #ifdef _WIN32
  550. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  551. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  552. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  553. #else
  554. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  555. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  556. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  557. #endif
  558. }
  559. // Forward declaration (see the base64_encode note below): split builds move the
  560. // definition into httplib.cc, so re-declaring it here lets the test link.
  561. namespace httplib {
  562. namespace detail {
  563. bool is_chunked_transfer_encoding(const Headers &headers);
  564. } // namespace detail
  565. } // namespace httplib
  566. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  567. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  568. auto make = [](std::initializer_list<const char *> lines) {
  569. Headers h;
  570. for (auto te : lines) {
  571. if (te) { h.emplace("Transfer-Encoding", te); }
  572. }
  573. return h;
  574. };
  575. // Sole coding, matched case-insensitively.
  576. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  577. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  578. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  579. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  580. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  581. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  582. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  583. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  584. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  585. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  586. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  587. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  588. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  589. // were received, into one list. Headers preserves that order, so the answer
  590. // is decided by the last coding of the last line and the order the lines
  591. // arrived in is significant.
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  593. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  595. // The split can fall anywhere in the list.
  596. EXPECT_TRUE(
  597. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  598. EXPECT_FALSE(
  599. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  600. // A trailing line naming no coding leaves the list ending in nothing, so it
  601. // must not inherit the chunked from the line before it.
  602. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  603. }
  604. // Forward declarations (see the base64_encode note below).
  605. namespace httplib {
  606. namespace detail {
  607. bool parse_status_line(const char *line, std::string &version, int &status,
  608. std::string &reason);
  609. std::string file_extension(const std::string &path);
  610. std::string
  611. find_content_type(const std::string &path,
  612. const std::map<std::string, std::string> &user_data,
  613. const std::string &default_content_type);
  614. bool can_compress_content_type(const std::string &content_type);
  615. bool is_prohibited_header_name(const std::string &name);
  616. bool is_valid_path(const std::string &path);
  617. #ifdef CPPHTTPLIB_SSL_ENABLED
  618. bool match_hostname(const std::string &pattern, const std::string &hostname);
  619. #endif
  620. } // namespace detail
  621. } // namespace httplib
  622. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  623. struct {
  624. const char *line;
  625. const char *version;
  626. int status;
  627. const char *reason;
  628. } cases[] = {
  629. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  630. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  631. // The reason phrase may be empty, or left out along with its space.
  632. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  633. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  634. };
  635. for (const auto &c : cases) {
  636. std::string version;
  637. int status = 0;
  638. std::string reason = "unset";
  639. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  640. << c.line;
  641. EXPECT_EQ(c.version, version);
  642. EXPECT_EQ(c.status, status);
  643. EXPECT_EQ(c.reason, reason);
  644. }
  645. }
  646. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  647. const char *lines[] = {
  648. "HTTP/2 200 OK\r\n",
  649. "HTTP/1.2 200 OK\r\n",
  650. "HTTP/1.1 20 OK\r\n",
  651. "HTTP/1.1 2000 OK\r\n",
  652. "HTTP/1.1 2x0 OK\r\n",
  653. "HTTP/1.1 200 OK\r\n",
  654. "HTTP/1.1 200OK\r\n",
  655. "HTTP/1.1 200 O\rK\r\n",
  656. "HTTP/1.1 200 OK",
  657. "HTTP/1.1 200 OK\r\nX",
  658. "",
  659. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  660. "HTTP/1.1 200 OK\n",
  661. #endif
  662. };
  663. for (auto line : lines) {
  664. std::string version;
  665. int status = 0;
  666. std::string reason;
  667. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  668. << line;
  669. }
  670. }
  671. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  672. // Long enough to overflow the stack when matched with std::regex.
  673. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  674. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  675. std::string version;
  676. int status = 0;
  677. std::string reason;
  678. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  679. EXPECT_EQ(200, status);
  680. EXPECT_EQ(long_reason, reason);
  681. }
  682. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  683. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  684. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  685. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  686. EXPECT_EQ("", detail::file_extension("noext"));
  687. EXPECT_EQ("", detail::file_extension("a."));
  688. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  689. EXPECT_EQ("", detail::file_extension("a.b-c"));
  690. // Long enough to overflow the stack when matched with std::regex.
  691. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  692. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  693. }
  694. #ifdef CPPHTTPLIB_SSL_ENABLED
  695. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  696. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  697. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  698. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  699. // A wildcard needs two labels after it, in the leftmost label only
  700. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  701. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  702. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  703. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  704. EXPECT_FALSE(
  705. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  706. // No name may have an empty label
  707. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  708. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  709. }
  710. #endif
  711. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  712. detail::case_ignore::hash hash;
  713. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  714. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  715. // Long enough to overflow the stack if hashed one call per character.
  716. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  717. }
  718. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  719. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  720. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  721. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  722. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  723. // Same 26-bit hash as html, svg and js.
  724. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  725. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  726. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  727. }
  728. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  729. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  730. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  731. }
  732. }
  733. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  734. // name anywhere else.
  735. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  736. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  737. #ifdef _WIN32
  738. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  739. #else
  740. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  741. #endif
  742. }
  743. }
  744. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  745. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  746. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  747. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  748. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  749. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  750. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  751. // Same 26-bit hash as application/json.
  752. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  753. }
  754. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  755. Request req;
  756. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  757. EXPECT_TRUE(req.is_multipart_form_data());
  758. std::string boundary;
  759. EXPECT_TRUE(detail::parse_multipart_boundary(
  760. req.get_header_value("Content-Type"), boundary));
  761. EXPECT_EQ("x", boundary);
  762. }
  763. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  764. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  765. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  766. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  767. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  768. // Same 26-bit hash as REMOTE_ADDR.
  769. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  770. }
  771. // Forward declaration: in split builds split.py strips `inline` and moves the
  772. // definition into httplib.cc, so detail::base64_encode is not visible from the
  773. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  774. // in both header-only and split builds.
  775. namespace httplib {
  776. namespace detail {
  777. std::string base64_encode(const std::string &in);
  778. } // namespace detail
  779. } // namespace httplib
  780. TEST(Base64EncodeTest, KnownAnswers) {
  781. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  782. // where the accumulator's top bit is already set before the next shift.
  783. EXPECT_EQ("", detail::base64_encode(""));
  784. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  785. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  786. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  787. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  788. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  789. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  790. // High bytes keep the top bit set across several rounds.
  791. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  792. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  793. }
  794. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  795. string unescapedCharacters = "-_.!~*'()";
  796. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  797. }
  798. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  799. string reservedCharacters = ";,/?:@&=+$";
  800. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  801. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  802. }
  803. TEST(ClientQueryOrder, PreserveOrder) {
  804. // This test reproduces Issue #2259: client may reorder query parameters
  805. // when sending a GET request. The expected behavior is that the client
  806. // preserves the original query string order when the caller supplied it
  807. // as part of the path.
  808. Server svr;
  809. svr.Get("/", [&](const Request &req, Response &res) {
  810. // Echo back the raw target so the test can assert ordering
  811. res.set_content(req.target, "text/plain");
  812. });
  813. std::thread t{[&] { svr.listen(HOST, PORT); }};
  814. auto se = detail::scope_exit([&] {
  815. svr.stop();
  816. t.join();
  817. ASSERT_FALSE(svr.is_running());
  818. });
  819. svr.wait_until_ready();
  820. Client cli(HOST, PORT);
  821. ASSERT_TRUE(cli.is_valid());
  822. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  823. auto res = cli.Get(original);
  824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  825. // Expect the echoed target to exactly match the original path (order
  826. // preserved)
  827. EXPECT_EQ(res->body, original);
  828. }
  829. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  830. string chineseCharacters = U8("中国語");
  831. string russianCharacters = U8("дом");
  832. string brazilianCharacters = U8("óculos");
  833. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  834. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  835. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  836. "%D0%B4%D0%BE%D0%BC");
  837. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  838. }
  839. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  840. string unescapedCharacters = "-_.!~*'()";
  841. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  842. }
  843. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  844. string reservedCharacters = ";,/?:@&=+$";
  845. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  846. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  847. }
  848. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  849. string chineseCharacters = U8("中国語");
  850. string russianCharacters = U8("дом");
  851. string brazilianCharacters = U8("óculos");
  852. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  853. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  854. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  855. "%D0%B4%D0%BE%D0%BC");
  856. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  857. }
  858. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  859. // Issue #2082 use case: encoding path component with ampersand
  860. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  861. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  862. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  863. }
  864. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  865. string unescapedCharacters = "-_.!~*'()";
  866. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  867. }
  868. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  869. string reservedCharacters = ";,/?:@&=+$#";
  870. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  871. }
  872. TEST(EncodeUriTest, TestUTF8Characters) {
  873. string chineseCharacters = U8("中国語");
  874. string russianCharacters = U8("дом");
  875. string brazilianCharacters = U8("óculos");
  876. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  877. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  878. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  879. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  880. }
  881. TEST(EncodeUriTest, TestCompleteUri) {
  882. string uri =
  883. "https://example.com/path/to/resource?query=value&param=test#fragment";
  884. EXPECT_EQ(
  885. httplib::encode_uri(uri),
  886. "https://example.com/path/to/resource?query=value&param=test#fragment");
  887. }
  888. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  889. string uri =
  890. "https://example.com/path with spaces/file name.html?q=hello world";
  891. EXPECT_EQ(httplib::encode_uri(uri),
  892. "https://example.com/path%20with%20spaces/"
  893. "file%20name.html?q=hello%20world");
  894. }
  895. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  896. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  897. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  898. }
  899. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  900. string unescapedCharacters = "-_.!~*'()";
  901. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  902. }
  903. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  904. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  905. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  906. string encodedBrazilian = "%C3%B3culos";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  908. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  909. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  910. }
  911. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  912. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  913. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  914. "Piri Tommy Villiers - on & on");
  915. }
  916. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  917. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  918. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  919. }
  920. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  921. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  922. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  923. }
  924. TEST(DecodeUriTest, TestUTF8Characters) {
  925. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  926. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  927. string encodedBrazilian = "%C3%B3culos";
  928. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  929. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  930. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  931. }
  932. TEST(DecodeUriTest, TestCompleteUri) {
  933. string encodedUri = "https://example.com/path%20with%20spaces/"
  934. "file%20name.html?q=hello%20world";
  935. EXPECT_EQ(
  936. httplib::decode_uri(encodedUri),
  937. "https://example.com/path with spaces/file name.html?q=hello world");
  938. }
  939. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  940. string original =
  941. "https://example.com/path with spaces/file name.html?q=hello world";
  942. string encoded = httplib::encode_uri(original);
  943. string decoded = httplib::decode_uri(encoded);
  944. EXPECT_EQ(decoded, original);
  945. }
  946. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  947. // decode_uri is the inverse of encode_uri: an escaped reserved character
  948. // stays encoded so it is not promoted into a real delimiter, while
  949. // non-reserved escapes still decode (like JS decodeURI).
  950. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  951. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  952. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  953. "%3F%3A%40%26%3D%2B%24%2C%3B");
  954. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  955. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  956. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  957. "http://example.com/a%2Fb");
  958. // decode_uri_component still decodes the reserved character.
  959. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  960. }
  961. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  962. string original = "Piri Tommy Villiers - on & on";
  963. string encoded = httplib::encode_uri_component(original);
  964. string decoded = httplib::decode_uri_component(encoded);
  965. EXPECT_EQ(decoded, original);
  966. }
  967. TEST(TrimTests, TrimStringTests) {
  968. EXPECT_EQ("abc", detail::trim_copy("abc"));
  969. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  970. EXPECT_TRUE(detail::trim_copy("").empty());
  971. }
  972. TEST(AsciiTest, LocaleIndependentClassification) {
  973. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  974. // which consult the global C locale: std::isalnum(0xC5) can return true
  975. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  976. // helpers must classify every byte by the ASCII grammar alone.
  977. for (int i = 0; i < 256; i++) {
  978. auto c = static_cast<char>(i);
  979. auto is_digit = i >= '0' && i <= '9';
  980. auto is_upper = i >= 'A' && i <= 'Z';
  981. auto is_lower = i >= 'a' && i <= 'z';
  982. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  983. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  984. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  985. << "byte " << i;
  986. }
  987. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  988. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  989. // Non-ASCII bytes must be percent-encoded, never passed through as
  990. // alphanumeric.
  991. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  992. }
  993. TEST(FromCharsTest, Double) {
  994. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  995. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  996. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  997. auto parse = [](const std::string &s, double &v) {
  998. return detail::from_chars(s.data(), s.data() + s.size(), v);
  999. };
  1000. double v = -1.0;
  1001. // Representative quality values.
  1002. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1003. EXPECT_DOUBLE_EQ(v, 0.0);
  1004. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1005. EXPECT_DOUBLE_EQ(v, 1.0);
  1006. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1007. EXPECT_DOUBLE_EQ(v, 0.8);
  1008. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1009. EXPECT_DOUBLE_EQ(v, 0.001);
  1010. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1011. EXPECT_DOUBLE_EQ(v, 1.0);
  1012. // A missing integer or fractional part is tolerated.
  1013. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1014. EXPECT_DOUBLE_EQ(v, 0.5);
  1015. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1016. EXPECT_DOUBLE_EQ(v, 5.0);
  1017. // Values outside [0, 1] still parse; the caller range-checks them.
  1018. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 123.456);
  1020. // Stops at the first byte that is not part of the number and reports where.
  1021. std::string trailing = "0.9, text/html";
  1022. auto r = parse(trailing, v);
  1023. EXPECT_EQ(r.ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.9);
  1025. EXPECT_EQ(*r.ptr, ',');
  1026. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1027. // outright, and an 'e'/'E' simply ends the number.
  1028. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1029. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1030. std::string exp_input = "1.5e3";
  1031. r = parse(exp_input, v);
  1032. EXPECT_EQ(r.ec, std::errc{});
  1033. EXPECT_DOUBLE_EQ(v, 1.5);
  1034. EXPECT_EQ(*r.ptr, 'e');
  1035. // Invalid inputs.
  1036. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1037. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1038. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1040. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1041. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1042. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1043. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1044. std::errc{});
  1045. EXPECT_DOUBLE_EQ(v, 0.0);
  1046. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1047. std::errc{});
  1048. EXPECT_GE(v, 0.0);
  1049. EXPECT_LE(v, 1.0);
  1050. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1051. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1052. }
  1053. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1054. // Simple case without quality values
  1055. std::vector<std::string> result1;
  1056. EXPECT_TRUE(detail::parse_accept_header(
  1057. "text/html,application/json,text/plain", result1));
  1058. EXPECT_EQ(result1.size(), 3U);
  1059. EXPECT_EQ(result1[0], "text/html");
  1060. EXPECT_EQ(result1[1], "application/json");
  1061. EXPECT_EQ(result1[2], "text/plain");
  1062. // With quality values
  1063. std::vector<std::string> result2;
  1064. EXPECT_TRUE(detail::parse_accept_header(
  1065. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1066. EXPECT_EQ(result2.size(), 3U);
  1067. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1068. EXPECT_EQ(result2[1], "text/html");
  1069. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1070. }
  1071. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1072. // Mixed with and without quality values
  1073. std::vector<std::string> result;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1076. EXPECT_EQ(result.size(), 3U);
  1077. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1078. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1079. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1080. }
  1081. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1082. // Empty header
  1083. std::vector<std::string> empty_result;
  1084. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1085. EXPECT_TRUE(empty_result.empty());
  1086. // Single type
  1087. std::vector<std::string> single_result;
  1088. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1089. EXPECT_EQ(single_result.size(), 1U);
  1090. EXPECT_EQ(single_result[0], "application/json");
  1091. // Wildcard types
  1092. std::vector<std::string> wildcard_result;
  1093. EXPECT_TRUE(detail::parse_accept_header(
  1094. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1095. EXPECT_EQ(wildcard_result.size(), 3U);
  1096. EXPECT_EQ(wildcard_result[0], "application/json");
  1097. EXPECT_EQ(wildcard_result[1], "text/*");
  1098. EXPECT_EQ(wildcard_result[2], "*/*");
  1099. }
  1100. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1101. // Common browser Accept header
  1102. std::vector<std::string> browser_result;
  1103. EXPECT_TRUE(
  1104. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1105. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1106. browser_result));
  1107. EXPECT_EQ(browser_result.size(), 6U);
  1108. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1109. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1110. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1111. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1112. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1113. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1114. // API client header
  1115. std::vector<std::string> api_result;
  1116. EXPECT_TRUE(detail::parse_accept_header(
  1117. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1118. api_result));
  1119. EXPECT_EQ(api_result.size(), 3U);
  1120. EXPECT_EQ(api_result[0], "application/json");
  1121. EXPECT_EQ(api_result[1], "application/xml");
  1122. EXPECT_EQ(api_result[2], "text/plain");
  1123. }
  1124. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1125. // Quality value with 3 decimal places
  1126. std::vector<std::string> decimal_result;
  1127. EXPECT_TRUE(detail::parse_accept_header(
  1128. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1129. EXPECT_EQ(decimal_result.size(), 2U);
  1130. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1131. EXPECT_EQ(decimal_result[1], "text/html");
  1132. // Zero quality (should still be included but with lowest priority)
  1133. std::vector<std::string> zero_q_result;
  1134. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1135. zero_q_result));
  1136. EXPECT_EQ(zero_q_result.size(), 2U);
  1137. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1138. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1139. // No spaces around commas
  1140. std::vector<std::string> no_space_result;
  1141. EXPECT_TRUE(detail::parse_accept_header(
  1142. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1143. no_space_result));
  1144. EXPECT_EQ(no_space_result.size(), 3U);
  1145. EXPECT_EQ(no_space_result[0], "text/html");
  1146. EXPECT_EQ(no_space_result[1], "application/json");
  1147. EXPECT_EQ(no_space_result[2], "text/plain");
  1148. }
  1149. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1150. // Quality values always use '.' as the decimal separator, so parsing must
  1151. // not depend on the process locale. An embedding application may have
  1152. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1153. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1154. std::string saved = cur ? cur : "C";
  1155. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1156. "fr_FR.UTF-8"};
  1157. bool switched = false;
  1158. for (const auto loc : comma_locales) {
  1159. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1160. std::localeconv()->decimal_point[0] == ',') {
  1161. switched = true;
  1162. break;
  1163. }
  1164. }
  1165. if (!switched) {
  1166. std::setlocale(LC_NUMERIC, saved.c_str());
  1167. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1168. }
  1169. // The higher-weighted type appears later in the list, so a correct parse
  1170. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1171. // sensitive parse reads both weights as 0 and leaves the original order.
  1172. std::vector<std::string> result;
  1173. EXPECT_TRUE(detail::parse_accept_header(
  1174. "application/json;q=0.1,text/html;q=0.9", result));
  1175. ASSERT_EQ(result.size(), 2U);
  1176. EXPECT_EQ(result[0], "text/html");
  1177. EXPECT_EQ(result[1], "application/json");
  1178. std::setlocale(LC_NUMERIC, saved.c_str());
  1179. }
  1180. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1181. std::vector<std::string> result;
  1182. // Invalid quality value (> 1.0)
  1183. EXPECT_FALSE(
  1184. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1185. // Invalid quality value (< 0.0)
  1186. EXPECT_FALSE(
  1187. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1188. // Invalid quality value (not a number)
  1189. EXPECT_FALSE(detail::parse_accept_header(
  1190. "text/html;q=invalid,application/json", result));
  1191. // A valid numeric prefix does not make the entire quality value valid.
  1192. EXPECT_FALSE(detail::parse_accept_header(
  1193. "text/html;q=0.5junk,application/json", result));
  1194. // Empty quality value
  1195. EXPECT_FALSE(
  1196. detail::parse_accept_header("text/html;q=,application/json", result));
  1197. // Invalid media type format (no slash and not wildcard)
  1198. EXPECT_FALSE(
  1199. detail::parse_accept_header("invalidtype,application/json", result));
  1200. // Valid cases should still work
  1201. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1202. EXPECT_EQ(result.size(), 1U);
  1203. EXPECT_EQ(result[0], "*/*");
  1204. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1205. EXPECT_EQ(result.size(), 1U);
  1206. EXPECT_EQ(result[0], "*");
  1207. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1208. EXPECT_EQ(result.size(), 1U);
  1209. EXPECT_EQ(result[0], "text/*");
  1210. }
  1211. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1212. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1213. // and must not be answered with 400 Bad Request.
  1214. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1215. struct {
  1216. const char *value;
  1217. std::vector<std::string> expected;
  1218. } cases[] = {
  1219. {",application/json", {"application/json"}},
  1220. {"text/html,", {"text/html"}},
  1221. {"text/html,,*/*", {"text/html", "*/*"}},
  1222. // An empty element may be spelled with whitespace in it
  1223. {"text/html, , application/json", {"text/html", "application/json"}},
  1224. // Nothing but empty elements is an empty list, which means the same
  1225. // thing as no Accept header at all
  1226. {",,,", {}},
  1227. // Quality values still apply across ignored empty elements
  1228. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1229. };
  1230. for (const auto &c : cases) {
  1231. std::vector<std::string> result;
  1232. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1233. << "value: " << c.value;
  1234. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1235. }
  1236. // An invalid entry is still rejected when empty elements surround it
  1237. std::vector<std::string> result;
  1238. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1239. }
  1240. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1241. // or ';' inside one does not end the list element or the parameter. Section
  1242. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1243. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1244. struct {
  1245. const char *value;
  1246. std::vector<std::string> expected;
  1247. } cases[] = {
  1248. {"text/html;profile=\"a,b\",application/json",
  1249. {"text/html", "application/json"}},
  1250. // A "q=" inside a quoted value is not the weight
  1251. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1252. {"text/html", "application/json"}},
  1253. // The weight after a quoted value still applies
  1254. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1255. {"application/json", "text/html"}},
  1256. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1257. {"application/json", "text/html"}},
  1258. {"text/html;profile=\"a\\\"b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // An escaped backslash does not escape the '"' after it
  1261. {"text/html;profile=\"a\\\\\",application/json",
  1262. {"text/html", "application/json"}},
  1263. };
  1264. for (const auto &c : cases) {
  1265. std::vector<std::string> result;
  1266. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1267. << "value: " << c.value;
  1268. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1269. }
  1270. }
  1271. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1272. Server svr;
  1273. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1274. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1275. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1276. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1277. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1278. res.set_content("ok", "text/plain");
  1279. });
  1280. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1281. EXPECT_TRUE(false);
  1282. res.set_content("bad request", "text/plain");
  1283. });
  1284. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1285. auto se = detail::scope_exit([&] {
  1286. svr.stop();
  1287. listen_thread.join();
  1288. ASSERT_FALSE(svr.is_running());
  1289. });
  1290. svr.wait_until_ready();
  1291. Client cli("localhost", PORT);
  1292. {
  1293. auto res = cli.Get(
  1294. "/accept_ok",
  1295. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1297. EXPECT_EQ(StatusCode::OK_200, res->status);
  1298. }
  1299. {
  1300. auto res = cli.Get("/accept_bad_request",
  1301. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1303. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1304. }
  1305. }
  1306. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1307. Server svr;
  1308. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1309. res.set_content("ok", "text/plain");
  1310. });
  1311. std::atomic<int> start_count{0};
  1312. std::atomic<bool> running_when_called{false};
  1313. svr.set_start_handler([&]() {
  1314. running_when_called = svr.is_running();
  1315. start_count++;
  1316. });
  1317. auto port = svr.bind_to_any_port(HOST);
  1318. std::thread t([&]() { svr.listen_after_bind(); });
  1319. auto se = detail::scope_exit([&] {
  1320. svr.stop();
  1321. t.join();
  1322. ASSERT_FALSE(svr.is_running());
  1323. });
  1324. svr.wait_until_ready();
  1325. // A successful request proves the accept loop is running, which the start
  1326. // handler precedes; so by now the handler must have run exactly once.
  1327. Client cli(HOST, port);
  1328. cli.set_connection_timeout(std::chrono::seconds(5));
  1329. auto res = cli.Get("/");
  1330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1331. EXPECT_EQ(StatusCode::OK_200, res->status);
  1332. EXPECT_EQ(1, start_count.load());
  1333. EXPECT_TRUE(running_when_called.load());
  1334. }
  1335. TEST(DivideTest, DivideStringTests) {
  1336. auto divide = [](const std::string &str, char d) {
  1337. std::string lhs;
  1338. std::string rhs;
  1339. detail::divide(str, d,
  1340. [&](const char *lhs_data, std::size_t lhs_size,
  1341. const char *rhs_data, std::size_t rhs_size) {
  1342. lhs.assign(lhs_data, lhs_size);
  1343. rhs.assign(rhs_data, rhs_size);
  1344. });
  1345. return std::make_pair(std::move(lhs), std::move(rhs));
  1346. };
  1347. {
  1348. const auto res = divide("", '=');
  1349. EXPECT_EQ(res.first, "");
  1350. EXPECT_EQ(res.second, "");
  1351. }
  1352. {
  1353. const auto res = divide("=", '=');
  1354. EXPECT_EQ(res.first, "");
  1355. EXPECT_EQ(res.second, "");
  1356. }
  1357. {
  1358. const auto res = divide(" ", '=');
  1359. EXPECT_EQ(res.first, " ");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("a", '=');
  1364. EXPECT_EQ(res.first, "a");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide("a=", '=');
  1369. EXPECT_EQ(res.first, "a");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("=b", '=');
  1374. EXPECT_EQ(res.first, "");
  1375. EXPECT_EQ(res.second, "b");
  1376. }
  1377. {
  1378. const auto res = divide("a=b", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "b");
  1381. }
  1382. {
  1383. const auto res = divide("a=b=", '=');
  1384. EXPECT_EQ(res.first, "a");
  1385. EXPECT_EQ(res.second, "b=");
  1386. }
  1387. {
  1388. const auto res = divide("a=b=c", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b=c");
  1391. }
  1392. }
  1393. TEST(SplitTest, ParseQueryString) {
  1394. string s = "key1=val1&key2=val2&key3=val3";
  1395. Params dic;
  1396. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1397. [&](const char *b, const char *e) {
  1398. string key, val;
  1399. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1400. if (key.empty()) {
  1401. key.assign(b2, e2);
  1402. } else {
  1403. val.assign(b2, e2);
  1404. }
  1405. });
  1406. dic.emplace(key, val);
  1407. });
  1408. EXPECT_EQ("val1", dic.find("key1")->second);
  1409. EXPECT_EQ("val2", dic.find("key2")->second);
  1410. EXPECT_EQ("val3", dic.find("key3")->second);
  1411. }
  1412. TEST(SplitTest, ParseInvalidQueryTests) {
  1413. {
  1414. string s = " ";
  1415. Params dict;
  1416. detail::parse_query_text(s, dict);
  1417. EXPECT_TRUE(dict.empty());
  1418. }
  1419. {
  1420. string s = " = =";
  1421. Params dict;
  1422. detail::parse_query_text(s, dict);
  1423. EXPECT_TRUE(dict.empty());
  1424. }
  1425. }
  1426. TEST(ParseQueryTest, ParseQueryString) {
  1427. {
  1428. std::string s = "key1=val1&key2=val2&key3=val3";
  1429. Params dic;
  1430. detail::parse_query_text(s, dic);
  1431. EXPECT_EQ("val1", dic.find("key1")->second);
  1432. EXPECT_EQ("val2", dic.find("key2")->second);
  1433. EXPECT_EQ("val3", dic.find("key3")->second);
  1434. }
  1435. {
  1436. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1437. Params dic;
  1438. detail::parse_query_text(s, dic);
  1439. EXPECT_EQ("", dic.find("key1")->second);
  1440. EXPECT_EQ("val1", dic.find("key2")->second);
  1441. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1442. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1443. }
  1444. }
  1445. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1446. Params dic;
  1447. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1448. dic.emplace("key1", "val1");
  1449. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1450. dic.emplace("key2", "val2");
  1451. dic.emplace("key3", "val3");
  1452. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1453. }
  1454. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1455. Params params;
  1456. params.emplace("a", "1");
  1457. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1458. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1459. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1460. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1461. // Long enough to overflow the stack when matched with std::regex.
  1462. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1463. EXPECT_EQ("/p?" + long_query + "&a=1",
  1464. append_query_params("/p?" + long_query, params));
  1465. }
  1466. // Joins every entry of a Headers or Params into "key=value " so a whole
  1467. // traversal can be compared in one assertion. Both are instantiations of the
  1468. // same insertion-ordered container, so one helper serves both.
  1469. template <typename Map> static std::string entries_to_string(const Map &m) {
  1470. std::string s;
  1471. for (const auto &entry : m) {
  1472. s += entry.first + "=" + entry.second + " ";
  1473. }
  1474. return s;
  1475. }
  1476. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1477. // Params used to be a std::multimap, which sorted by name and handed the
  1478. // caller's query back alphabetised. A client signing its query string could
  1479. // not reproduce the order it asked for.
  1480. Params dic;
  1481. dic.emplace("zulu", "1");
  1482. dic.emplace("alpha", "2");
  1483. dic.emplace("mike", "3");
  1484. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1485. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1486. }
  1487. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1488. Params dic;
  1489. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1490. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1491. }
  1492. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1493. Request req;
  1494. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1495. req.params);
  1496. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1497. EXPECT_EQ("first", req.get_param_value("tag"));
  1498. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1499. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1500. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1501. EXPECT_EQ("", req.get_param_value("tag", 3));
  1502. }
  1503. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1504. // Params shares its container with Headers, which matches field names
  1505. // case-insensitively. Parameter names must not pick that up.
  1506. Params dic;
  1507. dic.emplace("Key", "upper");
  1508. dic.emplace("key", "lower");
  1509. EXPECT_EQ(2U, dic.size());
  1510. EXPECT_EQ(1U, dic.count("Key"));
  1511. EXPECT_EQ(1U, dic.count("key"));
  1512. EXPECT_EQ("upper", dic.find("Key")->second);
  1513. EXPECT_EQ("lower", dic.find("key")->second);
  1514. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1515. }
  1516. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1517. Server svr;
  1518. std::string order;
  1519. svr.Get("/order", [&](const Request &req, Response &res) {
  1520. order = entries_to_string(req.params);
  1521. res.set_content("ok", "text/plain");
  1522. });
  1523. auto port = svr.bind_to_any_port(HOST);
  1524. thread t = thread([&] { svr.listen_after_bind(); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. t.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, port);
  1532. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1535. }
  1536. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1537. Server svr;
  1538. std::string field_order, file_order;
  1539. svr.Post("/order", [&](const Request &req, Response &res) {
  1540. for (const auto &field : req.form.fields) {
  1541. field_order += field.first + "=" + field.second.content + " ";
  1542. }
  1543. for (const auto &file : req.form.files) {
  1544. file_order += file.first + "=" + file.second.filename + " ";
  1545. }
  1546. res.set_content("ok", "text/plain");
  1547. });
  1548. auto port = svr.bind_to_any_port(HOST);
  1549. thread t = thread([&] { svr.listen_after_bind(); });
  1550. auto se = detail::scope_exit([&] {
  1551. svr.stop();
  1552. t.join();
  1553. ASSERT_FALSE(svr.is_running());
  1554. });
  1555. svr.wait_until_ready();
  1556. UploadFormDataItems items = {
  1557. {"zulu", "1", "", ""},
  1558. {"alpha", "2", "", ""},
  1559. {"mike", "3", "", ""},
  1560. {"zebra", "z", "z.txt", "text/plain"},
  1561. {"apple", "a", "a.txt", "text/plain"},
  1562. };
  1563. Client cli(HOST, port);
  1564. auto res = cli.Post("/order", items);
  1565. ASSERT_TRUE(res);
  1566. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1567. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1568. }
  1569. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1570. Server svr;
  1571. std::vector<std::string> values;
  1572. std::string first, second, out_of_range, order;
  1573. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1574. values = req.form.get_fields("tag");
  1575. first = req.form.get_field("tag", 0);
  1576. second = req.form.get_field("tag", 1);
  1577. out_of_range = req.form.get_field("tag", 2);
  1578. for (const auto &field : req.form.fields) {
  1579. order += field.first + "=" + field.second.content + " ";
  1580. }
  1581. res.set_content("ok", "text/plain");
  1582. });
  1583. auto port = svr.bind_to_any_port(HOST);
  1584. thread t = thread([&] { svr.listen_after_bind(); });
  1585. auto se = detail::scope_exit([&] {
  1586. svr.stop();
  1587. t.join();
  1588. ASSERT_FALSE(svr.is_running());
  1589. });
  1590. svr.wait_until_ready();
  1591. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1592. // not adjacent in the container.
  1593. UploadFormDataItems items = {
  1594. {"tag", "first", "", ""},
  1595. {"other", "x", "", ""},
  1596. {"tag", "second", "", ""},
  1597. };
  1598. Client cli(HOST, port);
  1599. auto res = cli.Post("/repeated", items);
  1600. ASSERT_TRUE(res);
  1601. ASSERT_EQ(2U, values.size());
  1602. EXPECT_EQ("first", values[0]);
  1603. EXPECT_EQ("second", values[1]);
  1604. EXPECT_EQ("first", first);
  1605. EXPECT_EQ("second", second);
  1606. // std::multimap already kept entries sharing a name in insertion order, so
  1607. // everything above passes without this change too. The whole traversal is
  1608. // what tells the two apart: sorting by name would hoist "other" to the front
  1609. // and the two "tag" parts would end up adjacent.
  1610. EXPECT_EQ("tag=first other=x tag=second ", order);
  1611. // Advancing past the last entry of a name used to run off the container;
  1612. // the container's saturating increment makes it return the default instead.
  1613. EXPECT_EQ("", out_of_range);
  1614. }
  1615. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1616. Server svr;
  1617. std::string file_names;
  1618. svr.Post("/upload", [&](const Request &req, Response &res) {
  1619. for (const auto &file : req.form.files) {
  1620. file_names += file.first + "|" + file.second.filename + " ";
  1621. }
  1622. res.set_content("ok", "text/plain");
  1623. });
  1624. auto port = svr.bind_to_any_port(HOST);
  1625. thread t = thread([&] { svr.listen_after_bind(); });
  1626. auto se = detail::scope_exit([&] {
  1627. svr.stop();
  1628. t.join();
  1629. ASSERT_FALSE(svr.is_running());
  1630. });
  1631. svr.wait_until_ready();
  1632. // A trailing backslash would otherwise escape the closing quote.
  1633. UploadFormDataItems items = {
  1634. {"dir\\", "x", "a.txt", "text/plain"},
  1635. {"b", "y", "a\\\\b.txt", "text/plain"},
  1636. };
  1637. Client cli(HOST, port);
  1638. auto res = cli.Post("/upload", items);
  1639. ASSERT_TRUE(res);
  1640. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1641. }
  1642. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1643. // Server::read_content() keeps a FormFields::iterator alive across the
  1644. // content callbacks that fill the part it points at. The container is
  1645. // vector-backed, so a later emplace can reallocate and invalidate an older
  1646. // iterator; 64 parts grow the vector through seven reallocations, which
  1647. // checks that every part's content still lands in its own entry.
  1648. const size_t part_count = 64;
  1649. // One formula for both the parts sent and the values expected back, so the
  1650. // two cannot drift apart.
  1651. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1652. auto content_of = [](size_t i) {
  1653. return std::string(64, static_cast<char>('a' + (i % 26)));
  1654. };
  1655. Server svr;
  1656. std::vector<std::pair<std::string, std::string>> received;
  1657. svr.Post("/many", [&](const Request &req, Response &res) {
  1658. for (const auto &field : req.form.fields) {
  1659. received.emplace_back(field.first, field.second.content);
  1660. }
  1661. res.set_content("ok", "text/plain");
  1662. });
  1663. auto port = svr.bind_to_any_port(HOST);
  1664. thread t = thread([&] { svr.listen_after_bind(); });
  1665. auto se = detail::scope_exit([&] {
  1666. svr.stop();
  1667. t.join();
  1668. ASSERT_FALSE(svr.is_running());
  1669. });
  1670. svr.wait_until_ready();
  1671. UploadFormDataItems items;
  1672. for (size_t i = 0; i < part_count; i++) {
  1673. items.push_back({name_of(i), content_of(i), "", ""});
  1674. }
  1675. Client cli(HOST, port);
  1676. auto res = cli.Post("/many", items);
  1677. ASSERT_TRUE(res);
  1678. ASSERT_EQ(part_count, received.size());
  1679. for (size_t i = 0; i < part_count; i++) {
  1680. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1681. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1682. }
  1683. }
  1684. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1685. string content_type = "multipart/form-data; boundary=something";
  1686. string boundary;
  1687. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1688. EXPECT_TRUE(ret);
  1689. EXPECT_EQ(boundary, "something");
  1690. }
  1691. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1692. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1693. string boundary;
  1694. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1695. EXPECT_TRUE(ret);
  1696. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1697. }
  1698. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1699. string content_type =
  1700. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1701. string boundary;
  1702. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1703. EXPECT_TRUE(ret);
  1704. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1705. }
  1706. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1707. string content_type =
  1708. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1709. string boundary;
  1710. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1711. EXPECT_TRUE(ret);
  1712. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1713. }
  1714. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1715. const string boundary(70, 'a');
  1716. string content_type = "multipart/form-data; boundary=" + boundary;
  1717. string parsed;
  1718. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1719. EXPECT_TRUE(ret);
  1720. EXPECT_EQ(parsed, boundary);
  1721. }
  1722. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1723. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1724. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1725. string parsed;
  1726. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1727. EXPECT_FALSE(ret);
  1728. }
  1729. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1730. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1731. // is 72 characters on the wire and still valid.
  1732. const string boundary(70, 'a');
  1733. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1734. string parsed;
  1735. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1736. EXPECT_EQ(parsed, boundary);
  1737. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1738. parsed.clear();
  1739. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1740. }
  1741. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1742. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1743. // The parameter parser must not treat that '=' as the key/value separator.
  1744. string content_type =
  1745. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1746. "charset=UTF-8";
  1747. string parsed;
  1748. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1749. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1752. // A ';' inside the quoted-string is part of the value, not a parameter
  1753. // separator, so it must not truncate the boundary.
  1754. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1755. string parsed;
  1756. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1757. EXPECT_EQ(parsed, "a;b");
  1758. }
  1759. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1760. string parsed;
  1761. EXPECT_TRUE(detail::parse_multipart_boundary(
  1762. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1763. EXPECT_EQ("a\\b", parsed);
  1764. EXPECT_TRUE(detail::parse_multipart_boundary(
  1765. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1766. EXPECT_EQ("a\"b", parsed);
  1767. }
  1768. TEST(ParseDispositionParamsTest, QuotedValues) {
  1769. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1770. // ';' and '=' are ordinary characters inside one.
  1771. struct {
  1772. const char *value;
  1773. std::vector<std::pair<const char *, const char *>> expected;
  1774. } cases[] = {
  1775. {"name=\"file1\"; filename=\"a.txt\"",
  1776. {{"name", "file1"}, {"filename", "a.txt"}}},
  1777. // Whitespace around '=' and ';' is still trimmed
  1778. {"name=\"file2\" ;filename = \"a.html\"",
  1779. {{"name", "file2"}, {"filename", "a.html"}}},
  1780. // '=' inside the value used to leave only the text after the last one
  1781. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1782. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1783. {"name=\"x=y\"", {{"name", "x=y"}}},
  1784. // ';' inside the value used to truncate the pair and leave a bogus one
  1785. {"name=\"file3\"; filename=\"a;b.txt\"",
  1786. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1787. // An unquoted value keeps working, and so does filename*
  1788. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1789. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1790. // A parameter with no key is dropped rather than turned into one whose
  1791. // key is the value
  1792. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1793. // An escaped quote does not end the value
  1794. {"name=\"a\\\"; filename=evil.php\"",
  1795. {{"name", "a\"; filename=evil.php"}}},
  1796. // Other backslashes, as in a Windows path, are kept
  1797. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1798. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1799. };
  1800. for (const auto &c : cases) {
  1801. Params params;
  1802. detail::parse_disposition_params(c.value, params);
  1803. for (const auto &kv : c.expected) {
  1804. auto it = params.find(kv.first);
  1805. ASSERT_NE(it, params.end())
  1806. << "value: " << c.value << ", key: " << kv.first;
  1807. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1808. }
  1809. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1810. }
  1811. }
  1812. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1813. Server svr;
  1814. std::string filename;
  1815. std::string content;
  1816. svr.Post("/upload", [&](const Request &req, Response &) {
  1817. const auto &file = req.form.get_file("file");
  1818. filename = file.filename;
  1819. content = file.content;
  1820. });
  1821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1822. auto se = detail::scope_exit([&] {
  1823. svr.stop();
  1824. thread.join();
  1825. ASSERT_FALSE(svr.is_running());
  1826. });
  1827. svr.wait_until_ready();
  1828. std::string body = "--B\r\n"
  1829. "Content-Disposition: form-data; name=\"file\"; "
  1830. "filename=\"a.txt\"\r\n"
  1831. "Content-Type: text/plain\r\n"
  1832. "\r\n"
  1833. "hello\r\n"
  1834. "--B--\r\n";
  1835. Client cli(HOST, PORT);
  1836. auto res = cli.Post(
  1837. "/upload",
  1838. [&](size_t offset, DataSink &sink) {
  1839. if (offset < body.size()) {
  1840. sink.write(&body[offset], 1);
  1841. } else {
  1842. sink.done();
  1843. }
  1844. return true;
  1845. },
  1846. "multipart/form-data; boundary=B");
  1847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1848. EXPECT_EQ(StatusCode::OK_200, res->status);
  1849. EXPECT_EQ("a.txt", filename);
  1850. EXPECT_EQ("hello", content);
  1851. }
  1852. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1853. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1854. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1855. Server svr;
  1856. std::string field_value, file_name, file_filename;
  1857. bool has_field = false, has_file = false;
  1858. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1859. has_field = req.form.has_field("x=y");
  1860. field_value = req.form.get_field("x=y");
  1861. has_file = req.form.has_file("file1");
  1862. const auto &file = req.form.get_file("file1");
  1863. file_name = file.name;
  1864. file_filename = file.filename;
  1865. res.set_content("ok", "text/plain");
  1866. });
  1867. auto port = svr.bind_to_any_port(HOST);
  1868. thread t = thread([&] { svr.listen_after_bind(); });
  1869. auto se = detail::scope_exit([&] {
  1870. svr.stop();
  1871. t.join();
  1872. ASSERT_FALSE(svr.is_running());
  1873. });
  1874. svr.wait_until_ready();
  1875. UploadFormDataItems items = {
  1876. {"x=y", "field-value", "", ""},
  1877. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1878. };
  1879. Client cli(HOST, port);
  1880. auto res = cli.Post("/quoted", items);
  1881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1882. ASSERT_EQ(StatusCode::OK_200, res->status);
  1883. EXPECT_TRUE(has_field);
  1884. EXPECT_EQ("field-value", field_value);
  1885. EXPECT_TRUE(has_file);
  1886. EXPECT_EQ("file1", file_name);
  1887. EXPECT_EQ("a;b=report.pdf", file_filename);
  1888. }
  1889. TEST(GetHeaderValueTest, DefaultValue) {
  1890. Headers headers = {{"Dummy", "Dummy"}};
  1891. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1892. EXPECT_STREQ("text/plain", val);
  1893. }
  1894. TEST(GetHeaderValueTest, DefaultValueInt) {
  1895. Headers headers = {{"Dummy", "Dummy"}};
  1896. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1897. EXPECT_EQ(100ull, val);
  1898. }
  1899. TEST(GetHeaderValueTest, RegularValue) {
  1900. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1901. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1902. EXPECT_STREQ("text/html", val);
  1903. }
  1904. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1905. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1906. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1907. EXPECT_STREQ("text/html", val);
  1908. }
  1909. TEST(GetHeaderValueTest, SetContent) {
  1910. Response res;
  1911. res.set_content("html", "text/html");
  1912. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1913. res.set_content("text", "text/plain");
  1914. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1915. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1916. }
  1917. TEST(GetHeaderValueTest, RegularValueInt) {
  1918. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1919. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1920. EXPECT_EQ(100ull, val);
  1921. }
  1922. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1923. Headers headers = {{"Content-Length", "x"}};
  1924. auto is_invalid_value = false;
  1925. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1926. is_invalid_value);
  1927. EXPECT_EQ(0ull, val);
  1928. EXPECT_TRUE(is_invalid_value);
  1929. }
  1930. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1931. // An all-digit value that overflows size_t must be reported as invalid, not
  1932. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1933. // a large length to a small one on 32-bit builds, leaving the framing length
  1934. // wrong while is_invalid_value stayed false.
  1935. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1936. auto is_invalid_value = false;
  1937. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1938. is_invalid_value);
  1939. EXPECT_TRUE(is_invalid_value);
  1940. // A well-formed length is unaffected.
  1941. Headers ok = {{"Content-Length", "1234"}};
  1942. is_invalid_value = false;
  1943. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1944. is_invalid_value);
  1945. EXPECT_EQ(1234ull, val);
  1946. EXPECT_FALSE(is_invalid_value);
  1947. }
  1948. TEST(GetHeaderValueTest, Range) {
  1949. {
  1950. Headers headers = {make_range_header({{1, -1}})};
  1951. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1952. EXPECT_STREQ("bytes=1-", val);
  1953. }
  1954. {
  1955. Headers headers = {make_range_header({{-1, 1}})};
  1956. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1957. EXPECT_STREQ("bytes=-1", val);
  1958. }
  1959. {
  1960. Headers headers = {make_range_header({{1, 10}})};
  1961. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1962. EXPECT_STREQ("bytes=1-10", val);
  1963. }
  1964. {
  1965. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1966. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1967. EXPECT_STREQ("bytes=1-10, 100-", val);
  1968. }
  1969. {
  1970. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1971. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1972. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1973. }
  1974. {
  1975. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1976. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1977. EXPECT_STREQ("bytes=0-0, -1", val);
  1978. }
  1979. }
  1980. TEST(BearerTokenAuthTest, SchemeValidation) {
  1981. // A value shorter than "Bearer " must not throw from the fixed-length
  1982. // substr, and a non-Bearer scheme must not be reported as a token.
  1983. struct {
  1984. const char *value;
  1985. const char *expected;
  1986. } cases[] = {
  1987. {"x", ""},
  1988. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1989. {"Bearer abc123", "abc123"},
  1990. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1991. };
  1992. for (const auto &c : cases) {
  1993. Request req;
  1994. req.set_header("Authorization", c.value);
  1995. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1996. }
  1997. }
  1998. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1999. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2000. // to depend on the standard library (libstdc++ handed back duplicates in
  2001. // reverse insertion order, libc++ in insertion order).
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip");
  2004. req.set_header("Accept-Encoding", "deflate");
  2005. req.set_header("Accept-Encoding", "br");
  2006. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2007. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2008. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2009. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2010. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2011. }
  2012. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2013. Request req;
  2014. req.set_header("X-Test", "only");
  2015. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2016. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2017. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2018. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2019. }
  2020. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2021. Request req;
  2022. req.set_header("X-First", "1");
  2023. req.set_header("X-Test", "2");
  2024. req.params.emplace("first", "1");
  2025. req.params.emplace("test", "2");
  2026. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2027. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2028. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2029. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2030. // The second one is negative when read as a signed value
  2031. const auto max_id = (std::numeric_limits<size_t>::max)();
  2032. for (auto id : {max_id / 2, max_id}) {
  2033. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2034. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2035. EXPECT_EQ("", req.get_param_value("test", id));
  2036. EXPECT_EQ("", req.form.get_field("test", id));
  2037. EXPECT_EQ("", req.form.get_file("test", id).content);
  2038. }
  2039. }
  2040. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2041. Headers headers;
  2042. headers.emplace("Host", "example.com");
  2043. headers.emplace("Accept-Encoding", "gzip");
  2044. headers.emplace("User-Agent", "test");
  2045. headers.emplace("Accept-Encoding", "deflate");
  2046. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2047. "Accept-Encoding=deflate ",
  2048. entries_to_string(headers));
  2049. }
  2050. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2051. Headers headers = {{"Content-Type", "text/html"},
  2052. {"CONTENT-TYPE", "text/xml"}};
  2053. EXPECT_EQ(2U, headers.count("content-type"));
  2054. auto it = headers.find("content-type");
  2055. ASSERT_TRUE(it != headers.end());
  2056. EXPECT_EQ("text/html", it->second);
  2057. }
  2058. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2059. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2060. // drop only those fields and leave everything positioned between them.
  2061. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2062. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2063. auto rng = headers.equal_range("a");
  2064. headers.erase(rng.first, rng.second);
  2065. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2066. }
  2067. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2068. Headers headers = {
  2069. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2070. EXPECT_EQ(3U, headers.erase("A"));
  2071. EXPECT_EQ(0U, headers.count("A"));
  2072. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2073. }
  2074. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2075. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2076. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2077. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2078. }
  2079. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2080. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2081. headers.emplace_front("Host", "example.com");
  2082. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2083. entries_to_string(headers));
  2084. }
  2085. TEST(ParseHeaderValueTest, Range) {
  2086. {
  2087. Ranges ranges;
  2088. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2089. EXPECT_TRUE(ret);
  2090. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2091. }
  2092. {
  2093. Ranges ranges;
  2094. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2095. EXPECT_TRUE(ret);
  2096. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2097. }
  2098. {
  2099. Ranges ranges;
  2100. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2101. EXPECT_TRUE(ret);
  2102. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2103. }
  2104. {
  2105. Ranges ranges;
  2106. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2107. EXPECT_FALSE(ret);
  2108. }
  2109. {
  2110. Ranges ranges;
  2111. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2112. EXPECT_TRUE(ret);
  2113. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2114. }
  2115. {
  2116. Ranges ranges;
  2117. auto ret =
  2118. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2119. EXPECT_TRUE(ret);
  2120. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2121. }
  2122. {
  2123. Ranges ranges;
  2124. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2125. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2126. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,,", ranges));
  2132. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2133. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2134. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2135. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2136. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2137. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2138. EXPECT_FALSE(
  2139. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2140. EXPECT_TRUE(ranges.empty());
  2141. }
  2142. {
  2143. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2144. // remainder of the representation, so it stays accepted.
  2145. Ranges ranges;
  2146. auto ret =
  2147. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2148. EXPECT_TRUE(ret);
  2149. ASSERT_EQ(1u, ranges.size());
  2150. EXPECT_EQ(0, ranges[0].first);
  2151. EXPECT_EQ(-1, ranges[0].second);
  2152. }
  2153. // RFC 9110 14.1: range unit names are case-insensitive.
  2154. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2155. Ranges ranges;
  2156. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2157. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2158. }
  2159. }
  2160. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2161. Request req;
  2162. req.set_header("Accept-Encoding", "gzip");
  2163. Response res;
  2164. res.set_header("Content-Type", "text/plain");
  2165. auto ret = detail::encoding_type(req, res);
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #else
  2169. EXPECT_TRUE(ret == detail::EncodingType::None);
  2170. #endif
  2171. }
  2172. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2173. Request req;
  2174. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2175. Response res;
  2176. res.set_header("Content-Type", "text/plain");
  2177. auto ret = detail::encoding_type(req, res);
  2178. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2179. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2180. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2181. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2182. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2183. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2184. #else
  2185. EXPECT_TRUE(ret == detail::EncodingType::None);
  2186. #endif
  2187. }
  2188. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2189. Request req;
  2190. req.set_header("Accept-Encoding",
  2191. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2192. Response res;
  2193. res.set_header("Content-Type", "text/plain");
  2194. auto ret = detail::encoding_type(req, res);
  2195. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2196. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2197. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2198. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2199. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2200. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2201. #else
  2202. EXPECT_TRUE(ret == detail::EncodingType::None);
  2203. #endif
  2204. }
  2205. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2206. // All supported encodings rejected with q=0 should return None
  2207. Request req;
  2208. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2209. Response res;
  2210. res.set_header("Content-Type", "text/plain");
  2211. auto ret = detail::encoding_type(req, res);
  2212. EXPECT_TRUE(ret == detail::EncodingType::None);
  2213. }
  2214. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2215. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2216. Request req;
  2217. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2218. Response res;
  2219. res.set_header("Content-Type", "text/plain");
  2220. auto ret = detail::encoding_type(req, res);
  2221. EXPECT_TRUE(ret == detail::EncodingType::None);
  2222. }
  2223. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2224. Request req;
  2225. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2226. Response res;
  2227. res.set_header("Content-Type", "text/plain");
  2228. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2229. }
  2230. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2231. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2232. Request req;
  2233. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2234. Response res;
  2235. res.set_header("Content-Type", "text/plain");
  2236. auto ret = detail::encoding_type(req, res);
  2237. EXPECT_TRUE(ret == detail::EncodingType::None);
  2238. }
  2239. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2240. // RFC 7231: Accept-Encoding values are case-insensitive
  2241. Request req;
  2242. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2243. Response res;
  2244. res.set_header("Content-Type", "text/plain");
  2245. auto ret = detail::encoding_type(req, res);
  2246. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2247. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2248. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2249. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2250. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2251. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2252. #else
  2253. EXPECT_TRUE(ret == detail::EncodingType::None);
  2254. #endif
  2255. }
  2256. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2257. // q value should determine priority, not hardcoded order
  2258. Request req;
  2259. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2260. Response res;
  2261. res.set_header("Content-Type", "text/plain");
  2262. auto ret = detail::encoding_type(req, res);
  2263. // gzip has highest q=1.0, so it should be selected even though
  2264. // br and zstd are also supported
  2265. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2266. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2267. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2268. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2269. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2270. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2271. #else
  2272. EXPECT_TRUE(ret == detail::EncodingType::None);
  2273. #endif
  2274. }
  2275. TEST(BufferStreamTest, read) {
  2276. detail::BufferStream strm1;
  2277. Stream &strm = strm1;
  2278. EXPECT_EQ(5, strm.write("hello"));
  2279. char buf[512];
  2280. EXPECT_EQ(2, strm.read(buf, 2));
  2281. EXPECT_EQ('h', buf[0]);
  2282. EXPECT_EQ('e', buf[1]);
  2283. EXPECT_EQ(2, strm.read(buf, 2));
  2284. EXPECT_EQ('l', buf[0]);
  2285. EXPECT_EQ('l', buf[1]);
  2286. EXPECT_EQ(1, strm.read(buf, 1));
  2287. EXPECT_EQ('o', buf[0]);
  2288. EXPECT_EQ(0, strm.read(buf, 1));
  2289. }
  2290. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2291. auto host = "www.httpwatch.com";
  2292. auto ip = hosted_at(host);
  2293. EXPECT_EQ("23.96.13.243", ip);
  2294. std::vector<std::string> addrs;
  2295. hosted_at(host, addrs);
  2296. EXPECT_EQ(1u, addrs.size());
  2297. }
  2298. #if 0 // It depends on each test environment...
  2299. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2300. auto host = "www.youtube.com";
  2301. std::vector<std::string> addrs;
  2302. hosted_at(host, addrs);
  2303. EXPECT_EQ(20u, addrs.size());
  2304. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2305. EXPECT_TRUE(it != addrs.end());
  2306. }
  2307. #endif
  2308. class ChunkedEncodingTest : public ::testing::Test {
  2309. protected:
  2310. ChunkedEncodingTest()
  2311. : cli_(HOST, PORT)
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. ,
  2314. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2315. #endif
  2316. {
  2317. cli_.set_connection_timeout(2);
  2318. #ifdef CPPHTTPLIB_SSL_ENABLED
  2319. cli_.enable_server_certificate_verification(false);
  2320. #endif
  2321. }
  2322. virtual void SetUp() {
  2323. read_file("./image.jpg", image_data_);
  2324. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2325. res.set_content("Hello World!", "text/plain");
  2326. });
  2327. svr_.Get(
  2328. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2329. res.set_chunked_content_provider(
  2330. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2331. size_t remaining = image_data_.size() - offset;
  2332. if (remaining == 0) {
  2333. sink.done();
  2334. } else {
  2335. constexpr size_t CHUNK_SIZE = 1024;
  2336. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2337. sink.write(&image_data_[offset], send_size);
  2338. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2339. }
  2340. return true;
  2341. });
  2342. });
  2343. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2344. svr_.wait_until_ready();
  2345. }
  2346. virtual void TearDown() {
  2347. svr_.stop();
  2348. if (!request_threads_.empty()) {
  2349. std::this_thread::sleep_for(std::chrono::seconds(1));
  2350. for (auto &t : request_threads_) {
  2351. t.join();
  2352. }
  2353. }
  2354. t_.join();
  2355. }
  2356. #ifdef CPPHTTPLIB_SSL_ENABLED
  2357. SSLClient cli_;
  2358. SSLServer svr_;
  2359. #else
  2360. Client cli_;
  2361. Server svr_;
  2362. #endif
  2363. thread t_;
  2364. std::vector<thread> request_threads_;
  2365. std::string image_data_;
  2366. };
  2367. TEST_F(ChunkedEncodingTest, NormalGet) {
  2368. auto res = cli_.Get("/chunked");
  2369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2370. std::string out;
  2371. read_file("./image.jpg", out);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ(out, res->body);
  2374. }
  2375. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2376. std::string body;
  2377. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2378. body.append(data, data_length);
  2379. return true;
  2380. });
  2381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2382. std::string out;
  2383. read_file("./image.jpg", out);
  2384. EXPECT_EQ(StatusCode::OK_200, res->status);
  2385. EXPECT_EQ(out, body);
  2386. }
  2387. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2388. std::string body;
  2389. auto res = cli_.Get(
  2390. "/chunked",
  2391. [&](const Response &response) {
  2392. EXPECT_EQ(StatusCode::OK_200, response.status);
  2393. return true;
  2394. },
  2395. [&](const char *data, size_t data_length) {
  2396. body.append(data, data_length);
  2397. return true;
  2398. });
  2399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2400. std::string out;
  2401. read_file("./image.jpg", out);
  2402. EXPECT_EQ(StatusCode::OK_200, res->status);
  2403. EXPECT_EQ(out, body);
  2404. }
  2405. TEST(RangeTest, FromHTTPBin_Online) {
  2406. auto host = "httpbingo.org";
  2407. auto path = std::string{"/range/32"};
  2408. #ifdef CPPHTTPLIB_SSL_ENABLED
  2409. auto port = 443;
  2410. SSLClient cli(host, port);
  2411. #else
  2412. auto port = 80;
  2413. Client cli(host, port);
  2414. #endif
  2415. cli.set_connection_timeout(5);
  2416. {
  2417. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  2418. SKIP_ON_GATEWAY_ERROR(res);
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. }
  2423. {
  2424. Headers headers = {make_range_header({{1, -1}})};
  2425. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2426. SKIP_ON_GATEWAY_ERROR(res);
  2427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2428. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2430. }
  2431. {
  2432. Headers headers = {make_range_header({{1, 10}})};
  2433. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2434. SKIP_ON_GATEWAY_ERROR(res);
  2435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2436. EXPECT_EQ("bcdefghijk", res->body);
  2437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2438. }
  2439. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2440. // entire resource, while the original httpbin returned 200. Both are
  2441. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2442. {
  2443. Headers headers = {make_range_header({{0, 31}})};
  2444. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2445. SKIP_ON_GATEWAY_ERROR(res);
  2446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2447. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2448. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2449. res->status == StatusCode::PartialContent_206);
  2450. }
  2451. {
  2452. Headers headers = {make_range_header({{0, -1}})};
  2453. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2454. SKIP_ON_GATEWAY_ERROR(res);
  2455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2456. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2457. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2458. res->status == StatusCode::PartialContent_206);
  2459. }
  2460. // go-httpbin returns 206 with clamped range for over-range requests,
  2461. // while the original httpbin returned 416. Both behaviors are observed
  2462. // in real servers, so we only verify the request succeeds.
  2463. {
  2464. Headers headers = {make_range_header({{0, 32}})};
  2465. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2466. SKIP_ON_GATEWAY_ERROR(res);
  2467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2468. }
  2469. }
  2470. TEST(RangeTest, IgnoredForPost) {
  2471. Server svr;
  2472. svr.Post("/", [](const Request &, Response &res) {
  2473. res.set_content("abcdefg", "text/plain");
  2474. });
  2475. auto port = svr.bind_to_any_port(HOST);
  2476. ASSERT_GT(port, 0);
  2477. thread t = thread([&] { svr.listen_after_bind(); });
  2478. auto se = detail::scope_exit([&] {
  2479. svr.stop();
  2480. t.join();
  2481. ASSERT_FALSE(svr.is_running());
  2482. });
  2483. svr.wait_until_ready();
  2484. Client cli(HOST, port);
  2485. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2486. auto res = cli.Post("/", Headers{{"Range", range}});
  2487. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2488. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2489. EXPECT_EQ("abcdefg", res->body) << range;
  2490. }
  2491. }
  2492. TEST(RangeTest, IgnoredForUnknownUnit) {
  2493. Server svr;
  2494. svr.Get("/", [](const Request &, Response &res) {
  2495. res.set_content("abcdefg", "text/plain");
  2496. });
  2497. auto port = svr.bind_to_any_port(HOST);
  2498. ASSERT_GT(port, 0);
  2499. thread t = thread([&] { svr.listen_after_bind(); });
  2500. auto se = detail::scope_exit([&] {
  2501. svr.stop();
  2502. t.join();
  2503. ASSERT_FALSE(svr.is_running());
  2504. });
  2505. svr.wait_until_ready();
  2506. Client cli(HOST, port);
  2507. for (auto range : {"items=1-2", "none=x"}) {
  2508. auto res = cli.Get("/", Headers{{"Range", range}});
  2509. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2510. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2511. EXPECT_EQ("abcdefg", res->body) << range;
  2512. }
  2513. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2514. ASSERT_TRUE(res) << to_string(res.error());
  2515. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2516. }
  2517. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2518. auto host = "unresolvableaddress.local";
  2519. auto path = std::string{"/"};
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 443;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 80;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(1);
  2528. {
  2529. auto res = cli.Get(path);
  2530. ASSERT_FALSE(res);
  2531. }
  2532. std::this_thread::sleep_for(std::chrono::seconds(8));
  2533. }
  2534. #if defined(__linux__) && defined(__GLIBC__) && \
  2535. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2536. // Forward declaration: in split builds split.py strips `inline` and moves the
  2537. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2538. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2539. // against the symbol in both header-only and split builds.
  2540. namespace httplib {
  2541. namespace detail {
  2542. int getaddrinfo_with_timeout(const char *node, const char *service,
  2543. const struct addrinfo *hints,
  2544. struct addrinfo **res, time_t timeout_sec);
  2545. } // namespace detail
  2546. } // namespace httplib
  2547. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2548. //
  2549. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2550. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2551. // gai_suspend() call hits the connection timeout the function calls
  2552. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2553. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2554. // still alive and still references the now-destroyed stack frame.
  2555. //
  2556. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2557. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2558. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2559. // and runs them in a container.
  2560. namespace {
  2561. bool should_run_issue_2431_tests() {
  2562. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2563. return v && *v && std::string(v) != "0";
  2564. }
  2565. std::string unique_unresolvable_host(int n) {
  2566. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2567. // glibc still asks the configured nameserver — which is exactly the path
  2568. // we want to exercise. A unique label per call avoids the resolver cache.
  2569. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2570. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2571. std::to_string(n) + ".invalid";
  2572. }
  2573. } // namespace
  2574. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2575. if (!should_run_issue_2431_tests()) {
  2576. GTEST_SKIP()
  2577. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2578. }
  2579. for (int i = 0; i < 8; ++i) {
  2580. struct addrinfo hints;
  2581. memset(&hints, 0, sizeof(hints));
  2582. hints.ai_family = AF_UNSPEC;
  2583. hints.ai_socktype = SOCK_STREAM;
  2584. auto host = unique_unresolvable_host(i);
  2585. struct addrinfo *result = nullptr;
  2586. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2587. &result, /*timeout_sec=*/1);
  2588. if (rc == 0 && result) { freeaddrinfo(result); }
  2589. }
  2590. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2591. // stack region they still believe holds their gaicb.
  2592. std::this_thread::sleep_for(std::chrono::seconds(3));
  2593. }
  2594. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2595. if (!should_run_issue_2431_tests()) {
  2596. GTEST_SKIP()
  2597. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2598. }
  2599. std::atomic<bool> stop{false};
  2600. std::vector<std::thread> threads;
  2601. for (int t = 0; t < 8; ++t) {
  2602. threads.emplace_back([t, &stop] {
  2603. int i = 0;
  2604. while (!stop.load(std::memory_order_relaxed)) {
  2605. struct addrinfo hints;
  2606. memset(&hints, 0, sizeof(hints));
  2607. hints.ai_family = AF_UNSPEC;
  2608. hints.ai_socktype = SOCK_STREAM;
  2609. auto host = unique_unresolvable_host(t * 100000 + i++);
  2610. struct addrinfo *result = nullptr;
  2611. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2612. &result, /*timeout_sec=*/1);
  2613. if (rc == 0 && result) { freeaddrinfo(result); }
  2614. }
  2615. });
  2616. }
  2617. std::this_thread::sleep_for(std::chrono::seconds(8));
  2618. stop.store(true, std::memory_order_relaxed);
  2619. for (auto &th : threads) {
  2620. th.join();
  2621. }
  2622. std::this_thread::sleep_for(std::chrono::seconds(3));
  2623. }
  2624. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2625. if (!should_run_issue_2431_tests()) {
  2626. GTEST_SKIP()
  2627. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2628. }
  2629. std::atomic<bool> stop{false};
  2630. std::vector<std::thread> threads;
  2631. for (int t = 0; t < 8; ++t) {
  2632. threads.emplace_back([t, &stop] {
  2633. int i = 0;
  2634. while (!stop.load(std::memory_order_relaxed)) {
  2635. auto host = unique_unresolvable_host(t * 100000 + i++);
  2636. Client cli(host, 80);
  2637. cli.set_connection_timeout(1, 0);
  2638. cli.set_read_timeout(1, 0);
  2639. cli.set_write_timeout(1, 0);
  2640. (void)cli.Get("/");
  2641. }
  2642. });
  2643. }
  2644. std::this_thread::sleep_for(std::chrono::seconds(8));
  2645. stop.store(true, std::memory_order_relaxed);
  2646. for (auto &th : threads) {
  2647. th.join();
  2648. }
  2649. std::this_thread::sleep_for(std::chrono::seconds(3));
  2650. }
  2651. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2652. TEST(ConnectionErrorTest, InvalidHost) {
  2653. auto host = "-abcde.com";
  2654. #ifdef CPPHTTPLIB_SSL_ENABLED
  2655. auto port = 443;
  2656. SSLClient cli(host, port);
  2657. #else
  2658. auto port = 80;
  2659. Client cli(host, port);
  2660. #endif
  2661. cli.set_connection_timeout(std::chrono::seconds(2));
  2662. auto res = cli.Get("/");
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_EQ(Error::Connection, res.error());
  2665. }
  2666. TEST(ConnectionErrorTest, InvalidHost2) {
  2667. auto host = "httpcan.org/";
  2668. #ifdef CPPHTTPLIB_SSL_ENABLED
  2669. SSLClient cli(host);
  2670. #else
  2671. Client cli(host);
  2672. #endif
  2673. cli.set_connection_timeout(std::chrono::seconds(2));
  2674. auto res = cli.Get("/");
  2675. ASSERT_TRUE(!res);
  2676. EXPECT_EQ(Error::Connection, res.error());
  2677. }
  2678. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2679. auto host = "httpcan.org/";
  2680. #ifdef CPPHTTPLIB_SSL_ENABLED
  2681. SSLClient cli(host);
  2682. #else
  2683. Client cli(host);
  2684. #endif
  2685. cli.set_connection_timeout(std::chrono::seconds(2));
  2686. auto res = cli.Get("/");
  2687. ASSERT_TRUE(!res);
  2688. stringstream s;
  2689. s << "error code: " << res.error();
  2690. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2691. }
  2692. TEST(ConnectionErrorTest, InvalidPort) {
  2693. auto host = "localhost";
  2694. auto port = 44380;
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. SSLClient cli(host, port);
  2697. #else
  2698. Client cli(host, port);
  2699. #endif
  2700. cli.set_connection_timeout(std::chrono::seconds(2));
  2701. auto res = cli.Get("/");
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_TRUE(Error::Connection == res.error() ||
  2704. Error::ConnectionTimeout == res.error());
  2705. }
  2706. TEST(ConnectionErrorTest, Timeout_Online) {
  2707. auto host = "google.com";
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. auto port = 44380;
  2710. SSLClient cli(host, port);
  2711. #else
  2712. auto port = 8080;
  2713. Client cli(host, port);
  2714. #endif
  2715. cli.set_connection_timeout(std::chrono::seconds(2));
  2716. // only probe one address type so that the error reason
  2717. // correlates to the timed-out IPv4, not the unsupported
  2718. // IPv6 connection attempt
  2719. cli.set_address_family(AF_INET);
  2720. auto res = cli.Get("/");
  2721. ASSERT_TRUE(!res);
  2722. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2723. }
  2724. TEST(CancelTest, NoCancel_Online) {
  2725. auto host = "httpbingo.org";
  2726. auto path = std::string{"/range/32"};
  2727. #ifdef CPPHTTPLIB_SSL_ENABLED
  2728. auto port = 443;
  2729. SSLClient cli(host, port);
  2730. #else
  2731. auto port = 80;
  2732. Client cli(host, port);
  2733. #endif
  2734. cli.set_connection_timeout(std::chrono::seconds(5));
  2735. auto res = retry_gateway_errors(
  2736. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2737. SKIP_ON_GATEWAY_ERROR(res);
  2738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2739. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. }
  2742. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2743. // Use /bytes with a large payload so that the DownloadProgress callback
  2744. // (which only fires for Content-Length responses) is invoked before the
  2745. // entire body is received, giving cancellation a chance to fire.
  2746. auto host = "httpbingo.org";
  2747. auto path = std::string{"/bytes/524288"};
  2748. #ifdef CPPHTTPLIB_SSL_ENABLED
  2749. auto port = 443;
  2750. SSLClient cli(host, port);
  2751. #else
  2752. auto port = 80;
  2753. Client cli(host, port);
  2754. #endif
  2755. auto res = retry_gateway_errors(
  2756. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2757. SKIP_ON_GATEWAY_ERROR(res);
  2758. cli.set_connection_timeout(std::chrono::seconds(5));
  2759. ASSERT_TRUE(!res);
  2760. EXPECT_EQ(Error::Canceled, res.error());
  2761. }
  2762. TEST(CancelTest, WithCancelLargePayload_Online) {
  2763. auto host = "httpbingo.org";
  2764. auto path = std::string{"/bytes/524288"};
  2765. #ifdef CPPHTTPLIB_SSL_ENABLED
  2766. auto port = 443;
  2767. SSLClient cli(host, port);
  2768. #else
  2769. auto port = 80;
  2770. Client cli(host, port);
  2771. #endif
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res = retry_gateway_errors([&] {
  2774. auto count = 0;
  2775. return cli.Get(path,
  2776. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2777. });
  2778. SKIP_ON_GATEWAY_ERROR(res);
  2779. ASSERT_TRUE(!res);
  2780. EXPECT_EQ(Error::Canceled, res.error());
  2781. }
  2782. TEST(CancelTest, NoCancelPost) {
  2783. Server svr;
  2784. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content("Hello World!", "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_connection_timeout(std::chrono::seconds(5));
  2796. auto res =
  2797. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2798. "application/json", [](uint64_t, uint64_t) { return true; });
  2799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2800. EXPECT_EQ("Hello World!", res->body);
  2801. EXPECT_EQ(StatusCode::OK_200, res->status);
  2802. }
  2803. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2804. Server svr;
  2805. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2809. auto se = detail::scope_exit([&] {
  2810. svr.stop();
  2811. thread.join();
  2812. ASSERT_FALSE(svr.is_running());
  2813. });
  2814. svr.wait_until_ready();
  2815. Client cli(HOST, PORT);
  2816. cli.set_connection_timeout(std::chrono::seconds(5));
  2817. auto res =
  2818. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2819. "application/json", [](uint64_t, uint64_t) { return false; });
  2820. ASSERT_TRUE(!res);
  2821. EXPECT_EQ(Error::Canceled, res.error());
  2822. }
  2823. TEST(CancelTest, WithCancelLargePayloadPost) {
  2824. Server svr;
  2825. svr.set_payload_max_length(200 * 1024 * 1024);
  2826. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2827. res.set_content(LARGE_DATA, "text/plain");
  2828. });
  2829. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2830. auto se = detail::scope_exit([&] {
  2831. svr.stop();
  2832. thread.join();
  2833. ASSERT_FALSE(svr.is_running());
  2834. });
  2835. svr.wait_until_ready();
  2836. Client cli(HOST, PORT);
  2837. cli.set_payload_max_length(200 * 1024 * 1024);
  2838. cli.set_connection_timeout(std::chrono::seconds(5));
  2839. auto res =
  2840. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2841. "application/json", [](uint64_t, uint64_t) { return false; });
  2842. ASSERT_TRUE(!res);
  2843. EXPECT_EQ(Error::Canceled, res.error());
  2844. }
  2845. TEST(CancelTest, NoCancelPut) {
  2846. Server svr;
  2847. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2848. res.set_content("Hello World!", "text/plain");
  2849. });
  2850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2851. auto se = detail::scope_exit([&] {
  2852. svr.stop();
  2853. thread.join();
  2854. ASSERT_FALSE(svr.is_running());
  2855. });
  2856. svr.wait_until_ready();
  2857. Client cli(HOST, PORT);
  2858. cli.set_connection_timeout(std::chrono::seconds(5));
  2859. auto res =
  2860. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2861. "application/json", [](uint64_t, uint64_t) { return true; });
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. EXPECT_EQ("Hello World!", res->body);
  2864. EXPECT_EQ(StatusCode::OK_200, res->status);
  2865. }
  2866. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2867. Server svr;
  2868. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2869. res.set_content("Hello World!", "text/plain");
  2870. });
  2871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2872. auto se = detail::scope_exit([&] {
  2873. svr.stop();
  2874. thread.join();
  2875. ASSERT_FALSE(svr.is_running());
  2876. });
  2877. svr.wait_until_ready();
  2878. Client cli(HOST, PORT);
  2879. cli.set_connection_timeout(std::chrono::seconds(5));
  2880. auto res =
  2881. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2882. "application/json", [](uint64_t, uint64_t) { return false; });
  2883. ASSERT_TRUE(!res);
  2884. EXPECT_EQ(Error::Canceled, res.error());
  2885. }
  2886. TEST(CancelTest, WithCancelLargePayloadPut) {
  2887. Server svr;
  2888. svr.set_payload_max_length(200 * 1024 * 1024);
  2889. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2890. res.set_content(LARGE_DATA, "text/plain");
  2891. });
  2892. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2893. auto se = detail::scope_exit([&] {
  2894. svr.stop();
  2895. thread.join();
  2896. ASSERT_FALSE(svr.is_running());
  2897. });
  2898. svr.wait_until_ready();
  2899. Client cli(HOST, PORT);
  2900. cli.set_payload_max_length(200 * 1024 * 1024);
  2901. cli.set_connection_timeout(std::chrono::seconds(5));
  2902. auto res =
  2903. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2904. "application/json", [](uint64_t, uint64_t) { return false; });
  2905. ASSERT_TRUE(!res);
  2906. EXPECT_EQ(Error::Canceled, res.error());
  2907. }
  2908. TEST(CancelTest, NoCancelPatch) {
  2909. Server svr;
  2910. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2911. res.set_content("Hello World!", "text/plain");
  2912. });
  2913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2914. auto se = detail::scope_exit([&] {
  2915. svr.stop();
  2916. thread.join();
  2917. ASSERT_FALSE(svr.is_running());
  2918. });
  2919. svr.wait_until_ready();
  2920. Client cli(HOST, PORT);
  2921. cli.set_connection_timeout(std::chrono::seconds(5));
  2922. auto res =
  2923. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2924. "application/json", [](uint64_t, uint64_t) { return true; });
  2925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2926. EXPECT_EQ("Hello World!", res->body);
  2927. EXPECT_EQ(StatusCode::OK_200, res->status);
  2928. }
  2929. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2930. Server svr;
  2931. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2932. res.set_content("Hello World!", "text/plain");
  2933. });
  2934. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2935. auto se = detail::scope_exit([&] {
  2936. svr.stop();
  2937. thread.join();
  2938. ASSERT_FALSE(svr.is_running());
  2939. });
  2940. svr.wait_until_ready();
  2941. Client cli(HOST, PORT);
  2942. cli.set_connection_timeout(std::chrono::seconds(5));
  2943. auto res =
  2944. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2945. "application/json", [](uint64_t, uint64_t) { return false; });
  2946. ASSERT_TRUE(!res);
  2947. EXPECT_EQ(Error::Canceled, res.error());
  2948. }
  2949. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2950. Server svr;
  2951. svr.set_payload_max_length(200 * 1024 * 1024);
  2952. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2953. res.set_content(LARGE_DATA, "text/plain");
  2954. });
  2955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2956. auto se = detail::scope_exit([&] {
  2957. svr.stop();
  2958. thread.join();
  2959. ASSERT_FALSE(svr.is_running());
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, PORT);
  2963. cli.set_payload_max_length(200 * 1024 * 1024);
  2964. cli.set_connection_timeout(std::chrono::seconds(5));
  2965. auto res =
  2966. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2967. "application/json", [](uint64_t, uint64_t) { return false; });
  2968. ASSERT_TRUE(!res);
  2969. EXPECT_EQ(Error::Canceled, res.error());
  2970. }
  2971. TEST(CancelTest, NoCancelDelete) {
  2972. Server svr;
  2973. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2974. res.set_content("Hello World!", "text/plain");
  2975. });
  2976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. thread.join();
  2980. ASSERT_FALSE(svr.is_running());
  2981. });
  2982. svr.wait_until_ready();
  2983. Client cli(HOST, PORT);
  2984. cli.set_connection_timeout(std::chrono::seconds(5));
  2985. auto res =
  2986. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2987. "application/json", [](uint64_t, uint64_t) { return true; });
  2988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2989. EXPECT_EQ("Hello World!", res->body);
  2990. EXPECT_EQ(StatusCode::OK_200, res->status);
  2991. }
  2992. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2993. Server svr;
  2994. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2995. res.set_content("Hello World!", "text/plain");
  2996. });
  2997. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2998. auto se = detail::scope_exit([&] {
  2999. svr.stop();
  3000. thread.join();
  3001. ASSERT_FALSE(svr.is_running());
  3002. });
  3003. svr.wait_until_ready();
  3004. Client cli(HOST, PORT);
  3005. cli.set_connection_timeout(std::chrono::seconds(5));
  3006. auto res =
  3007. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3008. "application/json", [](uint64_t, uint64_t) { return false; });
  3009. ASSERT_TRUE(!res);
  3010. EXPECT_EQ(Error::Canceled, res.error());
  3011. }
  3012. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3013. Server svr;
  3014. svr.set_payload_max_length(200 * 1024 * 1024);
  3015. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3016. res.set_content(LARGE_DATA, "text/plain");
  3017. });
  3018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3019. auto se = detail::scope_exit([&] {
  3020. svr.stop();
  3021. thread.join();
  3022. ASSERT_FALSE(svr.is_running());
  3023. });
  3024. svr.wait_until_ready();
  3025. Client cli(HOST, PORT);
  3026. cli.set_payload_max_length(200 * 1024 * 1024);
  3027. cli.set_connection_timeout(std::chrono::seconds(5));
  3028. auto res =
  3029. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3030. "application/json", [](uint64_t, uint64_t) { return false; });
  3031. ASSERT_TRUE(!res);
  3032. EXPECT_EQ(Error::Canceled, res.error());
  3033. }
  3034. // One stop() from another thread ends a request that waits for the response
  3035. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3036. Server svr;
  3037. std::atomic<bool> received{false};
  3038. std::atomic<bool> done{false};
  3039. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3040. received.store(true);
  3041. while (!done.load()) {
  3042. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3043. }
  3044. res.set_content("Hello World!", "text/plain");
  3045. });
  3046. auto port = svr.bind_to_any_port(HOST);
  3047. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3048. Client cli(HOST, port);
  3049. cli.set_read_timeout(std::chrono::seconds(30));
  3050. std::future<Result> request;
  3051. auto se = detail::scope_exit([&] {
  3052. done.store(true);
  3053. svr.stop();
  3054. thread.join();
  3055. ASSERT_FALSE(svr.is_running());
  3056. });
  3057. svr.wait_until_ready();
  3058. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3059. for (int i = 0; i < 500 && !received.load(); ++i) {
  3060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3061. }
  3062. ASSERT_TRUE(received.load());
  3063. // Let the client block in the wait for the response
  3064. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3065. auto start = std::chrono::steady_clock::now();
  3066. cli.stop();
  3067. ASSERT_EQ(std::future_status::ready,
  3068. request.wait_for(std::chrono::seconds(5)));
  3069. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3070. auto res = request.get();
  3071. ASSERT_TRUE(!res);
  3072. EXPECT_EQ(Error::Read, res.error());
  3073. }
  3074. // A listener whose backlog completes the TCP connections of clients, and that
  3075. // never answers them
  3076. struct SilentListener {
  3077. socket_t sock = INVALID_SOCKET;
  3078. sockaddr_in addr{};
  3079. int port = 0;
  3080. explicit SilentListener(int backlog = 1) {
  3081. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3082. addr.sin_family = AF_INET;
  3083. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3084. socklen_t len = sizeof(addr);
  3085. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3086. ::listen(sock, backlog) != 0 ||
  3087. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3088. detail::close_socket(sock);
  3089. sock = INVALID_SOCKET;
  3090. }
  3091. port = ntohs(addr.sin_port);
  3092. }
  3093. ~SilentListener() { detail::close_socket(sock); }
  3094. // The next connection, whose reads give up after 5 seconds
  3095. socket_t accept() const {
  3096. auto peer = ::accept(sock, nullptr, nullptr);
  3097. if (peer != INVALID_SOCKET) {
  3098. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3099. }
  3100. return peer;
  3101. }
  3102. };
  3103. static bool receives_a_byte(socket_t peer) {
  3104. char c = 0;
  3105. return detail::read_socket(peer, &c, 1, 0) == 1;
  3106. }
  3107. // Runs op, stops cli once the listener receives the first byte op sends, and
  3108. // expects op to end with error soon after
  3109. template <typename ClientType, typename Op>
  3110. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3111. Op op, Error error = Error::Canceled) {
  3112. auto ended = std::async(std::launch::async, op);
  3113. auto peer = listener.accept();
  3114. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3115. ASSERT_NE(INVALID_SOCKET, peer);
  3116. ASSERT_TRUE(receives_a_byte(peer));
  3117. cli.stop();
  3118. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3119. EXPECT_EQ(error, ended.get());
  3120. }
  3121. // Stops itself from another thread as the connection opens, the last moment a
  3122. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3123. // waits for the connection fails the test instead of hanging it.
  3124. class StoppedAsConnectedClient : public ClientImpl {
  3125. public:
  3126. using ClientImpl::ClientImpl;
  3127. protected:
  3128. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3129. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3130. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3131. stopper_.wait_for(std::chrono::seconds(1));
  3132. return true;
  3133. }
  3134. private:
  3135. std::future<void> stopper_;
  3136. };
  3137. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3138. SilentListener listener;
  3139. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3140. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3141. cli.set_read_timeout(std::chrono::seconds(3));
  3142. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3143. auto peer = listener.accept();
  3144. EXPECT_FALSE(receives_a_byte(peer));
  3145. detail::close_socket(peer);
  3146. auto handle = cli.open_stream("GET", "/");
  3147. EXPECT_FALSE(handle.is_valid());
  3148. EXPECT_EQ(Error::Canceled, handle.error);
  3149. peer = listener.accept();
  3150. EXPECT_FALSE(receives_a_byte(peer));
  3151. detail::close_socket(peer);
  3152. }
  3153. #ifdef __linux__
  3154. // A connect that a listener with a full backlog never completes
  3155. TEST(ClientStopTest, StopEndsAConnect) {
  3156. SilentListener listener(0);
  3157. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3158. std::vector<socket_t> backlog;
  3159. auto close_backlog = detail::scope_exit([&] {
  3160. for (auto sock : backlog) {
  3161. detail::close_socket(sock);
  3162. }
  3163. });
  3164. for (int i = 0; i < 8; i++) {
  3165. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3166. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3167. sizeof(listener.addr));
  3168. backlog.push_back(sock);
  3169. }
  3170. Client cli("127.0.0.1", listener.port);
  3171. cli.set_connection_timeout(std::chrono::seconds(3));
  3172. auto ended =
  3173. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3174. // A stop() before the request starts does not apply to it, so it repeats
  3175. auto status = std::future_status::timeout;
  3176. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3177. cli.stop();
  3178. status = ended.wait_for(std::chrono::milliseconds(10));
  3179. }
  3180. EXPECT_EQ(std::future_status::ready, status);
  3181. EXPECT_EQ(Error::Canceled, ended.get());
  3182. }
  3183. #endif
  3184. // The stream holds the socket while it waits for the head, out of the reach
  3185. // of shutdown()
  3186. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3187. SilentListener listener;
  3188. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3189. Client cli("127.0.0.1", listener.port);
  3190. cli.set_read_timeout(std::chrono::seconds(3));
  3191. expect_stop_ends(
  3192. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3193. Error::Read);
  3194. }
  3195. #ifdef CPPHTTPLIB_SSL_ENABLED
  3196. // A server that never answers the ClientHello
  3197. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3198. SilentListener listener;
  3199. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3200. SSLClient cli("127.0.0.1", listener.port);
  3201. cli.enable_server_certificate_verification(false);
  3202. cli.set_connection_timeout(std::chrono::seconds(3));
  3203. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3204. expect_stop_ends(cli, listener,
  3205. [&] { return cli.open_stream("GET", "/").error; });
  3206. }
  3207. // A proxy that takes the CONNECT and never answers it
  3208. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3209. SilentListener listener;
  3210. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3211. SSLClient cli("example.com", 443);
  3212. cli.set_proxy("127.0.0.1", listener.port);
  3213. cli.set_read_timeout(std::chrono::seconds(3));
  3214. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3215. }
  3216. #endif
  3217. // A read timeout past what the clock reaches waits for the response
  3218. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3219. SilentListener listener;
  3220. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3221. Client cli("127.0.0.1", listener.port);
  3222. cli.set_read_timeout(
  3223. static_cast<time_t>((std::min)(static_cast<long long>(
  3224. (std::numeric_limits<time_t>::max)()),
  3225. 10000000000LL)),
  3226. 0);
  3227. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3228. auto peer = listener.accept();
  3229. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3230. ASSERT_NE(INVALID_SOCKET, peer);
  3231. ASSERT_TRUE(receives_a_byte(peer));
  3232. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3233. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3234. "Connection: close\r\n\r\nok";
  3235. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3236. auto result = res.get();
  3237. ASSERT_TRUE(result);
  3238. EXPECT_EQ("ok", result->body);
  3239. }
  3240. static std::string remove_whitespace(const std::string &input) {
  3241. std::string output;
  3242. output.reserve(input.size());
  3243. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3244. [](unsigned char c) { return !std::isspace(c); });
  3245. return output;
  3246. }
  3247. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3248. auto host = "httpbingo.org";
  3249. auto path = std::string{"/basic-auth/hello/world"};
  3250. #ifdef CPPHTTPLIB_SSL_ENABLED
  3251. auto port = 443;
  3252. SSLClient cli(host, port);
  3253. #else
  3254. auto port = 80;
  3255. Client cli(host, port);
  3256. #endif
  3257. {
  3258. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3259. SKIP_ON_GATEWAY_ERROR(res);
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3262. }
  3263. {
  3264. auto res = retry_gateway_errors([&] {
  3265. return cli.Get(
  3266. path, Headers{make_basic_authentication_header("hello", "world")});
  3267. });
  3268. SKIP_ON_GATEWAY_ERROR(res);
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. auto body = remove_whitespace(res->body);
  3271. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3272. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3273. EXPECT_EQ(StatusCode::OK_200, res->status);
  3274. }
  3275. {
  3276. cli.set_basic_auth("hello", "world");
  3277. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3278. SKIP_ON_GATEWAY_ERROR(res);
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. auto body = remove_whitespace(res->body);
  3281. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3282. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. }
  3285. {
  3286. cli.set_basic_auth("hello", "bad");
  3287. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3288. SKIP_ON_GATEWAY_ERROR(res);
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3291. }
  3292. {
  3293. cli.set_basic_auth("bad", "world");
  3294. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3295. SKIP_ON_GATEWAY_ERROR(res);
  3296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3297. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3298. }
  3299. }
  3300. #ifdef CPPHTTPLIB_SSL_ENABLED
  3301. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3302. auto host = "httpbingo.org";
  3303. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3304. auto paths = std::vector<std::string>{
  3305. "/digest-auth/auth/hello/world/MD5",
  3306. "/digest-auth/auth/hello/world/SHA-256",
  3307. };
  3308. auto port = 443;
  3309. SSLClient cli(host, port);
  3310. {
  3311. auto res = retry_gateway_errors([&] { return cli.Get(unauth_path); });
  3312. SKIP_ON_GATEWAY_ERROR(res);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3315. }
  3316. {
  3317. cli.set_digest_auth("hello", "world");
  3318. for (const auto &path : paths) {
  3319. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3320. SKIP_ON_GATEWAY_ERROR(res);
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. auto body = remove_whitespace(res->body);
  3323. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3324. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3325. EXPECT_EQ(StatusCode::OK_200, res->status);
  3326. }
  3327. cli.set_digest_auth("hello", "bad");
  3328. for (const auto &path : paths) {
  3329. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3330. SKIP_ON_GATEWAY_ERROR(res);
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3333. }
  3334. }
  3335. }
  3336. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3337. // comma-separated list of challenges, and each challenge may itself carry a
  3338. // comma-separated auth-param list, so a server can legally offer Basic
  3339. // before Digest, either as two field lines or packed into one. Runs one 401
  3340. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3341. // value() joins them in receipt order) and checks that the retry carries a
  3342. // well-formed Digest Authorization header naming expected_realm.
  3343. static void
  3344. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3345. const std::string &expected_realm) {
  3346. std::atomic<int> hits{0};
  3347. Server svr;
  3348. svr.Get("/x", [&](const Request &req, Response &res) {
  3349. if (++hits == 1) {
  3350. res.status = StatusCode::Unauthorized_401;
  3351. for (const auto &challenge : challenges) {
  3352. res.set_header("WWW-Authenticate", challenge);
  3353. }
  3354. } else {
  3355. auto authorization = req.get_header_value("Authorization");
  3356. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3357. EXPECT_NE(std::string::npos,
  3358. authorization.find("realm=\"" + expected_realm + "\""));
  3359. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3360. res.set_content("ok", "text/plain");
  3361. }
  3362. });
  3363. auto port = svr.bind_to_any_port(HOST);
  3364. std::thread t([&]() { svr.listen_after_bind(); });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. t.join();
  3368. });
  3369. svr.wait_until_ready();
  3370. Client cli(HOST, port);
  3371. cli.set_digest_auth("hello", "world");
  3372. auto res = cli.Get("/x");
  3373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3374. EXPECT_EQ(2, hits.load());
  3375. }
  3376. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3377. static const char *kDigestChallenge =
  3378. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3379. "algorithm=MD5";
  3380. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3381. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3382. "testrealm");
  3383. }
  3384. // Same challenge list with the schemes in the opposite order, to make sure
  3385. // the fix above didn't just special-case "Basic first".
  3386. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3387. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3388. "testrealm");
  3389. }
  3390. // A comma inside a quoted auth-param value must not be mistaken for the
  3391. // separator between two challenges (or two auth-params).
  3392. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3393. run_digest_challenge_list_test(
  3394. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3395. "algorithm=MD5"},
  3396. "test,realm");
  3397. }
  3398. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3399. // the params and leaves out the fragment.
  3400. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3401. Server svr;
  3402. std::string uri, target;
  3403. svr.Get("/a b", [&](const Request &req, Response &res) {
  3404. auto auth = req.get_header_value("Authorization");
  3405. if (auth.empty()) {
  3406. res.status = StatusCode::Unauthorized_401;
  3407. res.set_header("WWW-Authenticate",
  3408. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3409. return;
  3410. }
  3411. auto b = auth.find("uri=\"") + 5;
  3412. uri = auth.substr(b, auth.find('"', b) - b);
  3413. target = req.target;
  3414. });
  3415. auto port = svr.bind_to_any_port(HOST);
  3416. std::thread t([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. t.join();
  3420. });
  3421. svr.wait_until_ready();
  3422. Client cli(HOST, port);
  3423. cli.set_digest_auth("hello", "world");
  3424. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3426. EXPECT_EQ("/a%20b?x=1", target);
  3427. EXPECT_EQ(target, uri);
  3428. }
  3429. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3430. // make_digest_authentication_header() dereferences both unconditionally, so
  3431. // a server sending a challenge missing either one must not be treated as
  3432. // usable -- doing so used to crash the client with std::out_of_range.
  3433. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3434. Server svr;
  3435. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3436. res.status = StatusCode::Unauthorized_401;
  3437. res.set_header("WWW-Authenticate", challenge);
  3438. });
  3439. auto port = svr.bind_to_any_port(HOST);
  3440. std::thread t([&]() { svr.listen_after_bind(); });
  3441. auto se = detail::scope_exit([&] {
  3442. svr.stop();
  3443. t.join();
  3444. });
  3445. svr.wait_until_ready();
  3446. Client cli(HOST, port);
  3447. cli.set_digest_auth("hello", "world");
  3448. auto res = cli.Get("/x");
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3451. }
  3452. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3453. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3454. }
  3455. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3456. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3457. }
  3458. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3459. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3460. }
  3461. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3462. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3463. // when storing the values, so the header builder has to re-escape them (and
  3464. // keep algorithm a bare token); otherwise the value breaks out of its
  3465. // quoted-string and injects extra auth-params into the client's Authorization.
  3466. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3467. std::atomic<int> hits{0};
  3468. std::string authorization;
  3469. Server svr;
  3470. svr.Get("/x", [&](const Request &req, Response &res) {
  3471. if (++hits == 1) {
  3472. res.status = StatusCode::Unauthorized_401;
  3473. // On the wire the quotes embedded in the values are backslash-escaped.
  3474. res.set_header("WWW-Authenticate",
  3475. "Digest realm=\"testrealm\", "
  3476. "nonce=\"n\\\"; injected=\\\"x\", "
  3477. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3478. } else {
  3479. authorization = req.get_header_value("Authorization");
  3480. res.set_content("ok", "text/plain");
  3481. }
  3482. });
  3483. auto port = svr.bind_to_any_port(HOST);
  3484. std::thread t([&]() { svr.listen_after_bind(); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. t.join();
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_digest_auth("hello", "world");
  3492. auto res = cli.Get("/x");
  3493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3494. EXPECT_EQ(2, hits.load());
  3495. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3496. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3497. // inside its quoted-string rather than starting an "injected" auth-param.
  3498. EXPECT_NE(std::string::npos,
  3499. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3500. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3501. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3502. }
  3503. #endif
  3504. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3505. auto host = "google.com";
  3506. auto another_host = "example.com";
  3507. auto wrong_ip = "0.0.0.0";
  3508. #ifdef CPPHTTPLIB_SSL_ENABLED
  3509. SSLClient cli(host);
  3510. #else
  3511. Client cli(host);
  3512. #endif
  3513. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3514. auto res = cli.Get("/");
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3517. }
  3518. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3519. auto host = "google.com";
  3520. auto wrong_ip = "0.0.0.0";
  3521. #ifdef CPPHTTPLIB_SSL_ENABLED
  3522. SSLClient cli(host);
  3523. #else
  3524. Client cli(host);
  3525. #endif
  3526. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3527. auto res = cli.Get("/");
  3528. ASSERT_TRUE(!res);
  3529. EXPECT_EQ(Error::Connection, res.error());
  3530. }
  3531. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3532. // A mapped value that is not an IP literal must be resolved. "localhost"
  3533. // resolves from the hosts file, so this test needs no external DNS.
  3534. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3535. auto host = "target.invalid";
  3536. Server svr;
  3537. std::string received_host;
  3538. svr.Get("/hi", [&](const Request &req, Response &res) {
  3539. received_host = req.get_header_value("Host");
  3540. res.set_content("Hello World!", "text/plain");
  3541. });
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3544. auto se = detail::scope_exit([&] {
  3545. svr.stop();
  3546. thread.join();
  3547. ASSERT_FALSE(svr.is_running());
  3548. });
  3549. svr.wait_until_ready();
  3550. Client cli(host, port);
  3551. cli.set_direct_hostname_addr_map({{host, HOST}});
  3552. auto res = cli.Get("/hi");
  3553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3554. EXPECT_EQ(StatusCode::OK_200, res->status);
  3555. // The mapping only redirects the connection; the identity stays host_.
  3556. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3557. }
  3558. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3559. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3560. auto host = "target.invalid";
  3561. Server svr;
  3562. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3563. res.set_content("Hello World!", "text/plain");
  3564. });
  3565. auto port = svr.bind_to_any_port("127.0.0.1");
  3566. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client cli(host, port);
  3574. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3575. auto res = cli.Get("/hi");
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ(StatusCode::OK_200, res->status);
  3578. }
  3579. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3580. // An empty mapped value must leave host_ as the connection target. Without
  3581. // that guard the empty value would become the host argument, getaddrinfo
  3582. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3583. // loopback - silently connecting somewhere the caller never asked for.
  3584. // The server listens on loopback, so such a fallback would succeed and is
  3585. // therefore observable as a failure of this test.
  3586. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3587. Server svr;
  3588. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3589. res.set_content("Hello World!", "text/plain");
  3590. });
  3591. auto port = svr.bind_to_any_port(HOST);
  3592. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3593. auto se = detail::scope_exit([&] {
  3594. svr.stop();
  3595. thread.join();
  3596. ASSERT_FALSE(svr.is_running());
  3597. });
  3598. svr.wait_until_ready();
  3599. Client cli(blackhole, port);
  3600. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3601. cli.set_connection_timeout(1);
  3602. auto res = cli.Get("/hi");
  3603. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3604. }
  3605. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3606. auto host = "target.invalid";
  3607. Server svr;
  3608. std::string received_host;
  3609. svr.Get("/hi", [&](const Request &req, Response &res) {
  3610. received_host = req.get_header_value("Host");
  3611. res.set_content("Hello World!", "text/plain");
  3612. });
  3613. auto port = svr.bind_to_any_port("127.0.0.1");
  3614. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3615. auto se = detail::scope_exit([&] {
  3616. svr.stop();
  3617. thread.join();
  3618. ASSERT_FALSE(svr.is_running());
  3619. });
  3620. svr.wait_until_ready();
  3621. Client cli(host, port);
  3622. #pragma GCC diagnostic push
  3623. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3624. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3625. #pragma GCC diagnostic pop
  3626. auto res = cli.Get("/hi");
  3627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3628. EXPECT_EQ(StatusCode::OK_200, res->status);
  3629. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3630. }
  3631. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3632. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3633. Server svr;
  3634. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3635. res.set_content("Hello World!", "text/plain");
  3636. });
  3637. auto port = svr.bind_to_any_port("127.0.0.1");
  3638. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3639. auto se = detail::scope_exit([&] {
  3640. svr.stop();
  3641. thread.join();
  3642. ASSERT_FALSE(svr.is_running());
  3643. });
  3644. svr.wait_until_ready();
  3645. Client cli("127.0.0.1", port);
  3646. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3647. cli.set_connection_timeout(1);
  3648. auto res = cli.Get("/hi");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::OK_200, res->status);
  3651. }
  3652. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3653. auto host = "httpbingo.org";
  3654. auto path = std::string{"/absolute-redirect/3"};
  3655. #ifdef CPPHTTPLIB_SSL_ENABLED
  3656. SSLClient cli(host);
  3657. #else
  3658. Client cli(host);
  3659. #endif
  3660. cli.set_follow_location(true);
  3661. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3662. SKIP_ON_GATEWAY_ERROR(res);
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. }
  3666. TEST(RedirectTest, Redirect_Online) {
  3667. auto host = "httpbingo.org";
  3668. auto path = std::string{"/redirect/3"};
  3669. #ifdef CPPHTTPLIB_SSL_ENABLED
  3670. SSLClient cli(host);
  3671. #else
  3672. Client cli(host);
  3673. #endif
  3674. cli.set_follow_location(true);
  3675. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3676. SKIP_ON_GATEWAY_ERROR(res);
  3677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3678. EXPECT_EQ(StatusCode::OK_200, res->status);
  3679. }
  3680. TEST(RelativeRedirectTest, Redirect_Online) {
  3681. auto host = "httpbingo.org";
  3682. auto path = std::string{"/relative-redirect/3"};
  3683. #ifdef CPPHTTPLIB_SSL_ENABLED
  3684. SSLClient cli(host);
  3685. #else
  3686. Client cli(host);
  3687. #endif
  3688. cli.set_follow_location(true);
  3689. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3690. SKIP_ON_GATEWAY_ERROR(res);
  3691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3692. EXPECT_EQ(StatusCode::OK_200, res->status);
  3693. }
  3694. TEST(TooManyRedirectTest, Redirect_Online) {
  3695. auto host = "httpbingo.org";
  3696. auto path = std::string{"/redirect/21"};
  3697. #ifdef CPPHTTPLIB_SSL_ENABLED
  3698. SSLClient cli(host);
  3699. #else
  3700. Client cli(host);
  3701. #endif
  3702. cli.set_follow_location(true);
  3703. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3704. SKIP_ON_GATEWAY_ERROR(res);
  3705. ASSERT_TRUE(!res);
  3706. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3707. }
  3708. #ifdef CPPHTTPLIB_SSL_ENABLED
  3709. TEST(YahooRedirectTest, Redirect_Online) {
  3710. Client cli("yahoo.com");
  3711. auto res = cli.Get("/");
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3714. cli.set_follow_location(true);
  3715. res = cli.Get("/");
  3716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3717. EXPECT_EQ(StatusCode::OK_200, res->status);
  3718. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3719. }
  3720. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3721. #define REDIR_HOST "httpbingo.org"
  3722. #define REDIR_PATH "/redirect-to"
  3723. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3724. SSLClient cli(REDIR_HOST);
  3725. cli.set_follow_location(true);
  3726. auto res = retry_gateway_errors([&] {
  3727. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3728. });
  3729. SKIP_ON_GATEWAY_ERROR(res);
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. }
  3733. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3734. SSLClient cli(REDIR_HOST);
  3735. cli.set_follow_location(true);
  3736. Params params;
  3737. params.emplace("url", "http://example.com");
  3738. params.emplace("status_code", "302");
  3739. auto res = retry_gateway_errors(
  3740. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3741. SKIP_ON_GATEWAY_ERROR(res);
  3742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3743. EXPECT_EQ(StatusCode::OK_200, res->status);
  3744. }
  3745. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3746. SSLClient cli(REDIR_HOST);
  3747. cli.set_follow_location(true);
  3748. Params params;
  3749. params.emplace("url", "http://example.com");
  3750. auto res = retry_gateway_errors([&] {
  3751. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3752. });
  3753. SKIP_ON_GATEWAY_ERROR(res);
  3754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3755. EXPECT_EQ(StatusCode::OK_200, res->status);
  3756. }
  3757. TEST(UrlWithSpace, Redirect_Online) {
  3758. SSLClient cli("edge.forgecdn.net");
  3759. cli.set_follow_location(true);
  3760. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3764. }
  3765. #endif
  3766. #if !defined(_WIN32) && !defined(_WIN64)
  3767. TEST(ReceiveSignals, Signal) {
  3768. auto setupSignalHandlers = []() {
  3769. struct sigaction act;
  3770. sigemptyset(&act.sa_mask);
  3771. act.sa_flags = SA_SIGINFO;
  3772. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3773. switch (sig) {
  3774. case SIGINT:
  3775. default: break;
  3776. }
  3777. };
  3778. ::sigaction(SIGINT, &act, nullptr);
  3779. };
  3780. Server svr;
  3781. int port = 0;
  3782. auto thread = std::thread([&]() {
  3783. setupSignalHandlers();
  3784. port = svr.bind_to_any_port(HOST);
  3785. svr.listen_after_bind();
  3786. });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. ASSERT_TRUE(svr.is_running());
  3794. pthread_kill(thread.native_handle(), SIGINT);
  3795. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3796. ASSERT_TRUE(svr.is_running());
  3797. }
  3798. #endif
  3799. TEST(RedirectToDifferentPort, Redirect) {
  3800. Server svr1;
  3801. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3802. res.set_content("Hello World!", "text/plain");
  3803. });
  3804. int svr1_port = 0;
  3805. auto thread1 = std::thread([&]() {
  3806. svr1_port = svr1.bind_to_any_port(HOST);
  3807. svr1.listen_after_bind();
  3808. });
  3809. Server svr2;
  3810. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3811. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3812. });
  3813. int svr2_port = 0;
  3814. auto thread2 = std::thread([&]() {
  3815. svr2_port = svr2.bind_to_any_port(HOST);
  3816. svr2.listen_after_bind();
  3817. });
  3818. auto se = detail::scope_exit([&] {
  3819. svr2.stop();
  3820. thread2.join();
  3821. svr1.stop();
  3822. thread1.join();
  3823. ASSERT_FALSE(svr2.is_running());
  3824. ASSERT_FALSE(svr1.is_running());
  3825. });
  3826. svr1.wait_until_ready();
  3827. svr2.wait_until_ready();
  3828. Client cli("localhost", svr2_port);
  3829. cli.set_follow_location(true);
  3830. auto res = cli.Get("/2");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("Hello World!", res->body);
  3834. }
  3835. // GET /redir on one server redirects to /target on another port, so the
  3836. // client follows it with a new client.
  3837. static Result
  3838. GetThroughRedirectToDifferentPort(Server::Handler target,
  3839. const std::function<void(Client &)> &setup,
  3840. const Headers &headers = Headers()) {
  3841. Server target_svr;
  3842. target_svr.Get("/target", target);
  3843. int target_port = 0;
  3844. auto target_thread = std::thread([&]() {
  3845. target_port = target_svr.bind_to_any_port(HOST);
  3846. target_svr.listen_after_bind();
  3847. });
  3848. Server origin_svr;
  3849. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3850. res.set_redirect(
  3851. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3852. });
  3853. int origin_port = 0;
  3854. auto origin_thread = std::thread([&]() {
  3855. origin_port = origin_svr.bind_to_any_port(HOST);
  3856. origin_svr.listen_after_bind();
  3857. });
  3858. auto se = detail::scope_exit([&] {
  3859. origin_svr.stop();
  3860. origin_thread.join();
  3861. target_svr.stop();
  3862. target_thread.join();
  3863. });
  3864. target_svr.wait_until_ready();
  3865. origin_svr.wait_until_ready();
  3866. Client cli("localhost", origin_port);
  3867. cli.set_follow_location(true);
  3868. setup(cli);
  3869. return cli.Get("/redir", headers);
  3870. }
  3871. static void
  3872. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3873. std::string captured_authorization;
  3874. auto result = GetThroughRedirectToDifferentPort(
  3875. [&](const Request &req, Response &res) {
  3876. captured_authorization = req.get_header_value("Authorization");
  3877. res.set_content("OK", "text/plain");
  3878. },
  3879. set_auth);
  3880. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3881. EXPECT_EQ(StatusCode::OK_200, result->status);
  3882. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3883. EXPECT_TRUE(captured_authorization.empty());
  3884. }
  3885. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3886. TestDoNotForwardCredentialsOnRedirect(
  3887. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3888. }
  3889. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3890. TestDoNotForwardCredentialsOnRedirect(
  3891. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3892. }
  3893. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3894. std::string captured_cookie;
  3895. auto result = GetThroughRedirectToDifferentPort(
  3896. [&](const Request &req, Response &res) {
  3897. captured_cookie = req.get_header_value("Cookie");
  3898. res.set_content("OK", "text/plain");
  3899. },
  3900. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3901. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3902. EXPECT_EQ(StatusCode::OK_200, result->status);
  3903. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3904. EXPECT_TRUE(captured_cookie.empty());
  3905. }
  3906. TEST(RedirectToSamePort, ForwardCookie) {
  3907. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3908. // header so that ordinary session flows keep working.
  3909. Server svr;
  3910. std::string captured_cookie;
  3911. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3912. res.set_redirect("/target", 302);
  3913. });
  3914. svr.Get("/target", [&](const Request &req, Response &res) {
  3915. captured_cookie = req.get_header_value("Cookie");
  3916. res.set_content("OK", "text/plain");
  3917. });
  3918. auto port = svr.bind_to_any_port(HOST);
  3919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3920. auto se = detail::scope_exit([&] {
  3921. svr.stop();
  3922. thread.join();
  3923. ASSERT_FALSE(svr.is_running());
  3924. });
  3925. svr.wait_until_ready();
  3926. Client cli(HOST, port);
  3927. cli.set_follow_location(true);
  3928. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3929. auto res = cli.Get("/redir", headers);
  3930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3933. }
  3934. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3935. // The Location alone names the next target, on any origin.
  3936. Server target_svr;
  3937. std::string cross_target;
  3938. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3939. cross_target = req.target;
  3940. res.set_content("OK", "text/plain");
  3941. });
  3942. auto target_port = target_svr.bind_to_any_port(HOST);
  3943. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3944. Server origin_svr;
  3945. std::string same_target;
  3946. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3947. res.set_redirect(
  3948. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3949. });
  3950. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3951. res.set_redirect("/landing", 302);
  3952. });
  3953. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3954. same_target = req.target;
  3955. res.set_content("OK", "text/plain");
  3956. });
  3957. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3958. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3959. auto se = detail::scope_exit([&] {
  3960. origin_svr.stop();
  3961. origin_thread.join();
  3962. target_svr.stop();
  3963. target_thread.join();
  3964. });
  3965. target_svr.wait_until_ready();
  3966. origin_svr.wait_until_ready();
  3967. Client cli("localhost", origin_port);
  3968. cli.set_follow_location(true);
  3969. Request req;
  3970. req.method = "GET";
  3971. req.params = {{"api_key", "SECRET"}};
  3972. req.path = "/cross";
  3973. auto res = cli.send(req);
  3974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3975. EXPECT_EQ("/landing", cross_target);
  3976. req.path = "/same";
  3977. res = cli.send(req);
  3978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3979. EXPECT_EQ("/landing", same_target);
  3980. }
  3981. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3982. std::string authorization;
  3983. std::string trace_id;
  3984. auto result = GetThroughRedirectToDifferentPort(
  3985. [&](const Request &req, Response &res) {
  3986. authorization = req.get_header_value("Authorization");
  3987. trace_id = req.get_header_value("X-Trace-Id");
  3988. res.set_content("OK", "text/plain");
  3989. },
  3990. [](Client &cli) {
  3991. cli.set_default_headers(
  3992. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3993. });
  3994. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3995. EXPECT_EQ(StatusCode::OK_200, result->status);
  3996. // Like a header given with the request, a default one goes along unless it
  3997. // carries credentials (RFC 9110 15.4).
  3998. EXPECT_TRUE(authorization.empty());
  3999. EXPECT_EQ("42", trace_id);
  4000. }
  4001. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4002. auto result = GetThroughRedirectToDifferentPort(
  4003. [](const Request &, Response &res) {
  4004. res.set_content(std::string(2048, 'x'), "text/plain");
  4005. },
  4006. [](Client &cli) { cli.set_payload_max_length(1024); });
  4007. EXPECT_FALSE(result);
  4008. }
  4009. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4010. auto result = GetThroughRedirectToDifferentPort(
  4011. [](const Request &req, Response &res) {
  4012. // Answer after a second, or once the client gives up.
  4013. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4014. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4015. }
  4016. res.set_content("late", "text/plain");
  4017. },
  4018. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4019. ASSERT_FALSE(result);
  4020. EXPECT_EQ(Error::Read, result.error());
  4021. }
  4022. #ifdef CPPHTTPLIB_SSL_ENABLED
  4023. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4024. auto result = GetThroughRedirectToDifferentPort(
  4025. [](const Request &, Response &res) {
  4026. res.status = StatusCode::Unauthorized_401;
  4027. res.set_header("WWW-Authenticate",
  4028. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4029. },
  4030. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4031. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4032. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4033. }
  4034. #endif
  4035. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4036. Server svr;
  4037. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4038. // Port number that overflows int — should not crash
  4039. res.set_redirect("http://localhost:99999999999999999999/target");
  4040. });
  4041. auto port = svr.bind_to_any_port(HOST);
  4042. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4043. auto se = detail::scope_exit([&] {
  4044. svr.stop();
  4045. thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. });
  4048. svr.wait_until_ready();
  4049. Client cli(HOST, port);
  4050. cli.set_follow_location(true);
  4051. auto res = cli.Get("/redir");
  4052. // Should fail gracefully, not crash (no valid response due to bad port)
  4053. EXPECT_FALSE(res);
  4054. }
  4055. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4056. Server svr;
  4057. auto port = svr.bind_to_any_port(HOST);
  4058. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4059. // The server's own port followed by junk must not be followed
  4060. res.set_redirect("http://" + std::string(HOST) + ":" +
  4061. std::to_string(port) + "junk/target");
  4062. });
  4063. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4064. res.set_content("target", "text/plain");
  4065. });
  4066. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4067. auto se = detail::scope_exit([&] {
  4068. svr.stop();
  4069. thread.join();
  4070. ASSERT_FALSE(svr.is_running());
  4071. });
  4072. svr.wait_until_ready();
  4073. Client cli(HOST, port);
  4074. cli.set_follow_location(true);
  4075. auto res = cli.Get("/redir");
  4076. EXPECT_FALSE(res);
  4077. }
  4078. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4079. Server target_svr;
  4080. std::atomic<int> target_hits{0};
  4081. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4082. target_hits++;
  4083. res.set_content("target", "text/plain");
  4084. });
  4085. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4086. res.set_content("target", "text/plain");
  4087. });
  4088. int target_port = 0;
  4089. auto target_thread = std::thread([&]() {
  4090. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4091. target_svr.listen_after_bind();
  4092. });
  4093. Server origin_svr;
  4094. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4095. res.set_redirect(req.get_param_value("to"));
  4096. });
  4097. int origin_port = 0;
  4098. auto origin_thread = std::thread([&]() {
  4099. origin_port = origin_svr.bind_to_any_port(HOST);
  4100. origin_svr.listen_after_bind();
  4101. });
  4102. auto se = detail::scope_exit([&] {
  4103. origin_svr.stop();
  4104. origin_thread.join();
  4105. target_svr.stop();
  4106. target_thread.join();
  4107. ASSERT_FALSE(origin_svr.is_running());
  4108. ASSERT_FALSE(target_svr.is_running());
  4109. });
  4110. target_svr.wait_until_ready();
  4111. origin_svr.wait_until_ready();
  4112. auto port = std::to_string(target_port);
  4113. for (const auto &to :
  4114. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4115. Client cli(HOST, origin_port);
  4116. cli.set_follow_location(true);
  4117. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4118. EXPECT_FALSE(res) << to;
  4119. }
  4120. EXPECT_EQ(0, target_hits);
  4121. Client cli(HOST, origin_port);
  4122. cli.set_follow_location(true);
  4123. auto res = cli.Get("/redir?to=" +
  4124. encode_query_component("//127.0.0.1:" + port + "/target"));
  4125. ASSERT_TRUE(res) << to_string(res.error());
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. EXPECT_EQ("target", res->body);
  4128. }
  4129. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4130. Server svr;
  4131. std::atomic<bool> followed{false};
  4132. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4133. res.status = StatusCode::NotModified_304;
  4134. res.set_header("Location", "/target");
  4135. });
  4136. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4137. res.status = StatusCode::UseProxy_305;
  4138. res.set_header("Location", "/target");
  4139. });
  4140. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4141. followed = true;
  4142. res.set_content("target", "text/plain");
  4143. });
  4144. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4145. auto se = detail::scope_exit([&] {
  4146. svr.stop();
  4147. th.join();
  4148. ASSERT_FALSE(svr.is_running());
  4149. });
  4150. svr.wait_until_ready();
  4151. Client cli("localhost", PORT);
  4152. cli.set_follow_location(true);
  4153. auto res = cli.Get("/304");
  4154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4155. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4156. res = cli.Get("/305");
  4157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4158. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4159. EXPECT_FALSE(followed);
  4160. }
  4161. TEST(RedirectFromPageWithContent, Redirect) {
  4162. Server svr;
  4163. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4164. res.set_content("___", "text/plain");
  4165. res.set_redirect("/2");
  4166. });
  4167. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4168. res.set_content("Hello World!", "text/plain");
  4169. });
  4170. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4171. auto se = detail::scope_exit([&] {
  4172. svr.stop();
  4173. th.join();
  4174. ASSERT_FALSE(svr.is_running());
  4175. });
  4176. svr.wait_until_ready();
  4177. {
  4178. Client cli("localhost", PORT);
  4179. cli.set_follow_location(true);
  4180. std::string body;
  4181. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4182. body.append(data, data_length);
  4183. return true;
  4184. });
  4185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ("Hello World!", body);
  4188. }
  4189. {
  4190. Client cli("localhost", PORT);
  4191. std::string body;
  4192. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4193. body.append(data, data_length);
  4194. return true;
  4195. });
  4196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4197. EXPECT_EQ(StatusCode::Found_302, res->status);
  4198. EXPECT_EQ("___", body);
  4199. }
  4200. }
  4201. // A server can close the connection after a request with "Connection: close"
  4202. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4203. // redirected request must go out on a new connection.
  4204. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4205. #ifndef _WIN32
  4206. signal(SIGPIPE, SIG_IGN);
  4207. #endif
  4208. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4209. default_socket_options(srv);
  4210. sockaddr_in addr{};
  4211. addr.sin_family = AF_INET;
  4212. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4213. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4214. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4215. ASSERT_EQ(0, ::listen(srv, 2));
  4216. auto send_text = [](socket_t sock, const std::string &text) {
  4217. ::send(sock,
  4218. #ifdef _WIN32
  4219. static_cast<const char *>(text.c_str()),
  4220. static_cast<int>(text.size()),
  4221. #else
  4222. text.c_str(), text.size(),
  4223. #endif
  4224. 0);
  4225. };
  4226. auto reused = false;
  4227. auto server_thread = std::thread([&] {
  4228. char buf[4096];
  4229. auto first = ::accept(srv, nullptr, nullptr);
  4230. if (first == INVALID_SOCKET) { return; }
  4231. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4232. ::recv(first, buf, sizeof(buf), 0);
  4233. send_text(
  4234. first,
  4235. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4236. auto next = first;
  4237. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4238. reused = true;
  4239. } else {
  4240. detail::close_socket(first);
  4241. next = ::accept(srv, nullptr, nullptr);
  4242. if (next == INVALID_SOCKET) { return; }
  4243. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4244. ::recv(next, buf, sizeof(buf), 0);
  4245. }
  4246. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4247. "Connection: close\r\n\r\nok");
  4248. detail::close_socket(next);
  4249. });
  4250. Client cli("127.0.0.1", PORT + 2);
  4251. cli.set_follow_location(true);
  4252. cli.set_read_timeout(5, 0);
  4253. auto res = cli.Get("/1");
  4254. server_thread.join();
  4255. detail::close_socket(srv);
  4256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4257. EXPECT_EQ(StatusCode::OK_200, res->status);
  4258. EXPECT_EQ("ok", res->body);
  4259. EXPECT_FALSE(reused);
  4260. }
  4261. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4262. Server svr;
  4263. auto port_str = std::to_string(PORT);
  4264. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4265. auto expected_host = "[::1]:" + port_str;
  4266. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4267. res.set_content("___", "text/plain");
  4268. // res.set_redirect("/2");
  4269. res.set_redirect(redirect_url);
  4270. });
  4271. svr.Get("/2", [&](const Request &req, Response &res) {
  4272. auto host_header = req.headers.find("Host");
  4273. ASSERT_TRUE(host_header != req.headers.end());
  4274. EXPECT_EQ(expected_host, host_header->second);
  4275. res.set_content("Hello World!", "text/plain");
  4276. });
  4277. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4278. auto se = detail::scope_exit([&] {
  4279. svr.stop();
  4280. th.join();
  4281. ASSERT_FALSE(svr.is_running());
  4282. });
  4283. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4284. // actually starts anything, so the condition !svr.is_running() will
  4285. // always remain true, and the loop never stops.
  4286. // This basically counts how many milliseconds have passed since the
  4287. // call to svr.listen(), and if after 5 seconds nothing started yet
  4288. // aborts the test.
  4289. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4290. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4291. ASSERT_LT(milliseconds, 5000U);
  4292. }
  4293. {
  4294. Client cli("::1", PORT);
  4295. cli.set_follow_location(true);
  4296. std::string body;
  4297. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4298. body.append(data, data_length);
  4299. return true;
  4300. });
  4301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("Hello World!", body);
  4304. }
  4305. {
  4306. Client cli("::1", PORT);
  4307. std::string body;
  4308. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4309. body.append(data, data_length);
  4310. return true;
  4311. });
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::Found_302, res->status);
  4314. EXPECT_EQ("___", body);
  4315. }
  4316. }
  4317. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4318. Server svr;
  4319. svr.Get("/foo", [](const Request &req, Response &res) {
  4320. auto a = req.params.find("a");
  4321. if (a != req.params.end()) {
  4322. res.set_content((*a).second, "text/plain");
  4323. res.status = StatusCode::OK_200;
  4324. } else {
  4325. res.status = StatusCode::BadRequest_400;
  4326. }
  4327. });
  4328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4329. auto se = detail::scope_exit([&] {
  4330. svr.stop();
  4331. thread.join();
  4332. ASSERT_FALSE(svr.is_running());
  4333. });
  4334. svr.wait_until_ready();
  4335. {
  4336. Client cli(HOST, PORT);
  4337. cli.set_path_encode(false);
  4338. auto res = cli.Get("/foo?a=explicitly+encoded");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. // This expects it back with a space, as the `+` won't have been
  4342. // url-encoded, and server-side the params get decoded turning `+`
  4343. // into spaces.
  4344. EXPECT_EQ("explicitly encoded", res->body);
  4345. }
  4346. }
  4347. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4348. // When path encoding is disabled the client must transmit the supplied
  4349. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4350. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4351. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4352. // than a space (0x20). Assert on the raw wire target to catch this.
  4353. Server svr;
  4354. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4355. svr.Get("/foo", [&](const Request &req, Response &res) {
  4356. EXPECT_EQ(expected_target, req.target);
  4357. res.status = StatusCode::OK_200;
  4358. });
  4359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4360. auto se = detail::scope_exit([&] {
  4361. svr.stop();
  4362. thread.join();
  4363. ASSERT_FALSE(svr.is_running());
  4364. });
  4365. svr.wait_until_ready();
  4366. {
  4367. Client cli(HOST, PORT);
  4368. cli.set_path_encode(false);
  4369. auto res = cli.Get(expected_target.c_str());
  4370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4371. EXPECT_EQ(StatusCode::OK_200, res->status);
  4372. }
  4373. }
  4374. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4375. // `open_stream()` used to skip the path encoding that the buffered send
  4376. // path applies, so the same `path` produced different bytes in the request
  4377. // line depending on which API was used. Assert the two agree.
  4378. Server svr;
  4379. std::string target;
  4380. svr.Get(".*", [&](const Request &req, Response &res) {
  4381. target = req.target;
  4382. res.status = StatusCode::OK_200;
  4383. });
  4384. auto port = svr.bind_to_any_port(HOST);
  4385. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4386. auto se = detail::scope_exit([&] {
  4387. svr.stop();
  4388. thread.join();
  4389. ASSERT_FALSE(svr.is_running());
  4390. });
  4391. svr.wait_until_ready();
  4392. struct {
  4393. const char *path;
  4394. const char *expected;
  4395. } cases[] = {
  4396. {"/a b?x=1", "/a%20b?x=1"},
  4397. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4398. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4399. };
  4400. for (const auto &c : cases) {
  4401. Client cli(HOST, port);
  4402. target.clear();
  4403. auto res = cli.Get(c.path);
  4404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4405. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4406. auto buffered_target = target;
  4407. target.clear();
  4408. auto handle = cli.open_stream("GET", c.path);
  4409. EXPECT_TRUE(handle.is_valid())
  4410. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4411. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4412. }
  4413. }
  4414. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4415. // The `set_path_encode(false)` contract — transmit the supplied target
  4416. // verbatim — must hold for the streaming API too.
  4417. Server svr;
  4418. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4419. std::string target;
  4420. svr.Get("/foo", [&](const Request &req, Response &res) {
  4421. target = req.target;
  4422. res.status = StatusCode::OK_200;
  4423. });
  4424. auto port = svr.bind_to_any_port(HOST);
  4425. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4426. auto se = detail::scope_exit([&] {
  4427. svr.stop();
  4428. thread.join();
  4429. ASSERT_FALSE(svr.is_running());
  4430. });
  4431. svr.wait_until_ready();
  4432. {
  4433. Client cli(HOST, port);
  4434. cli.set_path_encode(false);
  4435. auto handle = cli.open_stream("GET", expected_target);
  4436. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4437. EXPECT_EQ(expected_target, target);
  4438. }
  4439. }
  4440. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4441. // With path encoding enabled a CR/LF in the target is percent-encoded
  4442. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4443. // write_request_line still backstops `set_path_encode(false)`, which is
  4444. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4445. Server svr;
  4446. // Captured before routing: the decoded path contains a newline, which a
  4447. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4448. std::string target;
  4449. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4450. target = req.target;
  4451. res.status = StatusCode::OK_200;
  4452. return Server::HandlerResponse::Handled;
  4453. });
  4454. auto port = svr.bind_to_any_port(HOST);
  4455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4456. auto se = detail::scope_exit([&] {
  4457. svr.stop();
  4458. thread.join();
  4459. ASSERT_FALSE(svr.is_running());
  4460. });
  4461. svr.wait_until_ready();
  4462. {
  4463. Client cli(HOST, port);
  4464. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4465. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4466. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4467. }
  4468. }
  4469. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4470. // Every control character is percent-encoded, not just CR/LF, so the target
  4471. // passes the request-target check in write_request_line.
  4472. Server svr;
  4473. std::string target;
  4474. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4475. target = req.target;
  4476. res.status = StatusCode::OK_200;
  4477. return Server::HandlerResponse::Handled;
  4478. });
  4479. auto port = svr.bind_to_any_port(HOST);
  4480. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. {
  4488. Client cli(HOST, port);
  4489. auto res = cli.Get("/a\tb\x1b\x7f");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ("/a%09b%1B%7F", target);
  4492. }
  4493. }
  4494. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4495. // Nothing may reach the wire: a raw CR/LF target would split the request
  4496. // line and inject headers.
  4497. Server svr;
  4498. // Pre-routing so that "not called" means nothing reached the server at all,
  4499. // rather than merely failing to match a handler pattern.
  4500. auto handler_called = false;
  4501. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4502. handler_called = true;
  4503. res.status = StatusCode::OK_200;
  4504. return Server::HandlerResponse::Handled;
  4505. });
  4506. auto port = svr.bind_to_any_port(HOST);
  4507. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4508. auto se = detail::scope_exit([&] {
  4509. svr.stop();
  4510. thread.join();
  4511. ASSERT_FALSE(svr.is_running());
  4512. });
  4513. svr.wait_until_ready();
  4514. {
  4515. Client cli(HOST, port);
  4516. cli.set_path_encode(false);
  4517. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4518. EXPECT_FALSE(handle.is_valid());
  4519. EXPECT_EQ(Error::Write, handle.error);
  4520. EXPECT_FALSE(handler_called);
  4521. }
  4522. }
  4523. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4524. // Which of the two branches runs is decided by whether the query component
  4525. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4526. // an empty query and must still fall back to building one from
  4527. // `req.params`, while a non-empty query must win over `req.params`.
  4528. Server svr;
  4529. std::string target;
  4530. svr.Get("/foo", [&](const Request &req, Response &res) {
  4531. target = req.target;
  4532. res.status = StatusCode::OK_200;
  4533. });
  4534. auto port = svr.bind_to_any_port(HOST);
  4535. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. // Trailing `?` -> empty query component -> `req.params` is used.
  4544. Client cli(HOST, port);
  4545. Request req;
  4546. req.method = "GET";
  4547. req.path = "/foo?";
  4548. req.params.emplace("a", "1");
  4549. target.clear();
  4550. auto res = cli.send(req);
  4551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4552. EXPECT_EQ("/foo?a=1", target);
  4553. }
  4554. {
  4555. // Non-empty query in `req.path` -> `req.params` is not appended.
  4556. Client cli(HOST, port);
  4557. Request req;
  4558. req.method = "GET";
  4559. req.path = "/foo?b=2";
  4560. req.params.emplace("a", "1");
  4561. target.clear();
  4562. auto res = cli.send(req);
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("/foo?b=2", target);
  4565. }
  4566. }
  4567. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4568. Server svr;
  4569. svr.Get("/", [](const Request &req, Response &) {
  4570. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4571. });
  4572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, PORT);
  4581. cli.set_path_encode(false);
  4582. auto res = cli.Get("/?something=%0A");
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. }
  4586. }
  4587. TEST(BindServerTest, BindDualStack) {
  4588. Server svr;
  4589. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4590. res.set_content("Hello World!", "text/plain");
  4591. });
  4592. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4593. auto se = detail::scope_exit([&] {
  4594. svr.stop();
  4595. thread.join();
  4596. ASSERT_FALSE(svr.is_running());
  4597. });
  4598. svr.wait_until_ready();
  4599. {
  4600. Client cli("127.0.0.1", PORT);
  4601. auto res = cli.Get("/1");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. EXPECT_EQ("Hello World!", res->body);
  4605. }
  4606. {
  4607. Client cli("::1", PORT);
  4608. auto res = cli.Get("/1");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("Hello World!", res->body);
  4612. }
  4613. }
  4614. TEST(BindServerTest, BindAndListenSeparately) {
  4615. Server svr;
  4616. int port = svr.bind_to_any_port("0.0.0.0");
  4617. ASSERT_TRUE(svr.is_valid());
  4618. ASSERT_TRUE(port > 0);
  4619. svr.stop();
  4620. }
  4621. // Reports whether anything is still listening on a loopback port. A plain
  4622. // connect() is used instead of a Client request because a socket left bound by
  4623. // mistake accepts the connection into its backlog and never answers, which
  4624. // would hang the test instead of failing it.
  4625. static bool is_loopback_port_accepting(int port) {
  4626. sockaddr_in addr{};
  4627. addr.sin_family = AF_INET;
  4628. addr.sin_port = htons(static_cast<uint16_t>(port));
  4629. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4630. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4631. EXPECT_NE(sock, INVALID_SOCKET);
  4632. if (sock == INVALID_SOCKET) { return false; }
  4633. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4634. static_cast<socklen_t>(sizeof(addr)));
  4635. detail::close_socket(sock);
  4636. return ret == 0;
  4637. }
  4638. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4639. Server svr;
  4640. auto port = svr.bind_to_any_port("127.0.0.1");
  4641. ASSERT_TRUE(port > 0);
  4642. svr.stop();
  4643. // bind_to_any_port() already called listen(2), so until stop() closed the
  4644. // descriptor the port kept accepting connections into the backlog. ASSERT
  4645. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4646. // below blocks forever in the accept loop.
  4647. ASSERT_FALSE(is_loopback_port_accepting(port));
  4648. // Nothing is left to accept on, so listen_after_bind() must report failure
  4649. // instead of returning success without ever serving.
  4650. EXPECT_FALSE(svr.listen_after_bind());
  4651. // The failed listen marks the server decommissioned, so a waiter returns
  4652. // instead of spinning forever.
  4653. svr.wait_until_ready();
  4654. }
  4655. #ifdef CPPHTTPLIB_SSL_ENABLED
  4656. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4658. CLIENT_CA_CERT_DIR);
  4659. int port = svr.bind_to_any_port("0.0.0.0");
  4660. ASSERT_TRUE(svr.is_valid());
  4661. ASSERT_TRUE(port > 0);
  4662. svr.stop();
  4663. }
  4664. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4665. // or a rejected CustomRoute() registration would not stop the server binding.
  4666. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4668. CLIENT_CA_CERT_DIR);
  4669. ASSERT_TRUE(svr.is_valid());
  4670. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4671. EXPECT_FALSE(svr.is_valid());
  4672. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4673. }
  4674. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4675. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4676. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4677. int port = svr.bind_to_any_port("0.0.0.0");
  4678. ASSERT_TRUE(svr.is_valid());
  4679. ASSERT_TRUE(port > 0);
  4680. svr.stop();
  4681. }
  4682. TEST(BindServerTest, UpdateCertsPem) {
  4683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4684. int port = svr.bind_to_any_port("0.0.0.0");
  4685. ASSERT_TRUE(svr.is_valid());
  4686. ASSERT_TRUE(port > 0);
  4687. // Read PEM files
  4688. std::string cert_pem, key_pem, ca_pem;
  4689. read_file(SERVER_CERT_FILE, cert_pem);
  4690. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4691. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4692. // Update server certificates using PEM API
  4693. ASSERT_TRUE(
  4694. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4695. ASSERT_TRUE(svr.is_valid());
  4696. svr.stop();
  4697. }
  4698. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4699. // Start server with client CA (enables client auth)
  4700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4701. ASSERT_TRUE(svr.is_valid());
  4702. bool handler_called = false;
  4703. svr.Get("/test", [&](const Request &req, Response &res) {
  4704. handler_called = true;
  4705. // Verify client certificate is present
  4706. auto cert = req.peer_cert();
  4707. EXPECT_TRUE(static_cast<bool>(cert));
  4708. res.set_content("ok", "text/plain");
  4709. });
  4710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4711. auto se = detail::scope_exit([&] {
  4712. svr.stop();
  4713. t.join();
  4714. ASSERT_FALSE(svr.is_running());
  4715. });
  4716. svr.wait_until_ready();
  4717. // Read PEM files
  4718. std::string cert_pem, key_pem, ca_pem;
  4719. read_file(SERVER_CERT_FILE, cert_pem);
  4720. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4721. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4722. // Update server certificates and client CA using PEM API while server running
  4723. ASSERT_TRUE(
  4724. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4725. // Connect with client certificate
  4726. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4727. cli.enable_server_certificate_verification(false);
  4728. cli.set_connection_timeout(30);
  4729. auto res = cli.Get("/test");
  4730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4731. ASSERT_EQ(StatusCode::OK_200, res->status);
  4732. ASSERT_TRUE(handler_called);
  4733. EXPECT_EQ("ok", res->body);
  4734. }
  4735. // Puts a CA that did not sign the client's certificate in the old one's place.
  4736. static bool replace_client_ca(SSLServer &svr) {
  4737. std::string cert_pem, key_pem, ca_pem;
  4738. read_file(SERVER_CERT_FILE, cert_pem);
  4739. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4740. read_file(SERVER_CERT2_FILE, ca_pem);
  4741. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4742. ca_pem.c_str());
  4743. }
  4744. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4746. ASSERT_TRUE(svr.is_valid());
  4747. svr.Get("/test", [](const Request &, Response &res) {
  4748. res.set_content("ok", "text/plain");
  4749. });
  4750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4751. auto se = detail::scope_exit([&] {
  4752. svr.stop();
  4753. t.join();
  4754. ASSERT_FALSE(svr.is_running());
  4755. });
  4756. svr.wait_until_ready();
  4757. auto get = [] {
  4758. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4759. cli.enable_server_certificate_verification(false);
  4760. return cli.Get("/test");
  4761. };
  4762. ASSERT_TRUE(get());
  4763. ASSERT_TRUE(replace_client_ca(svr));
  4764. EXPECT_FALSE(get());
  4765. }
  4766. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4767. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4769. ASSERT_TRUE(svr.is_valid());
  4770. tls::set_verify_callback(svr.tls_context(),
  4771. [](const tls::VerifyContext &) -> bool {
  4772. throw std::runtime_error("verify");
  4773. });
  4774. svr.Get("/test", [](const Request &, Response &res) {
  4775. res.set_content("ok", "text/plain");
  4776. });
  4777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4778. auto se = detail::scope_exit([&] {
  4779. svr.stop();
  4780. t.join();
  4781. ASSERT_FALSE(svr.is_running());
  4782. });
  4783. svr.wait_until_ready();
  4784. auto get = [] {
  4785. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4786. cli.enable_server_certificate_verification(false);
  4787. return cli.Get("/test");
  4788. };
  4789. EXPECT_FALSE(get());
  4790. // The handshake is over, so an update does not wait for it.
  4791. std::string cert_pem, key_pem;
  4792. read_file(SERVER_CERT_FILE, cert_pem);
  4793. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4794. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4795. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4796. return v.preverify_ok;
  4797. });
  4798. auto res = get();
  4799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4800. EXPECT_EQ("ok", res->body);
  4801. }
  4802. #endif
  4803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4804. // Sends each request over a new connection with a client certificate,
  4805. // resuming the session of the one before when there is one.
  4806. class ResumingClient {
  4807. public:
  4808. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4809. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4810. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4811. SSL_FILETYPE_PEM);
  4812. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4813. // callback, not through SSL_get1_session().
  4814. SSL_CTX_set_app_data(ctx_, this);
  4815. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4816. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4817. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4818. auto self = static_cast<ResumingClient *>(
  4819. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4820. SSL_SESSION_free(self->session_);
  4821. self->session_ = session;
  4822. return 1; // Keeps the reference
  4823. });
  4824. }
  4825. ~ResumingClient() {
  4826. SSL_SESSION_free(session_);
  4827. SSL_CTX_free(ctx_);
  4828. }
  4829. // Tells whether the request was answered.
  4830. bool get() {
  4831. auto error = Error::Success;
  4832. auto sock = detail::create_client_socket(
  4833. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4834. /*connection_timeout_sec=*/5, 0,
  4835. /*read_timeout_sec=*/5, 0,
  4836. /*write_timeout_sec=*/5, 0, std::string(), error);
  4837. if (sock == INVALID_SOCKET) { return false; }
  4838. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4839. auto ssl = SSL_new(ctx_);
  4840. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4841. SSL_set_fd(ssl, static_cast<int>(sock));
  4842. if (session_) { SSL_set_session(ssl, session_); }
  4843. if (SSL_connect(ssl) != 1) { return false; }
  4844. reused_ = SSL_session_reused(ssl) == 1;
  4845. // Reading the response also takes in a TLS 1.3 session ticket.
  4846. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4847. "Connection: close\r\n\r\n";
  4848. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4849. std::string res;
  4850. char buf[256];
  4851. int n;
  4852. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4853. res.append(buf, static_cast<size_t>(n));
  4854. }
  4855. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4856. SSL_shutdown(ssl);
  4857. return res.find("200 OK") != std::string::npos;
  4858. }
  4859. // Whether the last connection resumed a session
  4860. bool reused() const { return reused_; }
  4861. private:
  4862. SSL_CTX *ctx_;
  4863. SSL_SESSION *session_ = nullptr;
  4864. bool reused_ = false;
  4865. };
  4866. // A client that resumes its session gets through, but not once the client CA
  4867. // has changed, as a resumed session does not show the certificate again.
  4868. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4870. ASSERT_TRUE(svr.is_valid());
  4871. svr.Get("/test", [](const Request &, Response &res) {
  4872. res.set_content("ok", "text/plain");
  4873. });
  4874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4875. auto se = detail::scope_exit([&] {
  4876. svr.stop();
  4877. t.join();
  4878. ASSERT_FALSE(svr.is_running());
  4879. });
  4880. svr.wait_until_ready();
  4881. ResumingClient cli;
  4882. ASSERT_TRUE(cli.get());
  4883. ASSERT_TRUE(cli.get());
  4884. EXPECT_TRUE(cli.reused());
  4885. ASSERT_TRUE(replace_client_ca(svr));
  4886. EXPECT_FALSE(cli.get());
  4887. }
  4888. // A resumed session does not show the certificate again, so the server does
  4889. // not resume one with a verify callback to run on it.
  4890. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4892. ASSERT_TRUE(svr.is_valid());
  4893. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4894. return v.preverify_ok;
  4895. });
  4896. svr.Get("/test", [](const Request &, Response &res) {
  4897. res.set_content("ok", "text/plain");
  4898. });
  4899. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4900. auto se = detail::scope_exit([&] {
  4901. svr.stop();
  4902. t.join();
  4903. ASSERT_FALSE(svr.is_running());
  4904. });
  4905. svr.wait_until_ready();
  4906. ResumingClient cli;
  4907. ASSERT_TRUE(cli.get());
  4908. ASSERT_TRUE(cli.get());
  4909. EXPECT_FALSE(cli.reused());
  4910. }
  4911. #endif
  4912. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4913. // wolfSSL shares its session cache between contexts, so a resumed session
  4914. // could carry a client certificate checked against another server's CA, or
  4915. // against a client CA since replaced.
  4916. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4918. ASSERT_TRUE(svr.is_valid());
  4919. // Trusts a CA that did not sign the client's certificate.
  4920. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4921. ASSERT_TRUE(other.is_valid());
  4922. for (auto s : {&svr, &other}) {
  4923. s->Get("/test", [](const Request &, Response &res) {
  4924. res.set_content("ok", "text/plain");
  4925. });
  4926. }
  4927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4928. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4929. auto se = detail::scope_exit([&] {
  4930. other.stop();
  4931. svr.stop();
  4932. t2.join();
  4933. t.join();
  4934. });
  4935. svr.wait_until_ready();
  4936. other.wait_until_ready();
  4937. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4938. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4939. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4940. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4941. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4942. ASSERT_EQ(WOLFSSL_SUCCESS,
  4943. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4944. WOLFSSL_FILETYPE_PEM));
  4945. WOLFSSL_SESSION *session = nullptr;
  4946. auto session_se = detail::scope_exit([&] {
  4947. if (session) { wolfSSL_SESSION_free(session); }
  4948. });
  4949. // A request over a new connection, resuming `session` when there is one and
  4950. // keeping the connection's own in its place. Tells whether it was answered.
  4951. auto get = [&](int port) {
  4952. auto error = Error::Success;
  4953. auto sock = detail::create_client_socket(
  4954. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4955. /*connection_timeout_sec=*/5, 0,
  4956. /*read_timeout_sec=*/5, 0,
  4957. /*write_timeout_sec=*/5, 0, std::string(), error);
  4958. if (sock == INVALID_SOCKET) { return false; }
  4959. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4960. auto ssl = wolfSSL_new(ctx);
  4961. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4962. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4963. if (session) { wolfSSL_set_session(ssl, session); }
  4964. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4965. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4966. "Connection: close\r\n\r\n";
  4967. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4968. std::string res;
  4969. char buf[256];
  4970. int n;
  4971. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4972. res.append(buf, static_cast<size_t>(n));
  4973. }
  4974. wolfSSL_shutdown(ssl);
  4975. if (session) { wolfSSL_SESSION_free(session); }
  4976. session = wolfSSL_get1_session(ssl);
  4977. return res.find("200 OK") != std::string::npos;
  4978. };
  4979. ASSERT_TRUE(get(PORT));
  4980. EXPECT_FALSE(get(PORT + 1));
  4981. ASSERT_TRUE(get(PORT));
  4982. ASSERT_TRUE(replace_client_ca(svr));
  4983. EXPECT_FALSE(get(PORT));
  4984. }
  4985. #endif
  4986. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4988. ASSERT_TRUE(svr.is_valid());
  4989. // Keep-alive parking would wait for the ClientHello without a handshake.
  4990. svr.set_keep_alive_parking(false);
  4991. svr.Get("/test", [](const Request &, Response &res) {
  4992. res.set_content("ok", "text/plain");
  4993. });
  4994. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4995. auto se = detail::scope_exit([&] {
  4996. svr.stop();
  4997. t.join();
  4998. ASSERT_FALSE(svr.is_running());
  4999. });
  5000. svr.wait_until_ready();
  5001. // A connection that sends no ClientHello keeps its handshake in progress,
  5002. // once the server has had a moment to start it.
  5003. auto error = Error::Success;
  5004. auto sock = detail::create_client_socket(
  5005. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5006. /*connection_timeout_sec=*/5, 0,
  5007. /*read_timeout_sec=*/5, 0,
  5008. /*write_timeout_sec=*/5, 0, std::string(), error);
  5009. ASSERT_NE(INVALID_SOCKET, sock);
  5010. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5011. std::string cert_pem, key_pem;
  5012. read_file(SERVER_CERT_FILE, cert_pem);
  5013. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5014. auto update = std::async(std::launch::async, [&]() {
  5015. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5016. });
  5017. EXPECT_EQ(std::future_status::timeout,
  5018. update.wait_for(std::chrono::milliseconds(200)));
  5019. detail::close_socket(sock);
  5020. EXPECT_TRUE(update.get());
  5021. SSLClient cli(HOST, PORT);
  5022. cli.enable_server_certificate_verification(false);
  5023. auto res = cli.Get("/test");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. }
  5027. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5029. ASSERT_TRUE(svr.is_valid());
  5030. // Keep-alive parking would wait for the ClientHello without a handshake.
  5031. svr.set_keep_alive_parking(false);
  5032. svr.set_read_timeout(10, 0);
  5033. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5034. auto se = detail::scope_exit([&] {
  5035. svr.stop();
  5036. if (t.joinable()) { t.join(); }
  5037. });
  5038. svr.wait_until_ready();
  5039. // A connection that sends no ClientHello keeps its handshake in progress,
  5040. // once the server has had a moment to start it.
  5041. auto error = Error::Success;
  5042. auto sock = detail::create_client_socket(
  5043. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5044. /*connection_timeout_sec=*/5, 0,
  5045. /*read_timeout_sec=*/5, 0,
  5046. /*write_timeout_sec=*/5, 0, std::string(), error);
  5047. ASSERT_NE(INVALID_SOCKET, sock);
  5048. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5049. auto start = std::chrono::steady_clock::now();
  5050. svr.stop();
  5051. t.join();
  5052. auto elapsed = std::chrono::steady_clock::now() - start;
  5053. detail::close_socket(sock);
  5054. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5055. }
  5056. #endif
  5057. TEST(ErrorHandlerTest, ContentLength) {
  5058. Server svr;
  5059. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5060. res.status = StatusCode::OK_200;
  5061. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5062. "text/html"); // <= Content-Length still 13
  5063. });
  5064. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5065. res.set_content("Hello World!\n", "text/plain");
  5066. res.status = 524;
  5067. });
  5068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5069. auto se = detail::scope_exit([&] {
  5070. svr.stop();
  5071. thread.join();
  5072. ASSERT_FALSE(svr.is_running());
  5073. });
  5074. svr.wait_until_ready();
  5075. {
  5076. Client cli(HOST, PORT);
  5077. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5079. EXPECT_EQ(StatusCode::OK_200, res->status);
  5080. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5081. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5082. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5083. }
  5084. }
  5085. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5086. TEST(ExceptionTest, WithoutExceptionHandler) {
  5087. Server svr;
  5088. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5089. throw std::runtime_error("exception...");
  5090. });
  5091. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5092. throw std::runtime_error("exception\r\n...");
  5093. });
  5094. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5095. auto se = detail::scope_exit([&] {
  5096. svr.stop();
  5097. listen_thread.join();
  5098. ASSERT_FALSE(svr.is_running());
  5099. });
  5100. svr.wait_until_ready();
  5101. Client cli("localhost", PORT);
  5102. {
  5103. auto res = cli.Get("/exception");
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5106. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5107. }
  5108. {
  5109. auto res = cli.Get("/unknown");
  5110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5112. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5113. }
  5114. }
  5115. TEST(ExceptionTest, WithExceptionHandler) {
  5116. Server svr;
  5117. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5118. std::exception_ptr ep) {
  5119. EXPECT_FALSE(ep == nullptr);
  5120. try {
  5121. std::rethrow_exception(ep);
  5122. } catch (std::exception &e) {
  5123. EXPECT_EQ("abc", std::string(e.what()));
  5124. } catch (...) {}
  5125. res.status = StatusCode::InternalServerError_500;
  5126. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5127. "text/html"); // <= Content-Length still 13 at this point
  5128. });
  5129. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5130. res.set_content("Hello World!\n", "text/plain");
  5131. throw std::runtime_error("abc");
  5132. });
  5133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5134. auto se = detail::scope_exit([&] {
  5135. svr.stop();
  5136. thread.join();
  5137. ASSERT_FALSE(svr.is_running());
  5138. });
  5139. svr.wait_until_ready();
  5140. for (size_t i = 0; i < 10; i++) {
  5141. Client cli(HOST, PORT);
  5142. for (size_t j = 0; j < 100; j++) {
  5143. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5145. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5146. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5147. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5148. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5149. }
  5150. cli.set_keep_alive(true);
  5151. for (size_t j = 0; j < 100; j++) {
  5152. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5155. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5156. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5157. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5158. }
  5159. }
  5160. }
  5161. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5162. Server svr;
  5163. svr.set_exception_handler(
  5164. [](const Request &, Response &res, std::exception_ptr) {
  5165. res.set_content("oops", "text/plain");
  5166. });
  5167. svr.Get("/throw", [](const Request &, Response &) {
  5168. throw std::runtime_error("throw");
  5169. });
  5170. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5171. res.status = StatusCode::Created_201;
  5172. throw std::runtime_error("created-then-throw");
  5173. });
  5174. auto port = svr.bind_to_any_port(HOST);
  5175. ASSERT_GT(port, 0);
  5176. thread t = thread([&] { svr.listen_after_bind(); });
  5177. auto se = detail::scope_exit([&] {
  5178. svr.stop();
  5179. t.join();
  5180. ASSERT_FALSE(svr.is_running());
  5181. });
  5182. svr.wait_until_ready();
  5183. Client cli(HOST, port);
  5184. for (auto path : {"/throw", "/created-then-throw"}) {
  5185. auto res = cli.Get(path);
  5186. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5187. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5188. }
  5189. }
  5190. TEST(ExceptionTest, AndErrorHandler) {
  5191. Server svr;
  5192. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5193. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5194. });
  5195. svr.set_exception_handler(
  5196. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5197. EXPECT_FALSE(ep == nullptr);
  5198. try {
  5199. std::rethrow_exception(ep);
  5200. } catch (std::exception &e) {
  5201. res.set_content(e.what(), "text/html");
  5202. } catch (...) {}
  5203. res.status = StatusCode::InternalServerError_500;
  5204. });
  5205. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5206. throw std::runtime_error("EXCEPTION");
  5207. });
  5208. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5209. res.set_content("ERROR", "text/html");
  5210. res.status = StatusCode::InternalServerError_500;
  5211. });
  5212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5213. auto se = detail::scope_exit([&] {
  5214. svr.stop();
  5215. thread.join();
  5216. ASSERT_FALSE(svr.is_running());
  5217. });
  5218. svr.wait_until_ready();
  5219. Client cli(HOST, PORT);
  5220. {
  5221. auto res = cli.Get("/exception");
  5222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5223. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5224. EXPECT_EQ("EXCEPTION", res->body);
  5225. }
  5226. {
  5227. auto res = cli.Get("/error");
  5228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5229. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5230. EXPECT_EQ("ERROR", res->body);
  5231. }
  5232. {
  5233. auto res = cli.Get("/invalid");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5236. EXPECT_EQ("NOT_FOUND", res->body);
  5237. }
  5238. }
  5239. #endif
  5240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5241. // An exception from a user callback outside process_request()'s try/catch
  5242. // used to unwind into the task queue - which does not catch - and terminate
  5243. // the process. Each test below runs the server on a single worker thread: a
  5244. // guard that catches the exception but still loses the thread would otherwise
  5245. // be hidden by a spare worker serving the follow-up request. Note that a
  5246. // regression here aborts the whole test binary rather than failing one test.
  5247. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5248. Server svr;
  5249. svr.new_task_queue = [] { return new ThreadPool(1); };
  5250. std::atomic<int> reported{0};
  5251. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5252. if (err == Error::UserCallbackException) { reported++; }
  5253. });
  5254. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5255. res.set_content_provider(
  5256. 1024, "text/plain",
  5257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5258. sink.write("hello", 5);
  5259. throw std::runtime_error("from the content provider");
  5260. });
  5261. });
  5262. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5263. res.set_content("ok", "text/plain");
  5264. });
  5265. auto port = svr.bind_to_any_port(HOST);
  5266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5267. auto se = detail::scope_exit([&] {
  5268. svr.stop();
  5269. listen_thread.join();
  5270. ASSERT_FALSE(svr.is_running());
  5271. });
  5272. svr.wait_until_ready();
  5273. {
  5274. Client cli(HOST, port);
  5275. cli.set_read_timeout(5, 0);
  5276. EXPECT_FALSE(cli.Get("/throw"));
  5277. }
  5278. EXPECT_TRUE(svr.is_running());
  5279. EXPECT_EQ(1, reported.load());
  5280. // A request on a fresh connection is still served.
  5281. {
  5282. Client cli(HOST, port);
  5283. auto res = cli.Get("/ok");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("ok", res->body);
  5287. }
  5288. }
  5289. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5290. Server svr;
  5291. svr.new_task_queue = [] { return new ThreadPool(1); };
  5292. std::atomic<bool> should_throw{true};
  5293. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5294. res.set_content("hi", "text/plain");
  5295. });
  5296. svr.set_post_routing_handler(
  5297. [&](const Request & /*req*/, Response & /*res*/) {
  5298. if (should_throw) {
  5299. throw std::runtime_error("from the post-routing handler");
  5300. }
  5301. });
  5302. auto port = svr.bind_to_any_port(HOST);
  5303. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5304. auto se = detail::scope_exit([&] {
  5305. svr.stop();
  5306. listen_thread.join();
  5307. ASSERT_FALSE(svr.is_running());
  5308. });
  5309. svr.wait_until_ready();
  5310. {
  5311. Client cli(HOST, port);
  5312. cli.set_read_timeout(5, 0);
  5313. EXPECT_FALSE(cli.Get("/hi"));
  5314. }
  5315. EXPECT_TRUE(svr.is_running());
  5316. should_throw = false;
  5317. {
  5318. Client cli(HOST, port);
  5319. auto res = cli.Get("/hi");
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. EXPECT_EQ("hi", res->body);
  5323. }
  5324. }
  5325. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5326. // The guard reports the caught exception through the error logger, which is
  5327. // a user callback too. A logger that throws has to be contained as well, or
  5328. // the process would terminate from inside the catch.
  5329. Server svr;
  5330. svr.new_task_queue = [] { return new ThreadPool(1); };
  5331. std::atomic<int> reported{0};
  5332. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5333. if (err == Error::UserCallbackException) {
  5334. reported++;
  5335. throw std::runtime_error("from the error logger");
  5336. }
  5337. });
  5338. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5339. res.set_content_provider(
  5340. 1024, "text/plain",
  5341. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5342. sink.write("hello", 5);
  5343. throw std::runtime_error("from the content provider");
  5344. });
  5345. });
  5346. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5347. res.set_content("ok", "text/plain");
  5348. });
  5349. auto port = svr.bind_to_any_port(HOST);
  5350. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5351. auto se = detail::scope_exit([&] {
  5352. svr.stop();
  5353. listen_thread.join();
  5354. ASSERT_FALSE(svr.is_running());
  5355. });
  5356. svr.wait_until_ready();
  5357. {
  5358. Client cli(HOST, port);
  5359. cli.set_read_timeout(5, 0);
  5360. EXPECT_FALSE(cli.Get("/throw"));
  5361. }
  5362. EXPECT_TRUE(svr.is_running());
  5363. EXPECT_EQ(1, reported.load());
  5364. {
  5365. Client cli(HOST, port);
  5366. auto res = cli.Get("/ok");
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. EXPECT_EQ(StatusCode::OK_200, res->status);
  5369. EXPECT_EQ("ok", res->body);
  5370. }
  5371. }
  5372. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5373. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5374. // so the exception unwinds through the ws::WebSocket object on its way to
  5375. // the guard. None of the HTTP cases above cross that.
  5376. Server svr;
  5377. svr.new_task_queue = [] { return new ThreadPool(1); };
  5378. std::atomic<int> reported{0};
  5379. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5380. if (err == Error::UserCallbackException) { reported++; }
  5381. });
  5382. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5383. throw std::runtime_error("from the WebSocket handler");
  5384. });
  5385. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5386. res.set_content("ok", "text/plain");
  5387. });
  5388. auto port = svr.bind_to_any_port(HOST);
  5389. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5390. auto se = detail::scope_exit([&] {
  5391. svr.stop();
  5392. listen_thread.join();
  5393. ASSERT_FALSE(svr.is_running());
  5394. });
  5395. svr.wait_until_ready();
  5396. {
  5397. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5398. "/ws");
  5399. auto res = client.connect();
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. // The server dropped the connection instead of dying.
  5402. std::string msg;
  5403. EXPECT_FALSE(client.read(msg));
  5404. client.close();
  5405. }
  5406. EXPECT_TRUE(svr.is_running());
  5407. EXPECT_EQ(1, reported.load());
  5408. {
  5409. Client cli(HOST, port);
  5410. auto res = cli.Get("/ok");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. EXPECT_EQ("ok", res->body);
  5414. }
  5415. }
  5416. #ifdef CPPHTTPLIB_SSL_ENABLED
  5417. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5418. // SSLServer serves through its own connection type, so it is exercised on
  5419. // its own.
  5420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5421. ASSERT_TRUE(svr.is_valid());
  5422. svr.new_task_queue = [] { return new ThreadPool(1); };
  5423. std::atomic<int> reported{0};
  5424. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5425. if (err == Error::UserCallbackException) { reported++; }
  5426. });
  5427. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5428. res.set_content_provider(
  5429. 1024, "text/plain",
  5430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5431. sink.write("hello", 5);
  5432. throw std::runtime_error("from the content provider");
  5433. });
  5434. });
  5435. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5436. res.set_content("ok", "text/plain");
  5437. });
  5438. auto port = svr.bind_to_any_port(HOST);
  5439. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5440. auto se = detail::scope_exit([&] {
  5441. svr.stop();
  5442. listen_thread.join();
  5443. ASSERT_FALSE(svr.is_running());
  5444. });
  5445. svr.wait_until_ready();
  5446. {
  5447. SSLClient cli(HOST, port);
  5448. cli.enable_server_certificate_verification(false);
  5449. cli.set_read_timeout(5, 0);
  5450. EXPECT_FALSE(cli.Get("/throw"));
  5451. }
  5452. EXPECT_TRUE(svr.is_running());
  5453. EXPECT_EQ(1, reported.load());
  5454. {
  5455. SSLClient cli(HOST, port);
  5456. cli.enable_server_certificate_verification(false);
  5457. auto res = cli.Get("/ok");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. EXPECT_EQ("ok", res->body);
  5461. }
  5462. }
  5463. #endif
  5464. #endif
  5465. TEST(NoContentTest, ContentLength) {
  5466. Server svr;
  5467. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5468. res.status = StatusCode::NoContent_204;
  5469. });
  5470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5471. auto se = detail::scope_exit([&] {
  5472. svr.stop();
  5473. thread.join();
  5474. ASSERT_FALSE(svr.is_running());
  5475. });
  5476. svr.wait_until_ready();
  5477. {
  5478. Client cli(HOST, PORT);
  5479. auto res = cli.Get("/hi");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5482. // RFC 9110 8.6: none in a 204 response
  5483. EXPECT_FALSE(res->has_header("Content-Length"));
  5484. }
  5485. }
  5486. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5487. Server svr;
  5488. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5489. res.set_header("Content-Length", "5");
  5490. res.set_content("hello world", "text/plain");
  5491. });
  5492. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5493. // A body that reads as the last chunk, were it taken as chunked
  5494. res.set_header("Transfer-Encoding", "chunked");
  5495. res.set_content("0\r\n\r\n", "text/plain");
  5496. });
  5497. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5498. res.set_header("Content-Length", "2");
  5499. res.set_content_provider(5, "text/plain",
  5500. [](size_t offset, size_t length, DataSink &sink) {
  5501. sink.write(&"hello"[offset], length);
  5502. return true;
  5503. });
  5504. });
  5505. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5506. res.set_header("Content-Length", "1234");
  5507. });
  5508. thread t = thread([&] { svr.listen(HOST, PORT); });
  5509. auto se = detail::scope_exit([&] {
  5510. svr.stop();
  5511. t.join();
  5512. ASSERT_FALSE(svr.is_running());
  5513. });
  5514. svr.wait_until_ready();
  5515. Client cli(HOST, PORT);
  5516. cli.set_read_timeout(1, 0);
  5517. auto expect_body = [&](const Result &res, const std::string &body) {
  5518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5519. EXPECT_EQ(body, res->body);
  5520. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5521. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5522. };
  5523. Headers identity{{"Accept-Encoding", ""}};
  5524. expect_body(cli.Get("/body", identity), "hello world");
  5525. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5526. expect_body(cli.Get("/body",
  5527. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5528. "he");
  5529. expect_body(cli.Get("/provider", identity), "hello");
  5530. expect_body(cli.Get("/empty", identity), "");
  5531. // A HEAD response may give the length of the body a GET would get.
  5532. auto res = cli.Head("/empty");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5535. }
  5536. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5537. Server svr;
  5538. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5539. res.set_content("short", "text/plain");
  5540. });
  5541. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5542. res.body += " with a footer";
  5543. res.set_header("Transfer-Encoding", "chunked");
  5544. });
  5545. thread t = thread([&] { svr.listen(HOST, PORT); });
  5546. auto se = detail::scope_exit([&] {
  5547. svr.stop();
  5548. t.join();
  5549. ASSERT_FALSE(svr.is_running());
  5550. });
  5551. svr.wait_until_ready();
  5552. Client cli(HOST, PORT);
  5553. cli.set_read_timeout(1, 0);
  5554. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ("short with a footer", res->body);
  5557. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5558. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5559. }
  5560. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5561. Server svr;
  5562. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5563. res.set_header("Content-Length", "3");
  5564. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5565. sink.write("abc", 3);
  5566. sink.done();
  5567. return true;
  5568. });
  5569. });
  5570. thread t = thread([&] { svr.listen(HOST, PORT); });
  5571. auto se = detail::scope_exit([&] {
  5572. svr.stop();
  5573. t.join();
  5574. ASSERT_FALSE(svr.is_running());
  5575. });
  5576. svr.wait_until_ready();
  5577. Client cli(HOST, PORT);
  5578. cli.set_keep_alive(true);
  5579. auto res = cli.Get("/");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ("abc", res->body);
  5582. EXPECT_FALSE(res->has_header("Content-Length"));
  5583. EXPECT_EQ("close", res->get_header_value("Connection"));
  5584. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5585. // No body to delimit
  5586. auto head = cli.Head("/");
  5587. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5588. EXPECT_FALSE(head->has_header("Connection"));
  5589. }
  5590. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5591. #ifdef CPPHTTPLIB_SSL_ENABLED
  5592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5593. ASSERT_TRUE(svr.is_valid());
  5594. #else
  5595. Server svr;
  5596. #endif
  5597. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5598. if (req.path == "/routing_handler") {
  5599. res.set_header("PRE_ROUTING", "on");
  5600. res.set_content("Routing Handler", "text/plain");
  5601. return httplib::Server::HandlerResponse::Handled;
  5602. }
  5603. return httplib::Server::HandlerResponse::Unhandled;
  5604. });
  5605. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5606. res.set_content("Error", "text/html");
  5607. });
  5608. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5609. if (req.path == "/routing_handler") {
  5610. res.set_header("POST_ROUTING", "on");
  5611. }
  5612. });
  5613. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5614. res.set_content("Hello World!\n", "text/plain");
  5615. });
  5616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5617. auto se = detail::scope_exit([&] {
  5618. svr.stop();
  5619. thread.join();
  5620. ASSERT_FALSE(svr.is_running());
  5621. });
  5622. svr.wait_until_ready();
  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("/routing_handler");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("Routing Handler", res->body);
  5634. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5635. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5636. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5637. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5638. }
  5639. {
  5640. #ifdef CPPHTTPLIB_SSL_ENABLED
  5641. SSLClient cli(HOST, PORT);
  5642. cli.enable_server_certificate_verification(false);
  5643. #else
  5644. Client cli(HOST, PORT);
  5645. #endif
  5646. auto res = cli.Get("/hi");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. EXPECT_EQ(StatusCode::OK_200, res->status);
  5649. EXPECT_EQ("Hello World!\n", res->body);
  5650. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5651. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5652. }
  5653. {
  5654. #ifdef CPPHTTPLIB_SSL_ENABLED
  5655. SSLClient cli(HOST, PORT);
  5656. cli.enable_server_certificate_verification(false);
  5657. #else
  5658. Client cli(HOST, PORT);
  5659. #endif
  5660. auto res = cli.Get("/aaa");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5663. EXPECT_EQ("Error", res->body);
  5664. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5665. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5666. }
  5667. }
  5668. TEST(RequestHandlerTest, PreRequestHandler) {
  5669. auto route_path = "/user/:user";
  5670. Server svr;
  5671. svr.Get("/hi", [](const Request &, Response &res) {
  5672. res.set_content("hi", "text/plain");
  5673. });
  5674. svr.Get(route_path, [](const Request &req, Response &res) {
  5675. res.set_content(req.path_params.at("user"), "text/plain");
  5676. });
  5677. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5678. if (req.matched_route == route_path) {
  5679. auto user = req.path_params.at("user");
  5680. if (user != "john") {
  5681. res.status = StatusCode::Forbidden_403;
  5682. res.set_content("error", "text/html");
  5683. return Server::HandlerResponse::Handled;
  5684. }
  5685. }
  5686. return Server::HandlerResponse::Unhandled;
  5687. });
  5688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5689. auto se = detail::scope_exit([&] {
  5690. svr.stop();
  5691. thread.join();
  5692. ASSERT_FALSE(svr.is_running());
  5693. });
  5694. svr.wait_until_ready();
  5695. Client cli(HOST, PORT);
  5696. {
  5697. auto res = cli.Get("/hi");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ("hi", res->body);
  5701. }
  5702. {
  5703. auto res = cli.Get("/user/john");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ("john", res->body);
  5707. }
  5708. {
  5709. auto res = cli.Get("/user/invalid-user");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5712. EXPECT_EQ("error", res->body);
  5713. }
  5714. }
  5715. // The pre-request handler must run before the request body is read, so a
  5716. // rejected request never forces the server to buffer a (potentially large)
  5717. // body. Here the posted body is larger than the payload limit: if the body
  5718. // were read first the server would answer 413, but because the pre-request
  5719. // handler runs first it answers 403 and the body is never read.
  5720. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5721. Server svr;
  5722. svr.set_payload_max_length(8);
  5723. auto handler_ran = false;
  5724. svr.Post("/reject", [&](const Request &req, Response &res) {
  5725. handler_ran = true;
  5726. res.set_content(req.body, "text/plain");
  5727. });
  5728. svr.Post("/accept", [](const Request &req, Response &res) {
  5729. res.set_content(req.body, "text/plain");
  5730. });
  5731. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5732. if (req.matched_route == "/reject") {
  5733. res.status = StatusCode::Forbidden_403;
  5734. res.set_content("denied", "text/plain");
  5735. return Server::HandlerResponse::Handled;
  5736. }
  5737. return Server::HandlerResponse::Unhandled;
  5738. });
  5739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5740. auto se = detail::scope_exit([&] {
  5741. svr.stop();
  5742. thread.join();
  5743. ASSERT_FALSE(svr.is_running());
  5744. });
  5745. svr.wait_until_ready();
  5746. Client cli(HOST, PORT);
  5747. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5748. // rejects with 403 before the body is read, so 413 is never reached.
  5749. {
  5750. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5753. EXPECT_EQ("denied", res->body);
  5754. EXPECT_FALSE(handler_ran);
  5755. }
  5756. // An approved route still reads the body and enforces the payload limit.
  5757. {
  5758. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5761. }
  5762. }
  5763. TEST(UserDataTest, BasicOperations) {
  5764. httplib::UserData ud;
  5765. // Initially empty
  5766. EXPECT_FALSE(ud.has("key"));
  5767. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5768. // set and get
  5769. ud.set("key", 42);
  5770. EXPECT_TRUE(ud.has("key"));
  5771. auto *p = ud.get<int>("key");
  5772. ASSERT_NE(nullptr, p);
  5773. EXPECT_EQ(42, *p);
  5774. // Type mismatch → nullptr
  5775. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5776. // Overwrite with different type
  5777. ud.set("key", std::string("hello"));
  5778. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5779. auto *s = ud.get<std::string>("key");
  5780. ASSERT_NE(nullptr, s);
  5781. EXPECT_EQ("hello", *s);
  5782. // erase
  5783. ud.erase("key");
  5784. EXPECT_FALSE(ud.has("key"));
  5785. // clear
  5786. ud.set("a", 1);
  5787. ud.set("b", 2);
  5788. ud.clear();
  5789. EXPECT_FALSE(ud.has("a"));
  5790. EXPECT_FALSE(ud.has("b"));
  5791. }
  5792. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5793. struct AuthCtx {
  5794. std::string user_id;
  5795. };
  5796. Server svr;
  5797. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5798. res.user_data.set("auth", AuthCtx{"alice"});
  5799. return Server::HandlerResponse::Unhandled;
  5800. });
  5801. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5802. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5803. ASSERT_NE(nullptr, ctx);
  5804. res.set_content("Hello " + ctx->user_id, "text/plain");
  5805. });
  5806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5807. auto se = detail::scope_exit([&] {
  5808. svr.stop();
  5809. thread.join();
  5810. ASSERT_FALSE(svr.is_running());
  5811. });
  5812. svr.wait_until_ready();
  5813. Client cli(HOST, PORT);
  5814. auto res = cli.Get("/me");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("Hello alice", res->body);
  5818. }
  5819. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5820. struct RoleCtx {
  5821. std::string role;
  5822. };
  5823. Server svr;
  5824. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5825. res.user_data.set("role", RoleCtx{"admin"});
  5826. return Server::HandlerResponse::Unhandled;
  5827. });
  5828. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5829. auto *ctx = res.user_data.get<RoleCtx>("role");
  5830. ASSERT_NE(nullptr, ctx);
  5831. res.set_content(ctx->role, "text/plain");
  5832. });
  5833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5834. auto se = detail::scope_exit([&] {
  5835. svr.stop();
  5836. thread.join();
  5837. ASSERT_FALSE(svr.is_running());
  5838. });
  5839. svr.wait_until_ready();
  5840. Client cli(HOST, PORT);
  5841. auto res = cli.Get("/role");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("admin", res->body);
  5845. }
  5846. TEST(InvalidFormatTest, StatusCode) {
  5847. Server svr;
  5848. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5849. res.set_content("Hello World!\n", "text/plain");
  5850. res.status = 9999; // Status should be a three-digit code...
  5851. });
  5852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5853. auto se = detail::scope_exit([&] {
  5854. svr.stop();
  5855. thread.join();
  5856. ASSERT_FALSE(svr.is_running());
  5857. });
  5858. svr.wait_until_ready();
  5859. {
  5860. Client cli(HOST, PORT);
  5861. auto res = cli.Get("/hi");
  5862. ASSERT_FALSE(res);
  5863. }
  5864. }
  5865. TEST(URLFragmentTest, WithFragment) {
  5866. Server svr;
  5867. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5868. EXPECT_TRUE(req.target == "/hi");
  5869. });
  5870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5871. auto se = detail::scope_exit([&] {
  5872. svr.stop();
  5873. thread.join();
  5874. ASSERT_FALSE(svr.is_running());
  5875. });
  5876. svr.wait_until_ready();
  5877. {
  5878. Client cli(HOST, PORT);
  5879. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5880. EXPECT_TRUE(res);
  5881. EXPECT_EQ(StatusCode::OK_200, res->status);
  5882. res = cli.Get("/hi%23key1=val1=key2=val2");
  5883. EXPECT_TRUE(res);
  5884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5885. }
  5886. }
  5887. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5888. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5889. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5890. Server svr;
  5891. std::vector<std::string> targets;
  5892. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5893. targets.push_back(req.target);
  5894. });
  5895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5896. auto se = detail::scope_exit([&] {
  5897. svr.stop();
  5898. thread.join();
  5899. ASSERT_FALSE(svr.is_running());
  5900. });
  5901. svr.wait_until_ready();
  5902. Client cli(HOST, PORT);
  5903. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5904. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5905. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5906. // A '?' after the '#' belongs to the fragment, not to the query.
  5907. Request req;
  5908. req.method = "GET";
  5909. req.path = "/hi#f?x=1";
  5910. req.params.emplace("a", "1");
  5911. Response res;
  5912. auto error = Error::Success;
  5913. EXPECT_TRUE(cli.send(req, res, error));
  5914. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5915. "/hi?a=1"}),
  5916. targets);
  5917. }
  5918. TEST(HeaderWriter, SetHeaderWriter) {
  5919. Server svr;
  5920. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5921. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5922. return detail::write_headers(strm, hdrs);
  5923. });
  5924. svr.Get("/hi", [](const Request &req, Response &res) {
  5925. auto it = req.headers.find("CustomClientHeader");
  5926. EXPECT_TRUE(it != req.headers.end());
  5927. EXPECT_EQ(it->second, "CustomClientValue");
  5928. res.set_content("Hello World!\n", "text/plain");
  5929. });
  5930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5931. auto se = detail::scope_exit([&] {
  5932. svr.stop();
  5933. thread.join();
  5934. ASSERT_FALSE(svr.is_running());
  5935. });
  5936. svr.wait_until_ready();
  5937. {
  5938. Client cli(HOST, PORT);
  5939. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5940. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5941. return detail::write_headers(strm, hdrs);
  5942. });
  5943. auto res = cli.Get("/hi");
  5944. EXPECT_TRUE(res);
  5945. EXPECT_EQ(StatusCode::OK_200, res->status);
  5946. auto it = res->headers.find("CustomServerHeader");
  5947. EXPECT_TRUE(it != res->headers.end());
  5948. EXPECT_EQ(it->second, "CustomServerValue");
  5949. }
  5950. }
  5951. class ServerTest : public ::testing::Test {
  5952. protected:
  5953. ServerTest()
  5954. : cli_(HOST, PORT)
  5955. #ifdef CPPHTTPLIB_SSL_ENABLED
  5956. ,
  5957. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5958. #endif
  5959. {
  5960. #ifdef CPPHTTPLIB_SSL_ENABLED
  5961. cli_.enable_server_certificate_verification(false);
  5962. #endif
  5963. // Allow LARGE_DATA (100MB) responses
  5964. cli_.set_payload_max_length(200 * 1024 * 1024);
  5965. }
  5966. virtual void SetUp() {
  5967. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5968. svr_.set_payload_max_length(200 * 1024 * 1024);
  5969. svr_.set_mount_point("/", "./www");
  5970. svr_.set_mount_point("/mount", "./www2");
  5971. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5972. svr_.Get("/hi",
  5973. [&](const Request & /*req*/, Response &res) {
  5974. res.set_content("Hello World!", "text/plain");
  5975. })
  5976. .Get("/file_content",
  5977. [&](const Request & /*req*/, Response &res) {
  5978. res.set_file_content("./www/dir/test.html");
  5979. })
  5980. .Get("/file_content_with_content_type",
  5981. [&](const Request & /*req*/, Response &res) {
  5982. res.set_file_content("./www/file", "text/plain");
  5983. })
  5984. .Get("/invalid_file_content",
  5985. [&](const Request & /*req*/, Response &res) {
  5986. res.set_file_content("./www/dir/invalid_file_path");
  5987. })
  5988. .Get("/http_response_splitting",
  5989. [&](const Request & /*req*/, Response &res) {
  5990. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5991. EXPECT_EQ(0U, res.headers.size());
  5992. EXPECT_FALSE(res.has_header("a"));
  5993. res.set_header("a", "1\nSet-Cookie: a=1");
  5994. EXPECT_EQ(0U, res.headers.size());
  5995. EXPECT_FALSE(res.has_header("a"));
  5996. res.set_header("a", "1\rSet-Cookie: a=1");
  5997. EXPECT_EQ(0U, res.headers.size());
  5998. EXPECT_FALSE(res.has_header("a"));
  5999. res.set_header("a\r\nb", "0");
  6000. EXPECT_EQ(0U, res.headers.size());
  6001. EXPECT_FALSE(res.has_header("a"));
  6002. res.set_header("a\rb", "0");
  6003. EXPECT_EQ(0U, res.headers.size());
  6004. EXPECT_FALSE(res.has_header("a"));
  6005. res.set_header("a\nb", "0");
  6006. EXPECT_EQ(0U, res.headers.size());
  6007. EXPECT_FALSE(res.has_header("a"));
  6008. res.set_redirect("1\r\nSet-Cookie: a=1");
  6009. EXPECT_EQ(0U, res.headers.size());
  6010. EXPECT_FALSE(res.has_header("Location"));
  6011. })
  6012. .Get("/slow",
  6013. [&](const Request & /*req*/, Response &res) {
  6014. std::this_thread::sleep_for(std::chrono::seconds(4));
  6015. res.set_content("slow", "text/plain");
  6016. })
  6017. #if 0
  6018. .Post("/slowpost",
  6019. [&](const Request & /*req*/, Response &res) {
  6020. std::this_thread::sleep_for(std::chrono::seconds(2));
  6021. res.set_content("slow", "text/plain");
  6022. })
  6023. #endif
  6024. .Get("/remote_addr",
  6025. [&](const Request &req, Response &res) {
  6026. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6027. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6028. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6029. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6030. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6031. #endif
  6032. res.set_content(req.remote_addr, "text/plain");
  6033. })
  6034. .Get("/local_addr",
  6035. [&](const Request &req, Response &res) {
  6036. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6037. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6038. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6039. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6040. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6041. #endif
  6042. auto local_addr = req.local_addr;
  6043. auto local_port = std::to_string(req.local_port);
  6044. res.set_content(local_addr.append(":").append(local_port),
  6045. "text/plain");
  6046. })
  6047. .Get("/endwith%",
  6048. [&](const Request & /*req*/, Response &res) {
  6049. res.set_content("Hello World!", "text/plain");
  6050. })
  6051. .Get("/a\\+\\+b",
  6052. [&](const Request &req, Response &res) {
  6053. ASSERT_TRUE(req.has_param("a +b"));
  6054. auto val = req.get_param_value("a +b");
  6055. res.set_content(val, "text/plain");
  6056. })
  6057. .Get("/", [&](const Request & /*req*/,
  6058. Response &res) { res.set_redirect("/hi"); })
  6059. .Post("/1",
  6060. [](const Request & /*req*/, Response &res) {
  6061. res.set_redirect("/2", StatusCode::SeeOther_303);
  6062. })
  6063. .Get("/2",
  6064. [](const Request & /*req*/, Response &res) {
  6065. res.set_content("redirected.", "text/plain");
  6066. res.status = StatusCode::OK_200;
  6067. })
  6068. .Post("/person",
  6069. [&](const Request &req, Response &res) {
  6070. if (req.has_param("name") && req.has_param("note")) {
  6071. persons_[req.get_param_value("name")] =
  6072. req.get_param_value("note");
  6073. } else {
  6074. res.status = StatusCode::BadRequest_400;
  6075. }
  6076. })
  6077. .Put("/person",
  6078. [&](const Request &req, Response &res) {
  6079. if (req.has_param("name") && req.has_param("note")) {
  6080. persons_[req.get_param_value("name")] =
  6081. req.get_param_value("note");
  6082. } else {
  6083. res.status = StatusCode::BadRequest_400;
  6084. }
  6085. })
  6086. .Get("/person/(.*)",
  6087. [&](const Request &req, Response &res) {
  6088. string name = req.matches[1];
  6089. if (persons_.find(name) != persons_.end()) {
  6090. auto note = persons_[name];
  6091. res.set_content(note, "text/plain");
  6092. } else {
  6093. res.status = StatusCode::NotFound_404;
  6094. }
  6095. })
  6096. .Delete("/person",
  6097. [&](const Request &req, Response &res) {
  6098. if (req.has_param("name")) {
  6099. string name = req.get_param_value("name");
  6100. if (persons_.find(name) != persons_.end()) {
  6101. persons_.erase(name);
  6102. res.set_content("DELETED", "text/plain");
  6103. } else {
  6104. res.status = StatusCode::NotFound_404;
  6105. }
  6106. } else {
  6107. res.status = StatusCode::BadRequest_400;
  6108. }
  6109. })
  6110. .Post("/x-www-form-urlencoded-json",
  6111. [&](const Request &req, Response &res) {
  6112. auto json = req.get_param_value("json");
  6113. ASSERT_EQ(JSON_DATA, json);
  6114. res.set_content(json, "appliation/json");
  6115. res.status = StatusCode::OK_200;
  6116. })
  6117. .Get("/streamed-chunked",
  6118. [&](const Request & /*req*/, Response &res) {
  6119. res.set_chunked_content_provider(
  6120. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6121. sink.os << "123";
  6122. sink.os << "456";
  6123. sink.os << "789";
  6124. sink.done();
  6125. return true;
  6126. });
  6127. })
  6128. .Get("/streamed-chunked-with-prohibited-trailer",
  6129. [&](const Request & /*req*/, Response &res) {
  6130. auto i = new int(0);
  6131. // Declare both a prohibited trailer (Content-Length) and an
  6132. // allowed one
  6133. res.set_header("Trailer", "Content-Length, X-Allowed");
  6134. res.set_chunked_content_provider(
  6135. "text/plain",
  6136. [i](size_t /*offset*/, DataSink &sink) {
  6137. switch (*i) {
  6138. case 0: sink.os << "123"; break;
  6139. case 1: sink.os << "456"; break;
  6140. case 2: sink.os << "789"; break;
  6141. case 3: {
  6142. sink.done_with_trailer(
  6143. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6144. } break;
  6145. }
  6146. (*i)++;
  6147. return true;
  6148. },
  6149. [i](bool success) {
  6150. EXPECT_TRUE(success);
  6151. delete i;
  6152. });
  6153. })
  6154. .Get("/streamed-chunked2",
  6155. [&](const Request & /*req*/, Response &res) {
  6156. auto i = new int(0);
  6157. res.set_chunked_content_provider(
  6158. "text/plain",
  6159. [i](size_t /*offset*/, DataSink &sink) {
  6160. switch (*i) {
  6161. case 0: sink.os << "123"; break;
  6162. case 1: sink.os << "456"; break;
  6163. case 2: sink.os << "789"; break;
  6164. case 3: sink.done(); break;
  6165. }
  6166. (*i)++;
  6167. return true;
  6168. },
  6169. [i](bool success) {
  6170. EXPECT_TRUE(success);
  6171. delete i;
  6172. });
  6173. })
  6174. .Get("/streamed-chunked-with-trailer",
  6175. [&](const Request & /*req*/, Response &res) {
  6176. auto i = new int(0);
  6177. res.set_header("Trailer", "Dummy1, Dummy2");
  6178. res.set_chunked_content_provider(
  6179. "text/plain",
  6180. [i](size_t /*offset*/, DataSink &sink) {
  6181. switch (*i) {
  6182. case 0: sink.os << "123"; break;
  6183. case 1: sink.os << "456"; break;
  6184. case 2: sink.os << "789"; break;
  6185. case 3: {
  6186. sink.done_with_trailer(
  6187. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6188. } break;
  6189. }
  6190. (*i)++;
  6191. return true;
  6192. },
  6193. [i](bool success) {
  6194. EXPECT_TRUE(success);
  6195. delete i;
  6196. });
  6197. })
  6198. .Get("/streamed",
  6199. [&](const Request & /*req*/, Response &res) {
  6200. res.set_content_provider(
  6201. 6, "text/plain",
  6202. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6203. sink.os << (offset < 3 ? "a" : "b");
  6204. return true;
  6205. });
  6206. })
  6207. .Get("/streamed-without-length",
  6208. [&](const Request & /*req*/, Response &res) {
  6209. auto data = new std::string("abcdefg");
  6210. res.set_content_provider(
  6211. "text/plain",
  6212. [data](size_t offset, DataSink &sink) {
  6213. if (offset < data->size()) {
  6214. sink.os << data->substr(offset);
  6215. }
  6216. sink.done();
  6217. return true;
  6218. },
  6219. [data](bool success) {
  6220. EXPECT_TRUE(success);
  6221. delete data;
  6222. });
  6223. })
  6224. .Get("/streamed-with-range",
  6225. [&](const Request &req, Response &res) {
  6226. auto data = new std::string("abcdefg");
  6227. // An explicit status keeps the server from picking the 206 it
  6228. // would otherwise choose for a ranged request, so the response
  6229. // is not a partial representation.
  6230. auto status = req.get_param_value("status");
  6231. if (status == "200") {
  6232. res.status = StatusCode::OK_200;
  6233. } else if (status == "403") {
  6234. res.status = StatusCode::Forbidden_403;
  6235. }
  6236. res.set_content_provider(
  6237. data->size(), "text/plain",
  6238. [data](size_t offset, size_t length, DataSink &sink) {
  6239. size_t DATA_CHUNK_SIZE = 4;
  6240. const auto &d = *data;
  6241. auto out_len =
  6242. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6243. auto ret =
  6244. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6245. EXPECT_TRUE(ret);
  6246. return true;
  6247. },
  6248. [data, &req](bool success) {
  6249. EXPECT_EQ(success, !req.has_param("error"));
  6250. delete data;
  6251. });
  6252. })
  6253. .Get("/streamed-cancel",
  6254. [&](const Request & /*req*/, Response &res) {
  6255. res.set_content_provider(
  6256. size_t(-1), "text/plain",
  6257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6258. sink.os << "data_chunk";
  6259. return true;
  6260. });
  6261. })
  6262. .Get("/regex-with-delimiter",
  6263. [&](const Request &req, Response & /*res*/) {
  6264. ASSERT_TRUE(req.has_param("key"));
  6265. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6266. })
  6267. .Get("/with-range",
  6268. [&](const Request & /*req*/, Response &res) {
  6269. res.set_content("abcdefg", "text/plain");
  6270. })
  6271. .Get("/test-start-time",
  6272. [&](const Request &req, Response & /*res*/) {
  6273. EXPECT_NE(req.start_time_,
  6274. std::chrono::steady_clock::time_point::min());
  6275. })
  6276. .Get("/with-range-customized-response",
  6277. [&](const Request & /*req*/, Response &res) {
  6278. res.status = StatusCode::BadRequest_400;
  6279. res.set_content(JSON_DATA, "application/json");
  6280. })
  6281. .Post("/chunked",
  6282. [&](const Request &req, Response & /*res*/) {
  6283. EXPECT_EQ(req.body, "dechunked post body");
  6284. })
  6285. .Post("/large-chunked",
  6286. [&](const Request &req, Response & /*res*/) {
  6287. std::string expected(6 * 30 * 1024u, 'a');
  6288. EXPECT_EQ(req.body, expected);
  6289. })
  6290. .Post("/multipart",
  6291. [&](const Request &req, Response & /*res*/) {
  6292. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6293. req.form.get_field_count("text2") +
  6294. req.form.get_field_count("file3") +
  6295. req.form.get_field_count("file4"));
  6296. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6297. req.form.get_file_count("file2"));
  6298. ASSERT_TRUE(!req.form.has_file("???"));
  6299. ASSERT_TRUE(!req.form.has_field("???"));
  6300. ASSERT_TRUE(req.body.empty());
  6301. {
  6302. const auto &text = req.form.get_field("text1");
  6303. EXPECT_EQ("text default", text);
  6304. }
  6305. {
  6306. const auto &text = req.form.get_field("text2");
  6307. EXPECT_EQ("aωb", text);
  6308. }
  6309. {
  6310. const auto &file = req.form.get_file("file1");
  6311. EXPECT_EQ("hello.txt", file.filename);
  6312. EXPECT_EQ("text/plain", file.content_type);
  6313. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6314. }
  6315. {
  6316. const auto &file = req.form.get_file("file2");
  6317. EXPECT_EQ("world.json", file.filename);
  6318. EXPECT_EQ("application/json", file.content_type);
  6319. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6320. }
  6321. {
  6322. const auto &text = req.form.get_field("file3");
  6323. EXPECT_EQ(0u, text.size());
  6324. }
  6325. {
  6326. const auto &text = req.form.get_field("file4");
  6327. EXPECT_EQ(0u, text.size());
  6328. }
  6329. })
  6330. .Post("/multipart/multi_file_values",
  6331. [&](const Request &req, Response & /*res*/) {
  6332. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6333. req.form.get_field_count("multi_text1"));
  6334. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6335. ASSERT_TRUE(!req.form.has_file("???"));
  6336. ASSERT_TRUE(!req.form.has_field("???"));
  6337. ASSERT_TRUE(req.body.empty());
  6338. {
  6339. const auto &text = req.form.get_field("text");
  6340. EXPECT_EQ("default text", text);
  6341. }
  6342. {
  6343. const auto &text1_values = req.form.get_fields("multi_text1");
  6344. EXPECT_EQ(2u, text1_values.size());
  6345. EXPECT_EQ("aaaaa", text1_values[0]);
  6346. EXPECT_EQ("bbbbb", text1_values[1]);
  6347. }
  6348. {
  6349. const auto &file1_values = req.form.get_files("multi_file1");
  6350. EXPECT_EQ(2u, file1_values.size());
  6351. auto file1 = file1_values[0];
  6352. EXPECT_EQ(file1.filename, "hello.txt");
  6353. EXPECT_EQ(file1.content_type, "text/plain");
  6354. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6355. auto file2 = file1_values[1];
  6356. EXPECT_EQ(file2.filename, "world.json");
  6357. EXPECT_EQ(file2.content_type, "application/json");
  6358. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6359. }
  6360. })
  6361. .Post("/empty",
  6362. [&](const Request &req, Response &res) {
  6363. EXPECT_EQ(req.body, "");
  6364. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6365. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6366. res.set_content("empty", "text/plain");
  6367. })
  6368. .Post("/empty-no-content-type",
  6369. [&](const Request &req, Response &res) {
  6370. EXPECT_EQ(req.body, "");
  6371. EXPECT_FALSE(req.has_header("Content-Type"));
  6372. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6373. res.set_content("empty-no-content-type", "text/plain");
  6374. })
  6375. .Post("/path-only",
  6376. [&](const Request &req, Response &res) {
  6377. EXPECT_EQ(req.body, "");
  6378. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6379. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6380. res.set_content("path-only", "text/plain");
  6381. })
  6382. .Post("/path-headers-only",
  6383. [&](const Request &req, Response &res) {
  6384. EXPECT_EQ(req.body, "");
  6385. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6386. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6387. EXPECT_EQ("world", req.get_header_value("hello"));
  6388. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6389. res.set_content("path-headers-only", "text/plain");
  6390. })
  6391. .Post("/post-large",
  6392. [&](const Request &req, Response &res) {
  6393. EXPECT_EQ(req.body, LARGE_DATA);
  6394. res.set_content(req.body, "text/plain");
  6395. })
  6396. .Post("/post-loopback",
  6397. [&](const Request &, Response &res,
  6398. ContentReader const &content_reader) {
  6399. std::string body;
  6400. content_reader([&](const char *data, size_t data_length) {
  6401. body.append(data, data_length);
  6402. return true;
  6403. });
  6404. res.set_content(body, "text/plain");
  6405. })
  6406. .Put("/put-loopback",
  6407. [&](const Request &, Response &res,
  6408. ContentReader const &content_reader) {
  6409. std::string body;
  6410. content_reader([&](const char *data, size_t data_length) {
  6411. body.append(data, data_length);
  6412. return true;
  6413. });
  6414. res.set_content(body, "text/plain");
  6415. })
  6416. .Patch("/patch-loopback",
  6417. [&](const Request &, Response &res,
  6418. ContentReader const &content_reader) {
  6419. std::string body;
  6420. content_reader([&](const char *data, size_t data_length) {
  6421. body.append(data, data_length);
  6422. return true;
  6423. });
  6424. res.set_content(body, "text/plain");
  6425. })
  6426. .Put("/empty-no-content-type",
  6427. [&](const Request &req, Response &res) {
  6428. EXPECT_EQ(req.body, "");
  6429. EXPECT_FALSE(req.has_header("Content-Type"));
  6430. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6431. res.set_content("empty-no-content-type", "text/plain");
  6432. })
  6433. .Put("/put",
  6434. [&](const Request &req, Response &res) {
  6435. EXPECT_EQ(req.body, "PUT");
  6436. res.set_content(req.body, "text/plain");
  6437. })
  6438. .Put("/put-large",
  6439. [&](const Request &req, Response &res) {
  6440. EXPECT_EQ(req.body, LARGE_DATA);
  6441. res.set_content(req.body, "text/plain");
  6442. })
  6443. .Patch("/patch",
  6444. [&](const Request &req, Response &res) {
  6445. EXPECT_EQ(req.body, "PATCH");
  6446. res.set_content(req.body, "text/plain");
  6447. })
  6448. .Delete("/delete",
  6449. [&](const Request & /*req*/, Response &res) {
  6450. res.set_content("DELETE", "text/plain");
  6451. })
  6452. .Delete("/delete-body",
  6453. [&](const Request &req, Response &res) {
  6454. EXPECT_EQ(req.body, "content");
  6455. res.set_content(req.body, "text/plain");
  6456. })
  6457. .Options(R"(\*)",
  6458. [&](const Request & /*req*/, Response &res) {
  6459. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6460. })
  6461. .CustomRoute("PROPFIND", "/dav/:id",
  6462. [&](const Request &req, Response &res) {
  6463. res.set_header("x-body-size",
  6464. std::to_string(req.body.size()));
  6465. res.set_header("x-matched-route", req.matched_route);
  6466. res.set_header("x-dav-id", req.path_params.at("id"));
  6467. res.status = StatusCode::MultiStatus_207;
  6468. res.set_content(req.body, "application/xml");
  6469. })
  6470. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6471. [&](const Request &req, Response &res) {
  6472. res.set_header("x-dav-match", req.matches[1]);
  6473. res.status = StatusCode::MultiStatus_207;
  6474. })
  6475. .CustomRoute("MKCOL", "/dav-mkcol",
  6476. [&](const Request &req, Response &res) {
  6477. EXPECT_TRUE(req.body.empty());
  6478. res.status = StatusCode::Created_201;
  6479. })
  6480. .CustomRoute(
  6481. "REPORT", "/dav-report",
  6482. [&](const Request & /*req*/, Response &res,
  6483. const ContentReader &content_reader) {
  6484. std::string body;
  6485. content_reader([&](const char *data, size_t data_length) {
  6486. body.append(data, data_length);
  6487. return true;
  6488. });
  6489. res.set_header("x-body-size", std::to_string(body.size()));
  6490. res.status = StatusCode::MultiStatus_207;
  6491. res.set_content(body, "application/xml");
  6492. })
  6493. .Get("/request-target",
  6494. [&](const Request &req, Response & /*res*/) {
  6495. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6496. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6497. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6498. })
  6499. .Get("/long-query-value",
  6500. [&](const Request &req, Response & /*res*/) {
  6501. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6502. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6503. })
  6504. .Get("/too-long-query-value",
  6505. [&](const Request &req, Response & /*res*/) {
  6506. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6507. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6508. })
  6509. .Get("/array-param",
  6510. [&](const Request &req, Response & /*res*/) {
  6511. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6512. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6513. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6514. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6515. })
  6516. .Get("/array-param-values",
  6517. [&](const Request &req, Response & /*res*/) {
  6518. auto values = req.get_param_values("array");
  6519. EXPECT_EQ(3u, values.size());
  6520. EXPECT_EQ("value1", values[0]);
  6521. EXPECT_EQ("value2", values[1]);
  6522. EXPECT_EQ("value3", values[2]);
  6523. auto empty = req.get_param_values("nonexistent");
  6524. EXPECT_TRUE(empty.empty());
  6525. })
  6526. .Post("/validate-no-multiple-headers",
  6527. [&](const Request &req, Response & /*res*/) {
  6528. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6529. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6530. })
  6531. .Post("/content_receiver",
  6532. [&](const Request &req, Response &res,
  6533. const ContentReader &content_reader) {
  6534. if (req.is_multipart_form_data()) {
  6535. std::vector<FormData> items;
  6536. content_reader(
  6537. [&](const FormData &file) {
  6538. items.push_back(file);
  6539. return true;
  6540. },
  6541. [&](const char *data, size_t data_length) {
  6542. items.back().content.append(data, data_length);
  6543. return true;
  6544. });
  6545. EXPECT_EQ(5u, items.size());
  6546. {
  6547. const auto &file = get_file_value(items, "text1");
  6548. EXPECT_TRUE(file.filename.empty());
  6549. EXPECT_EQ("text default", file.content);
  6550. }
  6551. {
  6552. const auto &file = get_file_value(items, "text2");
  6553. EXPECT_TRUE(file.filename.empty());
  6554. EXPECT_EQ("aωb", file.content);
  6555. }
  6556. {
  6557. const auto &file = get_file_value(items, "file1");
  6558. EXPECT_EQ("hello.txt", file.filename);
  6559. EXPECT_EQ("text/plain", file.content_type);
  6560. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6561. }
  6562. {
  6563. const auto &file = get_file_value(items, "file2");
  6564. EXPECT_EQ("world.json", file.filename);
  6565. EXPECT_EQ("application/json", file.content_type);
  6566. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6567. }
  6568. {
  6569. const auto &file = get_file_value(items, "file3");
  6570. EXPECT_TRUE(file.filename.empty());
  6571. EXPECT_EQ("application/octet-stream", file.content_type);
  6572. EXPECT_EQ(0u, file.content.size());
  6573. }
  6574. } else {
  6575. std::string body;
  6576. content_reader([&](const char *data, size_t data_length) {
  6577. EXPECT_EQ(7U, data_length);
  6578. body.append(data, data_length);
  6579. return true;
  6580. });
  6581. EXPECT_EQ(body, "content");
  6582. res.set_content(body, "text/plain");
  6583. }
  6584. })
  6585. .Put("/content_receiver",
  6586. [&](const Request & /*req*/, Response &res,
  6587. const ContentReader &content_reader) {
  6588. std::string body;
  6589. content_reader([&](const char *data, size_t data_length) {
  6590. body.append(data, data_length);
  6591. return true;
  6592. });
  6593. EXPECT_EQ(body, "content");
  6594. res.set_content(body, "text/plain");
  6595. })
  6596. .Patch("/content_receiver",
  6597. [&](const Request & /*req*/, Response &res,
  6598. const ContentReader &content_reader) {
  6599. std::string body;
  6600. content_reader([&](const char *data, size_t data_length) {
  6601. body.append(data, data_length);
  6602. return true;
  6603. });
  6604. EXPECT_EQ(body, "content");
  6605. res.set_content(body, "text/plain");
  6606. })
  6607. .Post("/query-string-and-body",
  6608. [&](const Request &req, Response & /*res*/) {
  6609. ASSERT_TRUE(req.has_param("key"));
  6610. EXPECT_EQ(req.get_param_value("key"), "value");
  6611. EXPECT_EQ(req.body, "content");
  6612. })
  6613. .Get("/last-request",
  6614. [&](const Request &req, Response & /*res*/) {
  6615. EXPECT_EQ("close", req.get_header_value("Connection"));
  6616. })
  6617. .Get(R"(/redirect/(\d+))",
  6618. [&](const Request &req, Response &res) {
  6619. auto num = std::stoi(req.matches[1]) + 1;
  6620. std::string url = "/redirect/" + std::to_string(num);
  6621. res.set_redirect(url);
  6622. })
  6623. .Post("/binary",
  6624. [&](const Request &req, Response &res) {
  6625. EXPECT_EQ(4U, req.body.size());
  6626. EXPECT_EQ("application/octet-stream",
  6627. req.get_header_value("Content-Type"));
  6628. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6629. res.set_content(req.body, "application/octet-stream");
  6630. })
  6631. .Put("/binary",
  6632. [&](const Request &req, Response &res) {
  6633. EXPECT_EQ(4U, req.body.size());
  6634. EXPECT_EQ("application/octet-stream",
  6635. req.get_header_value("Content-Type"));
  6636. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6637. res.set_content(req.body, "application/octet-stream");
  6638. })
  6639. .Patch("/binary",
  6640. [&](const Request &req, Response &res) {
  6641. EXPECT_EQ(4U, req.body.size());
  6642. EXPECT_EQ("application/octet-stream",
  6643. req.get_header_value("Content-Type"));
  6644. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6645. res.set_content(req.body, "application/octet-stream");
  6646. })
  6647. .Delete("/binary",
  6648. [&](const Request &req, Response &res) {
  6649. EXPECT_EQ(4U, req.body.size());
  6650. EXPECT_EQ("application/octet-stream",
  6651. req.get_header_value("Content-Type"));
  6652. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6653. res.set_content(req.body, "application/octet-stream");
  6654. })
  6655. .Get("/issue1772",
  6656. [&](const Request & /*req*/, Response &res) {
  6657. res.status = 401;
  6658. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6659. })
  6660. .Delete("/issue609",
  6661. [](const httplib::Request &, httplib::Response &res,
  6662. const httplib::ContentReader &) {
  6663. res.set_content("ok", "text/plain");
  6664. })
  6665. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6666. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6667. .Get("/compress",
  6668. [&](const Request & /*req*/, Response &res) {
  6669. res.set_content(
  6670. "12345678901234567890123456789012345678901234567890123456789"
  6671. "01234567890123456789012345678901234567890",
  6672. "text/plain");
  6673. })
  6674. .Get("/compress-with-charset",
  6675. [&](const Request & /*req*/, Response &res) {
  6676. res.set_content(
  6677. "12345678901234567890123456789012345678901234567890123456789"
  6678. "01234567890123456789012345678901234567890",
  6679. "application/json; charset=utf-8");
  6680. })
  6681. .Get("/nocompress",
  6682. [&](const Request & /*req*/, Response &res) {
  6683. res.set_content(
  6684. "12345678901234567890123456789012345678901234567890123456789"
  6685. "01234567890123456789012345678901234567890",
  6686. "application/octet-stream");
  6687. })
  6688. .Post("/compress-multipart",
  6689. [&](const Request &req, Response & /*res*/) {
  6690. EXPECT_EQ(2u, req.form.fields.size());
  6691. ASSERT_TRUE(!req.form.has_field("???"));
  6692. {
  6693. const auto &text = req.form.get_field("key1");
  6694. EXPECT_EQ("test", text);
  6695. }
  6696. {
  6697. const auto &text = req.form.get_field("key2");
  6698. EXPECT_EQ("--abcdefg123", text);
  6699. }
  6700. })
  6701. #endif
  6702. ;
  6703. persons_["john"] = "programmer";
  6704. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6705. svr_.wait_until_ready();
  6706. }
  6707. virtual void TearDown() {
  6708. svr_.stop();
  6709. if (!request_threads_.empty()) {
  6710. std::this_thread::sleep_for(std::chrono::seconds(1));
  6711. for (auto &t : request_threads_) {
  6712. t.join();
  6713. }
  6714. }
  6715. t_.join();
  6716. }
  6717. map<string, string> persons_;
  6718. #ifdef CPPHTTPLIB_SSL_ENABLED
  6719. SSLClient cli_;
  6720. SSLServer svr_;
  6721. #else
  6722. Client cli_;
  6723. Server svr_;
  6724. #endif
  6725. thread t_;
  6726. std::vector<thread> request_threads_;
  6727. };
  6728. TEST_F(ServerTest, GetMethod200) {
  6729. auto res = cli_.Get("/hi");
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ("HTTP/1.1", res->version);
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ("OK", res->reason);
  6734. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6735. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6736. EXPECT_EQ("Hello World!", res->body);
  6737. }
  6738. TEST_F(ServerTest, GetEmptyFile) {
  6739. auto res = cli_.Get("/empty_file");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6743. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6744. EXPECT_EQ("", res->body);
  6745. }
  6746. TEST_F(ServerTest, GetFileContent) {
  6747. auto res = cli_.Get("/file_content");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6751. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6752. EXPECT_EQ("test.html", res->body);
  6753. }
  6754. TEST_F(ServerTest, GetFileContentWithRange) {
  6755. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6758. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6759. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6760. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6761. EXPECT_EQ("est", res->body);
  6762. }
  6763. TEST_F(ServerTest, GetFileContentWithContentType) {
  6764. auto res = cli_.Get("/file_content_with_content_type");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6769. EXPECT_EQ("file\n", res->body);
  6770. }
  6771. TEST_F(ServerTest, GetInvalidFileContent) {
  6772. auto res = cli_.Get("/invalid_file_content");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6775. }
  6776. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6777. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6779. EXPECT_EQ("HTTP/1.1", res->version);
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6782. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6783. EXPECT_EQ("Hello World!", res->body);
  6784. }
  6785. TEST_F(ServerTest, GetMethod302) {
  6786. auto res = cli_.Get("/");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. EXPECT_EQ(StatusCode::Found_302, res->status);
  6789. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6790. }
  6791. TEST_F(ServerTest, GetMethod302Redirect) {
  6792. cli_.set_follow_location(true);
  6793. auto res = cli_.Get("/");
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. EXPECT_EQ("Hello World!", res->body);
  6797. EXPECT_EQ("/hi", res->location);
  6798. }
  6799. TEST_F(ServerTest, GetMethod404) {
  6800. auto res = cli_.Get("/invalid");
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6803. }
  6804. TEST_F(ServerTest, HeadMethod200) {
  6805. auto res = cli_.Head("/hi");
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6809. EXPECT_TRUE(res->body.empty());
  6810. }
  6811. TEST_F(ServerTest, HeadMethod200Static) {
  6812. auto res = cli_.Head("/mount/dir/index.html");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6816. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6817. EXPECT_TRUE(res->body.empty());
  6818. }
  6819. TEST_F(ServerTest, HeadMethod404) {
  6820. auto res = cli_.Head("/invalid");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6823. EXPECT_TRUE(res->body.empty());
  6824. }
  6825. TEST_F(ServerTest, GetMethodPersonJohn) {
  6826. auto res = cli_.Get("/person/john");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6830. EXPECT_EQ("programmer", res->body);
  6831. }
  6832. TEST_F(ServerTest, PostMethod1) {
  6833. auto res = cli_.Get("/person/john1");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6836. res = cli_.Post("/person", "name=john1&note=coder",
  6837. "application/x-www-form-urlencoded");
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. ASSERT_EQ(StatusCode::OK_200, res->status);
  6840. res = cli_.Get("/person/john1");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. ASSERT_EQ(StatusCode::OK_200, res->status);
  6843. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6844. ASSERT_EQ("coder", res->body);
  6845. }
  6846. TEST_F(ServerTest, PostMethod2) {
  6847. auto res = cli_.Get("/person/john2");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6850. Params params;
  6851. params.emplace("name", "john2");
  6852. params.emplace("note", "coder");
  6853. res = cli_.Post("/person", params);
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. ASSERT_EQ(StatusCode::OK_200, res->status);
  6856. res = cli_.Get("/person/john2");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. ASSERT_EQ(StatusCode::OK_200, res->status);
  6859. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6860. ASSERT_EQ("coder", res->body);
  6861. }
  6862. TEST_F(ServerTest, PutMethod3) {
  6863. auto res = cli_.Get("/person/john3");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6866. Params params;
  6867. params.emplace("name", "john3");
  6868. params.emplace("note", "coder");
  6869. res = cli_.Put("/person", params);
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. ASSERT_EQ(StatusCode::OK_200, res->status);
  6872. res = cli_.Get("/person/john3");
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. ASSERT_EQ(StatusCode::OK_200, res->status);
  6875. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6876. ASSERT_EQ("coder", res->body);
  6877. }
  6878. TEST_F(ServerTest, DeleteMethod1) {
  6879. auto res = cli_.Get("/person/john4");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6882. Params params;
  6883. params.emplace("name", "john4");
  6884. params.emplace("note", "coder");
  6885. res = cli_.Post("/person", params);
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. ASSERT_EQ(StatusCode::OK_200, res->status);
  6888. res = cli_.Get("/person/john4");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. ASSERT_EQ(StatusCode::OK_200, res->status);
  6891. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6892. ASSERT_EQ("coder", res->body);
  6893. Params delete_params;
  6894. delete_params.emplace("name", "john4");
  6895. res = cli_.Delete("/person", delete_params);
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. ASSERT_EQ(StatusCode::OK_200, res->status);
  6898. ASSERT_EQ("DELETED", res->body);
  6899. res = cli_.Get("/person/john4");
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6902. }
  6903. TEST_F(ServerTest, DeleteMethod2) {
  6904. auto res = cli_.Get("/person/john5");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6907. Params params;
  6908. params.emplace("name", "john5");
  6909. params.emplace("note", "developer");
  6910. res = cli_.Post("/person", params);
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. res = cli_.Get("/person/john5");
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. ASSERT_EQ(StatusCode::OK_200, res->status);
  6916. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6917. ASSERT_EQ("developer", res->body);
  6918. Params delete_params;
  6919. delete_params.emplace("name", "john5");
  6920. Headers headers;
  6921. headers.emplace("Custom-Header", "test-value");
  6922. res = cli_.Delete("/person", headers, delete_params);
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. ASSERT_EQ(StatusCode::OK_200, res->status);
  6925. ASSERT_EQ("DELETED", res->body);
  6926. res = cli_.Get("/person/john5");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6929. }
  6930. TEST_F(ServerTest, DeleteMethod3) {
  6931. auto res = cli_.Get("/person/john6");
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6934. Params params;
  6935. params.emplace("name", "john6");
  6936. params.emplace("note", "tester");
  6937. res = cli_.Post("/person", params);
  6938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6939. ASSERT_EQ(StatusCode::OK_200, res->status);
  6940. res = cli_.Get("/person/john6");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. ASSERT_EQ(StatusCode::OK_200, res->status);
  6943. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6944. ASSERT_EQ("tester", res->body);
  6945. Params delete_params;
  6946. delete_params.emplace("name", "john6");
  6947. Headers headers;
  6948. headers.emplace("Custom-Header", "test-value");
  6949. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. ASSERT_EQ(StatusCode::OK_200, res->status);
  6952. ASSERT_EQ("DELETED", res->body);
  6953. res = cli_.Get("/person/john6");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6956. }
  6957. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6958. Params params;
  6959. params.emplace("json", JSON_DATA);
  6960. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. ASSERT_EQ(StatusCode::OK_200, res->status);
  6963. ASSERT_EQ(JSON_DATA, res->body);
  6964. }
  6965. TEST_F(ServerTest, PostEmptyContent) {
  6966. auto res = cli_.Post("/empty", "", "text/plain");
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. ASSERT_EQ(StatusCode::OK_200, res->status);
  6969. ASSERT_EQ("empty", res->body);
  6970. }
  6971. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6972. auto res = cli_.Post("/empty-no-content-type");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. ASSERT_EQ(StatusCode::OK_200, res->status);
  6975. ASSERT_EQ("empty-no-content-type", res->body);
  6976. }
  6977. TEST_F(ServerTest, PostPathOnly) {
  6978. auto res = cli_.Post("/path-only");
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. ASSERT_EQ(StatusCode::OK_200, res->status);
  6981. ASSERT_EQ("path-only", res->body);
  6982. }
  6983. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6984. auto res = cli_.Post("/path-headers-only",
  6985. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. ASSERT_EQ(StatusCode::OK_200, res->status);
  6988. ASSERT_EQ("path-headers-only", res->body);
  6989. }
  6990. TEST_F(ServerTest, PostLarge) {
  6991. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. ASSERT_EQ(StatusCode::OK_200, res->status);
  6994. EXPECT_EQ(LARGE_DATA, res->body);
  6995. }
  6996. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6997. auto res = cli_.Put("/empty-no-content-type");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. ASSERT_EQ(StatusCode::OK_200, res->status);
  7000. ASSERT_EQ("empty-no-content-type", res->body);
  7001. }
  7002. TEST_F(ServerTest, GetMethodDir) {
  7003. auto res = cli_.Get("/dir/");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7007. auto body = R"(<html>
  7008. <head>
  7009. </head>
  7010. <body>
  7011. <a href="/dir/test.html">Test</a>
  7012. <a href="/hi">hi</a>
  7013. </body>
  7014. </html>
  7015. )";
  7016. EXPECT_EQ(body, res->body);
  7017. }
  7018. TEST_F(ServerTest, GetMethodDirTest) {
  7019. auto res = cli_.Get("/dir/test.html");
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. EXPECT_EQ(StatusCode::OK_200, res->status);
  7022. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7023. EXPECT_EQ("test.html", res->body);
  7024. }
  7025. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7026. auto res = cli_.Get("/dir/../dir/test.html");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7029. }
  7030. TEST_F(ServerTest, GetMethodInvalidPath) {
  7031. auto res = cli_.Get("/dir/../test.html");
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7034. }
  7035. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7036. auto res = cli_.Get("/../www/dir/test.html");
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7039. }
  7040. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7041. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7044. }
  7045. TEST_F(ServerTest, GetMethodDirMountTest) {
  7046. auto res = cli_.Get("/mount/dir/test.html");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7050. EXPECT_EQ("test.html", res->body);
  7051. }
  7052. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7053. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7056. }
  7057. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7058. auto res = cli_.Get("/mount/dir/../test.html");
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7061. }
  7062. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7063. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7066. }
  7067. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7068. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7070. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7071. }
  7072. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7073. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7076. }
  7077. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7078. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7081. }
  7082. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7083. auto res = cli_.Get("/mount/dir");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7086. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7087. }
  7088. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7089. auto res = cli_.Get("//dir");
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7092. EXPECT_FALSE(res->has_header("Location"));
  7093. }
  7094. TEST_F(ServerTest, PostMethod303) {
  7095. auto res = cli_.Post("/1", "body", "text/plain");
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7098. EXPECT_EQ("/2", res->get_header_value("Location"));
  7099. }
  7100. TEST_F(ServerTest, PostMethod303Redirect) {
  7101. cli_.set_follow_location(true);
  7102. auto res = cli_.Post("/1", "body", "text/plain");
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::OK_200, res->status);
  7105. EXPECT_EQ("redirected.", res->body);
  7106. EXPECT_EQ("/2", res->location);
  7107. }
  7108. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7109. auto res = cli_.Get("/dir/test.abcde");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::OK_200, res->status);
  7112. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7113. EXPECT_EQ("abcde", res->body);
  7114. }
  7115. TEST_F(ServerTest, StaticFileRange) {
  7116. auto res =
  7117. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7120. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7121. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7122. EXPECT_EQ(true, res->has_header("Content-Range"));
  7123. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7124. EXPECT_EQ(std::string("cd"), res->body);
  7125. }
  7126. TEST_F(ServerTest, StaticFileRanges) {
  7127. auto res = cli_.Get("/dir/test.abcde",
  7128. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7131. EXPECT_TRUE(
  7132. res->get_header_value("Content-Type")
  7133. .find(
  7134. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7135. 0);
  7136. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7137. }
  7138. TEST_F(ServerTest, StaticFileRangeHead) {
  7139. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7142. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7143. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7144. EXPECT_EQ(true, res->has_header("Content-Range"));
  7145. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7146. }
  7147. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7148. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7152. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7153. EXPECT_EQ(true, res->has_header("Content-Range"));
  7154. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7155. res->get_header_value("Content-Range"));
  7156. EXPECT_EQ("LAST\n", res->body);
  7157. }
  7158. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7159. auto res =
  7160. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7164. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7165. EXPECT_EQ(true, res->has_header("Content-Range"));
  7166. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7167. }
  7168. TEST_F(ServerTest, StaticFileBigFile) {
  7169. auto res = cli_.Get("/dir/1MB.txt");
  7170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7173. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7174. }
  7175. TEST_F(ServerTest, InvalidBaseDirMount) {
  7176. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7177. }
  7178. TEST_F(ServerTest, Binary) {
  7179. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7180. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7181. "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_.Put("/binary", binary.data(), binary.size(),
  7186. "application/octet-stream");
  7187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7188. ASSERT_EQ(StatusCode::OK_200, res->status);
  7189. ASSERT_EQ(4U, res->body.size());
  7190. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7191. "application/octet-stream");
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. ASSERT_EQ(StatusCode::OK_200, res->status);
  7194. ASSERT_EQ(4U, res->body.size());
  7195. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7196. "application/octet-stream");
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. ASSERT_EQ(StatusCode::OK_200, res->status);
  7199. ASSERT_EQ(4U, res->body.size());
  7200. }
  7201. TEST_F(ServerTest, BinaryString) {
  7202. auto binary = std::string("\x00\x01\x02\x03", 4);
  7203. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. ASSERT_EQ(StatusCode::OK_200, res->status);
  7206. ASSERT_EQ(4U, res->body.size());
  7207. res = cli_.Put("/binary", binary, "application/octet-stream");
  7208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7209. ASSERT_EQ(StatusCode::OK_200, res->status);
  7210. ASSERT_EQ(4U, res->body.size());
  7211. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. ASSERT_EQ(StatusCode::OK_200, res->status);
  7214. ASSERT_EQ(4U, res->body.size());
  7215. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. ASSERT_EQ(StatusCode::OK_200, res->status);
  7218. ASSERT_EQ(4U, res->body.size());
  7219. }
  7220. TEST_F(ServerTest, EmptyRequest) {
  7221. auto res = cli_.Get("");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::Connection, res.error());
  7224. }
  7225. TEST_F(ServerTest, LongRequest) {
  7226. std::string request;
  7227. for (size_t i = 0; i < 545; i++) {
  7228. request += "/TooLongRequest";
  7229. }
  7230. request += "OK";
  7231. auto res = cli_.Get(request.c_str());
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7234. }
  7235. TEST_F(ServerTest, TooLongRequest) {
  7236. std::string request;
  7237. for (size_t i = 0; i < 546; i++) {
  7238. request += "/TooLongRequest";
  7239. }
  7240. request += "_NG";
  7241. auto start = std::chrono::high_resolution_clock::now();
  7242. cli_.set_keep_alive(true);
  7243. auto res = cli_.Get(request.c_str());
  7244. auto end = std::chrono::high_resolution_clock::now();
  7245. auto elapsed =
  7246. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7247. .count();
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7250. EXPECT_LE(elapsed, 1000);
  7251. EXPECT_EQ("close", res->get_header_value("Connection"));
  7252. EXPECT_FALSE(cli_.is_socket_open());
  7253. }
  7254. TEST_F(ServerTest, AlmostTooLongRequest) {
  7255. // test for #2046 - URI length check shouldn't include other content on req
  7256. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7257. // leading /, space, HTTP/1.1)
  7258. std::string request =
  7259. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7260. auto res = cli_.Get(request.c_str());
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7263. }
  7264. TEST_F(ServerTest, LongHeader) {
  7265. Request req;
  7266. req.method = "GET";
  7267. req.path = "/hi";
  7268. std::string host_and_port;
  7269. host_and_port += HOST;
  7270. host_and_port += ":";
  7271. host_and_port += std::to_string(PORT);
  7272. req.headers.emplace("Host", host_and_port.c_str());
  7273. req.headers.emplace("Accept", "*/*");
  7274. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7275. req.headers.emplace(
  7276. "Header-Name",
  7277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7305. "@@@@@@@@@@@@@@@@");
  7306. auto res = std::make_shared<Response>();
  7307. auto error = Error::Success;
  7308. auto ret = cli_.send(req, *res, error);
  7309. ASSERT_TRUE(ret);
  7310. EXPECT_EQ(StatusCode::OK_200, res->status);
  7311. }
  7312. TEST_F(ServerTest, LongQueryValue) {
  7313. auto start = std::chrono::high_resolution_clock::now();
  7314. cli_.set_keep_alive(true);
  7315. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7316. auto end = std::chrono::high_resolution_clock::now();
  7317. auto elapsed =
  7318. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7319. .count();
  7320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7321. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7322. EXPECT_LE(elapsed, 1000);
  7323. EXPECT_EQ("close", res->get_header_value("Connection"));
  7324. EXPECT_FALSE(cli_.is_socket_open());
  7325. }
  7326. TEST_F(ServerTest, TooLongQueryValue) {
  7327. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7328. ASSERT_FALSE(res);
  7329. EXPECT_EQ(Error::Read, res.error());
  7330. }
  7331. TEST_F(ServerTest, TooLongHeader) {
  7332. Request req;
  7333. req.method = "GET";
  7334. req.path = "/hi";
  7335. std::string host_and_port;
  7336. host_and_port += HOST;
  7337. host_and_port += ":";
  7338. host_and_port += std::to_string(PORT);
  7339. req.headers.emplace("Host", host_and_port.c_str());
  7340. req.headers.emplace("Accept", "*/*");
  7341. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7342. req.headers.emplace(
  7343. "Header-Name",
  7344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7372. "@@@@@@@@@@@@@@@@@");
  7373. auto res = std::make_shared<Response>();
  7374. auto error = Error::Success;
  7375. auto ret = cli_.send(req, *res, error);
  7376. ASSERT_TRUE(ret);
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. }
  7379. TEST_F(ServerTest, HeaderCountAtLimit) {
  7380. // Test with headers just under the 100 limit
  7381. httplib::Headers headers;
  7382. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7383. // This should keep us just under the 100 header limit
  7384. for (int i = 0; i < 95; i++) {
  7385. std::string name = "X-Test-Header-" + std::to_string(i);
  7386. std::string value = "value" + std::to_string(i);
  7387. headers.emplace(name, value);
  7388. }
  7389. // This should work fine as we're under the limit
  7390. auto res = cli_.Get("/hi", headers);
  7391. EXPECT_TRUE(res);
  7392. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7393. }
  7394. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7395. // Test with many headers to exceed the 100 limit
  7396. httplib::Headers headers;
  7397. // Add 150 headers to definitely exceed the 100 limit
  7398. for (int i = 0; i < 150; i++) {
  7399. std::string name = "X-Test-Header-" + std::to_string(i);
  7400. std::string value = "value" + std::to_string(i);
  7401. headers.emplace(name, value);
  7402. }
  7403. // This should fail due to exceeding header count limit
  7404. cli_.set_keep_alive(true);
  7405. auto res = cli_.Get("/hi", headers);
  7406. // The server should respond with 400 Bad Request
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7409. EXPECT_EQ("close", res->get_header_value("Connection"));
  7410. EXPECT_FALSE(cli_.is_socket_open());
  7411. }
  7412. TEST_F(ServerTest, PercentEncoding) {
  7413. auto res = cli_.Get("/e%6edwith%");
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::OK_200, res->status);
  7416. }
  7417. TEST_F(ServerTest, PercentEncodingUnicode) {
  7418. auto res = cli_.Get("/e%u006edwith%");
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. }
  7422. TEST_F(ServerTest, InvalidPercentEncoding) {
  7423. auto res = cli_.Get("/%endwith%");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7426. }
  7427. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7428. auto res = cli_.Get("/%uendwith%");
  7429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7431. }
  7432. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7433. auto res = cli_.Get("/hello?aaa=bbb%");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7436. }
  7437. TEST_F(ServerTest, PlusSignEncoding) {
  7438. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("a +b", res->body);
  7442. }
  7443. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7444. // This test simulates a potential DoS attack using many headers
  7445. // to verify our security fix prevents memory exhaustion
  7446. httplib::Headers attack_headers;
  7447. // Attempt to add many headers like an attacker would (200 headers to far
  7448. // exceed limit)
  7449. for (int i = 0; i < 200; i++) {
  7450. std::string name = "X-Attack-Header-" + std::to_string(i);
  7451. std::string value = "attack_payload_" + std::to_string(i);
  7452. attack_headers.emplace(name, value);
  7453. }
  7454. // Try to POST with excessive headers
  7455. cli_.set_keep_alive(true);
  7456. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7457. // Should either fail or return 400 Bad Request due to security limit
  7458. if (res) {
  7459. // If we get a response, it should be 400 Bad Request
  7460. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7461. EXPECT_EQ("close", res->get_header_value("Connection"));
  7462. }
  7463. EXPECT_FALSE(cli_.is_socket_open());
  7464. }
  7465. TEST_F(ServerTest, MultipartFormData) {
  7466. UploadFormDataItems items = {
  7467. {"text1", "text default", "", ""},
  7468. {"text2", "aωb", "", ""},
  7469. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7470. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7471. {"file3", "", "", "application/octet-stream"},
  7472. {"file4", "", "", " application/json tmp-string "}};
  7473. auto res = cli_.Post("/multipart", items);
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::OK_200, res->status);
  7476. }
  7477. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7478. UploadFormDataItems items = {
  7479. {"text", "default text", "", ""},
  7480. {"multi_text1", "aaaaa", "", ""},
  7481. {"multi_text1", "bbbbb", "", ""},
  7482. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7483. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7484. "application/json"},
  7485. };
  7486. auto res = cli_.Post("/multipart/multi_file_values", items);
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7491. auto res = cli_.Get("/hi");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7495. EXPECT_EQ("Hello World!", res->body);
  7496. }
  7497. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7498. Request req;
  7499. req.method = "POST";
  7500. req.path = "/chunked";
  7501. std::string host_and_port;
  7502. host_and_port += HOST;
  7503. host_and_port += ":";
  7504. host_and_port += std::to_string(PORT);
  7505. req.headers.emplace("Host", host_and_port.c_str());
  7506. req.headers.emplace("Accept", "*/*");
  7507. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7508. req.headers.emplace("Content-Type", "text/plain");
  7509. req.headers.emplace("Content-Length", "0");
  7510. req.headers.emplace(
  7511. "Transfer-Encoding",
  7512. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7513. // Client does not chunk, so make a chunked body manually.
  7514. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7515. auto res = std::make_shared<Response>();
  7516. auto error = Error::Success;
  7517. auto ret = cli_.send(req, *res, error);
  7518. ASSERT_TRUE(ret);
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. }
  7521. template <typename ClientT>
  7522. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7523. int expected_status) {
  7524. Request req;
  7525. req.method = "POST";
  7526. req.path = "/chunked";
  7527. std::string host_and_port;
  7528. host_and_port += HOST;
  7529. host_and_port += ":";
  7530. host_and_port += std::to_string(PORT);
  7531. req.headers.emplace("Host", host_and_port.c_str());
  7532. req.headers.emplace("Content-Length", "0");
  7533. req.headers.emplace("Transfer-Encoding", "chunked");
  7534. req.body = body;
  7535. auto res = std::make_shared<Response>();
  7536. auto error = Error::Success;
  7537. ASSERT_TRUE(cli.send(req, *res, error));
  7538. EXPECT_EQ(expected_status, res->status);
  7539. }
  7540. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7541. // rather than treat them as valid lengths.
  7542. template <typename ClientT>
  7543. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7544. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7545. }
  7546. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7547. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7548. }
  7549. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7550. expect_chunked_body_rejected(
  7551. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7552. }
  7553. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7554. // chunk-size line carries no CR, LF or other control character ahead of its
  7555. // terminator. Such a line must be refused rather than read as extension text.
  7556. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7557. expect_chunked_body_rejected(
  7558. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7559. }
  7560. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7561. expect_chunked_body_rejected(
  7562. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7563. }
  7564. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7565. expect_chunked_body_rejected(
  7566. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7567. }
  7568. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7569. // The literal stays split: a hex escape consumes every hex digit that
  7570. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7571. expect_chunked_body_rejected(
  7572. cli_, "4;a\x01"
  7573. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7574. }
  7575. // The bytes around chunk data are no payload, so they cannot ride on the
  7576. // payload limit
  7577. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7578. // Small enough that the whole request is sent before the server turns it
  7579. // down, yet past the limit by the last chunks
  7580. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7581. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7582. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7583. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7584. SCOPED_TRACE(size_line.substr(0, 2));
  7585. std::string body;
  7586. for (auto c : std::string("dechunked post body")) {
  7587. body += size_line + "\r\n" + c + "\r\n";
  7588. }
  7589. body += "0\r\n\r\n";
  7590. expect_chunked_body_rejected(cli_, body.c_str());
  7591. }
  7592. }
  7593. TEST_F(ServerTest, AcceptsChunkExtension) {
  7594. expect_chunked_body_status(cli_,
  7595. "4;name=value\r\ndech\r\n"
  7596. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7597. "0;last\r\n\r\n",
  7598. StatusCode::OK_200);
  7599. }
  7600. TEST_F(ServerTest, GetStreamed2) {
  7601. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7604. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7605. EXPECT_EQ(true, res->has_header("Content-Range"));
  7606. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7607. EXPECT_EQ(std::string("ab"), res->body);
  7608. }
  7609. TEST_F(ServerTest, GetStreamed) {
  7610. auto res = cli_.Get("/streamed");
  7611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7612. EXPECT_EQ(StatusCode::OK_200, res->status);
  7613. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7614. EXPECT_EQ(std::string("aaabbb"), res->body);
  7615. }
  7616. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7617. auto res = cli_.Get("/streamed-without-length",
  7618. Headers{make_range_header({{0, -1}})});
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(StatusCode::OK_200, res->status);
  7621. EXPECT_EQ(false, res->has_header("Content-Length"));
  7622. EXPECT_EQ(false, res->has_header("Content-Range"));
  7623. EXPECT_EQ(std::string("abcdefg"), res->body);
  7624. }
  7625. TEST_F(ServerTest, GetStreamedWithRange1) {
  7626. auto res =
  7627. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7630. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7631. EXPECT_EQ(true, res->has_header("Content-Range"));
  7632. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7633. EXPECT_EQ(std::string("def"), res->body);
  7634. }
  7635. TEST_F(ServerTest, GetStreamedWithRange2) {
  7636. auto res =
  7637. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7640. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ(true, res->has_header("Content-Range"));
  7642. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7643. EXPECT_EQ(std::string("bcdefg"), res->body);
  7644. }
  7645. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7646. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7648. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7649. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7650. EXPECT_EQ(true, res->has_header("Content-Range"));
  7651. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7652. EXPECT_EQ(std::string("efg"), res->body);
  7653. }
  7654. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7655. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7656. // the entire representation.
  7657. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7658. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7660. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7661. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7662. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7663. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7664. }
  7665. }
  7666. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7667. auto res =
  7668. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7671. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7672. EXPECT_EQ(false, res->has_header("Content-Range"));
  7673. EXPECT_EQ(0U, res->body.size());
  7674. }
  7675. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7676. // Only a 206 is served as a partial representation. Under any other status
  7677. // `apply_ranges()` reported the full content length, so the body must match
  7678. // that header, and the content provider must never be asked for an offset
  7679. // outside the representation.
  7680. auto check = [&](int status, const char *range) {
  7681. auto path =
  7682. std::string("/streamed-with-range?status=") + std::to_string(status);
  7683. auto ctx = path + " Range: " + range;
  7684. auto res = cli_.Get(path, Headers{{"Range", range}});
  7685. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7686. EXPECT_EQ(status, res->status) << ctx;
  7687. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7689. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7690. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7691. };
  7692. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7693. check(403, "bytes=3-5");
  7694. // The offset is far past the representation.
  7695. check(403, "bytes=100000-100200");
  7696. // `first_pos` is still -1 here, and the bounds asserts in
  7697. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7698. check(403, "bytes=-3");
  7699. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7700. // multipart branch would have written one that is empty.
  7701. check(403, "bytes=1-2, 4-5");
  7702. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7703. // covers the whole representation.
  7704. check(200, "bytes=3-5");
  7705. check(200, "bytes=1-2, 4-5");
  7706. }
  7707. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7708. auto res =
  7709. cli_.Get("/streamed-with-range",
  7710. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7711. "92233720368547758079223372036854775807"}});
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7714. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7715. EXPECT_EQ(false, res->has_header("Content-Range"));
  7716. EXPECT_EQ(0U, res->body.size());
  7717. }
  7718. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7719. auto res = cli_.Get(
  7720. "/with-range",
  7721. Headers{{"Range",
  7722. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7723. {"Accept-Encoding", ""}});
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7726. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7727. EXPECT_EQ(true, res->has_header("Content-Range"));
  7728. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7729. EXPECT_EQ(std::string("abcdefg"), res->body);
  7730. }
  7731. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7732. auto res = cli_.Get("/with-range", Headers{
  7733. {"Range", "bytes=0-"},
  7734. {"Accept-Encoding", ""},
  7735. });
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7738. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7739. EXPECT_EQ(true, res->has_header("Content-Range"));
  7740. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7741. EXPECT_EQ(std::string("abcdefg"), res->body);
  7742. }
  7743. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7744. auto res = cli_.Get("/streamed-with-range",
  7745. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7748. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7749. EXPECT_EQ(false, res->has_header("Content-Range"));
  7750. EXPECT_EQ(267U, res->body.size());
  7751. // Check that both range contents are present
  7752. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7753. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7754. // Check that Content-Range headers are present for both ranges
  7755. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7756. std::string::npos);
  7757. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7758. std::string::npos);
  7759. }
  7760. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7761. Ranges ranges;
  7762. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7763. ranges.emplace_back(0, -1);
  7764. }
  7765. auto res = cli_.Get("/streamed-with-range?error",
  7766. Headers{{make_range_header(ranges)}});
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7769. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7770. EXPECT_EQ(false, res->has_header("Content-Range"));
  7771. EXPECT_EQ(0U, res->body.size());
  7772. }
  7773. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7774. auto res = cli_.Get("/streamed-with-range",
  7775. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7778. EXPECT_EQ(5U, res->body.size());
  7779. // Check that overlapping ranges are coalesced into a single range
  7780. EXPECT_EQ("bcdef", res->body);
  7781. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7782. // Should be single range, not multipart
  7783. EXPECT_TRUE(res->has_header("Content-Range"));
  7784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7785. }
  7786. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7787. auto res = cli_.Get("/streamed-with-range",
  7788. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7791. EXPECT_EQ(268U, res->body.size());
  7792. // Check that both range contents are present
  7793. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7794. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7795. // Check that Content-Range headers are present for both ranges
  7796. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7797. std::string::npos);
  7798. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7799. std::string::npos);
  7800. }
  7801. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7802. auto res = cli_.Get("/streamed-with-range",
  7803. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7806. EXPECT_EQ(269U, res->body.size());
  7807. // Check that both duplicate range contents are present
  7808. size_t first_abc = res->body.find("abc\r\n");
  7809. EXPECT_TRUE(first_abc != std::string::npos);
  7810. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7811. EXPECT_TRUE(second_abc != std::string::npos);
  7812. // Check that Content-Range headers are present for both ranges
  7813. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7814. EXPECT_TRUE(first_range != std::string::npos);
  7815. size_t second_range =
  7816. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7817. EXPECT_TRUE(second_range != std::string::npos);
  7818. }
  7819. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7820. auto res =
  7821. cli_.Get("/streamed-with-range?error",
  7822. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7825. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7826. EXPECT_EQ(false, res->has_header("Content-Range"));
  7827. EXPECT_EQ(0U, res->body.size());
  7828. }
  7829. TEST_F(ServerTest, GetStreamedEndless) {
  7830. uint64_t offset = 0;
  7831. auto res = cli_.Get("/streamed-cancel",
  7832. [&](const char * /*data*/, uint64_t data_length) {
  7833. if (offset < 100) {
  7834. offset += data_length;
  7835. return true;
  7836. }
  7837. return false;
  7838. });
  7839. ASSERT_TRUE(!res);
  7840. EXPECT_EQ(Error::Canceled, res.error());
  7841. }
  7842. TEST_F(ServerTest, ClientStop) {
  7843. std::atomic_size_t count{4};
  7844. std::vector<std::thread> threads;
  7845. for (auto i = count.load(); i != 0; --i) {
  7846. threads.emplace_back([&]() {
  7847. auto res = cli_.Get("/streamed-cancel",
  7848. [&](const char *, uint64_t) { return true; });
  7849. --count;
  7850. ASSERT_TRUE(!res);
  7851. EXPECT_TRUE(res.error() == Error::Canceled ||
  7852. res.error() == Error::Read || res.error() == Error::Write);
  7853. });
  7854. }
  7855. std::this_thread::sleep_for(std::chrono::seconds(2));
  7856. while (count != 0) {
  7857. cli_.stop();
  7858. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7859. }
  7860. for (auto &t : threads) {
  7861. t.join();
  7862. }
  7863. }
  7864. TEST_F(ServerTest, GetWithRange1) {
  7865. auto res = cli_.Get("/with-range", Headers{
  7866. make_range_header({{3, 5}}),
  7867. {"Accept-Encoding", ""},
  7868. });
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7871. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7872. EXPECT_EQ(true, res->has_header("Content-Range"));
  7873. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7874. EXPECT_EQ(std::string("def"), res->body);
  7875. }
  7876. TEST_F(ServerTest, GetWithRange2) {
  7877. auto res = cli_.Get("/with-range", Headers{
  7878. make_range_header({{1, -1}}),
  7879. {"Accept-Encoding", ""},
  7880. });
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7883. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7884. EXPECT_EQ(true, res->has_header("Content-Range"));
  7885. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7886. EXPECT_EQ(std::string("bcdefg"), res->body);
  7887. }
  7888. TEST_F(ServerTest, GetWithRange3) {
  7889. auto res = cli_.Get("/with-range", Headers{
  7890. make_range_header({{0, 0}}),
  7891. {"Accept-Encoding", ""},
  7892. });
  7893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7895. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7896. EXPECT_EQ(true, res->has_header("Content-Range"));
  7897. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7898. EXPECT_EQ(std::string("a"), res->body);
  7899. }
  7900. TEST_F(ServerTest, GetWithRange4) {
  7901. auto res = cli_.Get("/with-range", Headers{
  7902. make_range_header({{-1, 2}}),
  7903. {"Accept-Encoding", ""},
  7904. });
  7905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7906. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7907. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7908. EXPECT_EQ(true, res->has_header("Content-Range"));
  7909. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7910. EXPECT_EQ(std::string("fg"), res->body);
  7911. }
  7912. TEST_F(ServerTest, GetWithRange5) {
  7913. auto res = cli_.Get("/with-range", Headers{
  7914. make_range_header({{0, 5}}),
  7915. {"Accept-Encoding", ""},
  7916. });
  7917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7919. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7920. EXPECT_EQ(true, res->has_header("Content-Range"));
  7921. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7922. EXPECT_EQ(std::string("abcdef"), res->body);
  7923. }
  7924. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7925. auto res =
  7926. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7929. }
  7930. TEST_F(ServerTest, GetWithRangeMultipart) {
  7931. auto res =
  7932. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7935. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7936. EXPECT_EQ(false, res->has_header("Content-Range"));
  7937. EXPECT_EQ(267U, res->body.size());
  7938. }
  7939. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7940. auto res = cli_.Get("/with-range",
  7941. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7944. }
  7945. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7946. auto res = cli_.Get("/with-range-customized-response",
  7947. Headers{{make_range_header({{1, 2}})}});
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7950. EXPECT_EQ(true, res->has_header("Content-Length"));
  7951. EXPECT_EQ(false, res->has_header("Content-Range"));
  7952. EXPECT_EQ(JSON_DATA, res->body);
  7953. }
  7954. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7955. auto res = cli_.Get("/with-range-customized-response",
  7956. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7959. EXPECT_EQ(true, res->has_header("Content-Length"));
  7960. EXPECT_EQ(false, res->has_header("Content-Range"));
  7961. EXPECT_EQ(JSON_DATA, res->body);
  7962. }
  7963. TEST_F(ServerTest, Issue1772) {
  7964. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7966. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7967. }
  7968. TEST_F(ServerTest, Issue609) {
  7969. auto res = cli_.Delete("/issue609");
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(StatusCode::OK_200, res->status);
  7972. EXPECT_EQ(std::string("ok"), res->body);
  7973. }
  7974. TEST_F(ServerTest, GetStreamedChunked) {
  7975. auto res = cli_.Get("/streamed-chunked");
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. EXPECT_EQ(std::string("123456789"), res->body);
  7979. }
  7980. TEST_F(ServerTest, GetStreamedChunked2) {
  7981. auto res = cli_.Get("/streamed-chunked2");
  7982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. EXPECT_EQ(std::string("123456789"), res->body);
  7985. }
  7986. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7987. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. EXPECT_EQ(std::string("123456789"), res->body);
  7991. EXPECT_TRUE(res->has_header("Trailer"));
  7992. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7993. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7994. // Trailers are now stored separately from headers (security fix)
  7995. EXPECT_EQ(2U, res->trailers.size());
  7996. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7997. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7998. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7999. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8000. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8001. // Verify trailers are NOT in headers (security verification)
  8002. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8003. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8004. }
  8005. TEST_F(ServerTest, LargeChunkedPost) {
  8006. Request req;
  8007. req.method = "POST";
  8008. req.path = "/large-chunked";
  8009. std::string host_and_port;
  8010. host_and_port += HOST;
  8011. host_and_port += ":";
  8012. host_and_port += std::to_string(PORT);
  8013. req.headers.emplace("Host", host_and_port.c_str());
  8014. req.headers.emplace("Accept", "*/*");
  8015. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8016. req.headers.emplace("Content-Type", "text/plain");
  8017. req.headers.emplace("Content-Length", "0");
  8018. req.headers.emplace("Transfer-Encoding", "chunked");
  8019. std::string long_string(30 * 1024u, 'a');
  8020. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8021. // Attempt to make a large enough post to exceed OS buffers, to test that
  8022. // the server handles short reads if the full chunk data isn't available.
  8023. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8024. auto res = std::make_shared<Response>();
  8025. auto error = Error::Success;
  8026. auto ret = cli_.send(req, *res, error);
  8027. ASSERT_TRUE(ret);
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. }
  8030. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8031. auto res = cli_.Get("/remote_addr");
  8032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8033. EXPECT_EQ(StatusCode::OK_200, res->status);
  8034. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8035. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8036. }
  8037. TEST_F(ServerTest, GetMethodLocalAddr) {
  8038. auto res = cli_.Get("/local_addr");
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8042. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8043. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8044. }
  8045. TEST_F(ServerTest, HTTPResponseSplitting) {
  8046. auto res = cli_.Get("/http_response_splitting");
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. }
  8050. TEST_F(ServerTest, SlowRequest) {
  8051. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8052. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8053. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8054. }
  8055. #if 0
  8056. TEST_F(ServerTest, SlowPost) {
  8057. char buffer[64 * 1024];
  8058. memset(buffer, 0x42, sizeof(buffer));
  8059. auto res = cli_.Post(
  8060. "/slowpost", 64 * 1024 * 1024,
  8061. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8062. auto ret = sink.write(buffer, sizeof(buffer));
  8063. EXPECT_TRUE(ret);
  8064. return true;
  8065. },
  8066. "text/plain");
  8067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8068. EXPECT_EQ(StatusCode::OK_200, res->status);
  8069. }
  8070. TEST_F(ServerTest, SlowPostFail) {
  8071. char buffer[64 * 1024];
  8072. memset(buffer, 0x42, sizeof(buffer));
  8073. cli_.set_write_timeout(std::chrono::seconds(0));
  8074. auto res = cli_.Post(
  8075. "/slowpost", 64 * 1024 * 1024,
  8076. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8077. sink.write(buffer, sizeof(buffer));
  8078. return true;
  8079. },
  8080. "text/plain");
  8081. ASSERT_TRUE(!res);
  8082. EXPECT_EQ(Error::Write, res.error());
  8083. }
  8084. #endif
  8085. TEST_F(ServerTest, Put) {
  8086. auto res = cli_.Put("/put", "PUT", "text/plain");
  8087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8088. EXPECT_EQ(StatusCode::OK_200, res->status);
  8089. EXPECT_EQ("PUT", res->body);
  8090. }
  8091. TEST_F(ServerTest, PutWithContentProvider) {
  8092. auto res = cli_.Put(
  8093. "/put", 3,
  8094. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8095. sink.os << "PUT";
  8096. return true;
  8097. },
  8098. "text/plain");
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ(StatusCode::OK_200, res->status);
  8101. EXPECT_EQ("PUT", res->body);
  8102. }
  8103. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8104. auto res = cli_.Post(
  8105. "/post", 42,
  8106. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8107. return false;
  8108. },
  8109. "text/plain");
  8110. ASSERT_TRUE(!res);
  8111. EXPECT_EQ(Error::Canceled, res.error());
  8112. }
  8113. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8114. auto res = cli_.Put(
  8115. "/put",
  8116. [](size_t /*offset*/, DataSink &sink) {
  8117. sink.os << "PUT";
  8118. sink.done();
  8119. return true;
  8120. },
  8121. "text/plain");
  8122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8123. EXPECT_EQ(StatusCode::OK_200, res->status);
  8124. EXPECT_EQ("PUT", res->body);
  8125. }
  8126. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8127. auto res = cli_.Post(
  8128. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8129. "text/plain");
  8130. ASSERT_TRUE(!res);
  8131. EXPECT_EQ(Error::Canceled, res.error());
  8132. }
  8133. TEST_F(ServerTest, PostLoopBack) {
  8134. std::string body;
  8135. auto res = cli_.Post(
  8136. "/post-loopback", 9,
  8137. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8138. EXPECT_EQ(9u, length);
  8139. sink.write("123", 3);
  8140. sink.write("456", 3);
  8141. sink.write("789", 3);
  8142. return true;
  8143. },
  8144. "text/plain",
  8145. [&body](const char *data, size_t data_length) {
  8146. body.append(data, data_length);
  8147. return true;
  8148. });
  8149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. EXPECT_EQ("123456789", body);
  8152. }
  8153. TEST_F(ServerTest, PutLoopBack) {
  8154. std::string body;
  8155. auto res = cli_.Put(
  8156. "/put-loopback", 9,
  8157. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8158. EXPECT_EQ(9u, length);
  8159. sink.write("123", 3);
  8160. sink.write("456", 3);
  8161. sink.write("789", 3);
  8162. return true;
  8163. },
  8164. "text/plain",
  8165. [&body](const char *data, size_t data_length) {
  8166. body.append(data, data_length);
  8167. return true;
  8168. });
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("123456789", body);
  8172. }
  8173. TEST_F(ServerTest, PatchLoopBack) {
  8174. std::string body;
  8175. auto res = cli_.Patch(
  8176. "/patch-loopback", 9,
  8177. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8178. EXPECT_EQ(9u, length);
  8179. sink.write("123", 3);
  8180. sink.write("456", 3);
  8181. sink.write("789", 3);
  8182. return true;
  8183. },
  8184. "text/plain",
  8185. [&body](const char *data, size_t data_length) {
  8186. body.append(data, data_length);
  8187. return true;
  8188. });
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("123456789", body);
  8192. }
  8193. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8194. std::string body;
  8195. auto res = cli_.Post(
  8196. "/post-loopback",
  8197. [](size_t /*offset*/, DataSink &sink) {
  8198. sink.write("123", 3);
  8199. sink.write("456", 3);
  8200. sink.write("789", 3);
  8201. sink.done();
  8202. return true;
  8203. },
  8204. "text/plain",
  8205. [&body](const char *data, size_t data_length) {
  8206. body.append(data, data_length);
  8207. return true;
  8208. });
  8209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8210. EXPECT_EQ(StatusCode::OK_200, res->status);
  8211. EXPECT_EQ("123456789", body);
  8212. }
  8213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8214. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8215. cli_.set_compress(true);
  8216. auto res = cli_.Put(
  8217. "/put", 3,
  8218. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8219. sink.os << "PUT";
  8220. return true;
  8221. },
  8222. "text/plain");
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("PUT", res->body);
  8226. }
  8227. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8228. cli_.set_compress(true);
  8229. auto res = cli_.Post(
  8230. "/post", 42,
  8231. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8232. return false;
  8233. },
  8234. "text/plain");
  8235. ASSERT_TRUE(!res);
  8236. EXPECT_EQ(Error::Canceled, res.error());
  8237. }
  8238. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8239. cli_.set_compress(true);
  8240. auto res = cli_.Put(
  8241. "/put",
  8242. [](size_t /*offset*/, DataSink &sink) {
  8243. sink.os << "PUT";
  8244. sink.done();
  8245. return true;
  8246. },
  8247. "text/plain");
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ("PUT", res->body);
  8251. }
  8252. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8253. cli_.set_compress(true);
  8254. auto res = cli_.Post(
  8255. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8256. "text/plain");
  8257. ASSERT_TRUE(!res);
  8258. EXPECT_EQ(Error::Canceled, res.error());
  8259. }
  8260. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8261. cli_.set_compress(true);
  8262. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8264. EXPECT_EQ(StatusCode::OK_200, res->status);
  8265. EXPECT_EQ(LARGE_DATA, res->body);
  8266. }
  8267. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8268. #ifdef CPPHTTPLIB_SSL_ENABLED
  8269. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8270. Client cli(s.c_str());
  8271. cli.enable_server_certificate_verification(false);
  8272. #else
  8273. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8274. Client cli(s.c_str());
  8275. #endif
  8276. cli.set_compress(true);
  8277. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::OK_200, res->status);
  8280. EXPECT_EQ(LARGE_DATA, res->body);
  8281. // The compressed size should be less than a 10th of the original. May vary
  8282. // depending on the zlib library.
  8283. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8284. static_cast<uint64_t>(10 * 1024 * 1024));
  8285. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8286. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8287. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8288. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8289. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8290. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8291. #endif
  8292. }
  8293. TEST_F(ServerTest, PutContentWithDeflate) {
  8294. cli_.set_compress(false);
  8295. Headers headers;
  8296. headers.emplace("Content-Encoding", "deflate");
  8297. // PUT in deflate format:
  8298. auto res = cli_.Put("/put", headers,
  8299. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. EXPECT_EQ("PUT", res->body);
  8303. }
  8304. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8305. Headers headers;
  8306. headers.emplace("Accept-Encoding", "gzip, deflate");
  8307. auto res = cli_.Get("/streamed-chunked", headers);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::OK_200, res->status);
  8310. EXPECT_EQ(std::string("123456789"), res->body);
  8311. }
  8312. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8313. Headers headers;
  8314. headers.emplace("Accept-Encoding", "gzip, deflate");
  8315. auto res = cli_.Get("/streamed-chunked2", headers);
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_EQ(std::string("123456789"), res->body);
  8319. }
  8320. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8321. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8323. EXPECT_EQ(StatusCode::OK_200, res->status);
  8324. }
  8325. TEST(GzipDecompressor, ChunkedDecompression) {
  8326. std::string data;
  8327. for (size_t i = 0; i < 32 * 1024; ++i) {
  8328. data.push_back(static_cast<char>('a' + i % 26));
  8329. }
  8330. std::string compressed_data;
  8331. {
  8332. httplib::detail::gzip_compressor compressor;
  8333. bool result = compressor.compress(
  8334. data.data(), data.size(),
  8335. /*last=*/true,
  8336. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8337. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8338. compressed_data_size);
  8339. return true;
  8340. });
  8341. ASSERT_TRUE(result);
  8342. }
  8343. std::string decompressed_data;
  8344. {
  8345. httplib::detail::gzip_decompressor decompressor;
  8346. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8347. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8348. size_t chunk_size = 130;
  8349. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8350. chunk_begin += chunk_size) {
  8351. size_t current_chunk_size =
  8352. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8353. bool result = decompressor.decompress(
  8354. compressed_data.data() + chunk_begin, current_chunk_size,
  8355. [&](const char *decompressed_data_chunk,
  8356. size_t decompressed_data_chunk_size) {
  8357. decompressed_data.insert(decompressed_data.size(),
  8358. decompressed_data_chunk,
  8359. decompressed_data_chunk_size);
  8360. return true;
  8361. });
  8362. ASSERT_TRUE(result);
  8363. }
  8364. }
  8365. ASSERT_EQ(data, decompressed_data);
  8366. }
  8367. TEST(GzipDecompressor, DeflateDecompression) {
  8368. std::string original_text = "Raw deflate without gzip";
  8369. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8370. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8371. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8372. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8373. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8374. std::string decompressed_data;
  8375. {
  8376. httplib::detail::gzip_decompressor decompressor;
  8377. bool result = decompressor.decompress(
  8378. compressed_data.data(), compressed_data.size(),
  8379. [&](const char *decompressed_data_chunk,
  8380. size_t decompressed_data_chunk_size) {
  8381. decompressed_data.insert(decompressed_data.size(),
  8382. decompressed_data_chunk,
  8383. decompressed_data_chunk_size);
  8384. return true;
  8385. });
  8386. ASSERT_TRUE(result);
  8387. }
  8388. ASSERT_EQ(original_text, decompressed_data);
  8389. }
  8390. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8391. std::string original_text = "Raw deflate without gzip";
  8392. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8393. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8394. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8395. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8396. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8397. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8398. std::string decompressed_data;
  8399. {
  8400. httplib::detail::gzip_decompressor decompressor;
  8401. bool result = decompressor.decompress(
  8402. compressed_data.data(), compressed_data.size(),
  8403. [&](const char *decompressed_data_chunk,
  8404. size_t decompressed_data_chunk_size) {
  8405. decompressed_data.insert(decompressed_data.size(),
  8406. decompressed_data_chunk,
  8407. decompressed_data_chunk_size);
  8408. return true;
  8409. });
  8410. ASSERT_TRUE(result);
  8411. }
  8412. ASSERT_EQ(original_text, decompressed_data);
  8413. }
  8414. #endif
  8415. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8416. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "br");
  8419. auto res = cli_.Get("/streamed-chunked", headers);
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. EXPECT_EQ(std::string("123456789"), res->body);
  8423. }
  8424. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "br");
  8427. auto res = cli_.Get("/streamed-chunked2", headers);
  8428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8429. EXPECT_EQ(StatusCode::OK_200, res->status);
  8430. EXPECT_EQ(std::string("123456789"), res->body);
  8431. }
  8432. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8433. cli_.set_compress(true);
  8434. auto res = cli_.Put(
  8435. "/put", 3,
  8436. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8437. sink.os << "PUT";
  8438. return true;
  8439. },
  8440. "text/plain");
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. EXPECT_EQ("PUT", res->body);
  8444. }
  8445. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8446. cli_.set_compress(true);
  8447. auto res = cli_.Put(
  8448. "/put",
  8449. [](size_t /*offset*/, DataSink &sink) {
  8450. sink.os << "PUT";
  8451. sink.done();
  8452. return true;
  8453. },
  8454. "text/plain");
  8455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8456. EXPECT_EQ(StatusCode::OK_200, res->status);
  8457. EXPECT_EQ("PUT", res->body);
  8458. }
  8459. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8460. cli_.set_compress(true);
  8461. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::OK_200, res->status);
  8464. EXPECT_EQ(LARGE_DATA, res->body);
  8465. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8466. }
  8467. #endif
  8468. TEST_F(ServerTest, Patch) {
  8469. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_EQ(StatusCode::OK_200, res->status);
  8472. EXPECT_EQ("PATCH", res->body);
  8473. }
  8474. TEST_F(ServerTest, Delete) {
  8475. auto res = cli_.Delete("/delete");
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. EXPECT_EQ("DELETE", res->body);
  8479. }
  8480. TEST_F(ServerTest, DeleteContentReceiver) {
  8481. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8483. EXPECT_EQ(StatusCode::OK_200, res->status);
  8484. EXPECT_EQ("content", res->body);
  8485. }
  8486. TEST_F(ServerTest, Options) {
  8487. auto res = cli_.Options("*");
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ(StatusCode::OK_200, res->status);
  8490. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8491. EXPECT_TRUE(res->body.empty());
  8492. }
  8493. TEST_F(ServerTest, URL) {
  8494. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8496. EXPECT_EQ(StatusCode::OK_200, res->status);
  8497. }
  8498. TEST_F(ServerTest, ArrayParam) {
  8499. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8501. EXPECT_EQ(StatusCode::OK_200, res->status);
  8502. }
  8503. TEST_F(ServerTest, ArrayParamValues) {
  8504. auto res =
  8505. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::OK_200, res->status);
  8508. }
  8509. TEST_F(ServerTest, NoMultipleHeaders) {
  8510. Headers headers = {{"Content-Length", "5"}};
  8511. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8512. "text/plain");
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(ServerTest, PostContentReceiver) {
  8517. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. ASSERT_EQ(StatusCode::OK_200, res->status);
  8520. ASSERT_EQ("content", res->body);
  8521. }
  8522. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8523. UploadFormDataItems items = {
  8524. {"text1", "text default", "", ""},
  8525. {"text2", "aωb", "", ""},
  8526. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8527. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8528. {"file3", "", "", "application/octet-stream"},
  8529. };
  8530. auto res = cli_.Post("/content_receiver", items);
  8531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8532. EXPECT_EQ(StatusCode::OK_200, res->status);
  8533. }
  8534. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8535. UploadFormDataItems items = {
  8536. {"text1", "text default", "", ""},
  8537. {"text2", "aωb", "", ""},
  8538. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8539. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8540. {"file3", "", "", "application/octet-stream"},
  8541. };
  8542. auto boundary = std::string("+++++");
  8543. std::string body;
  8544. for (const auto &item : items) {
  8545. body += "--" + boundary + "\r\n";
  8546. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8547. if (!item.filename.empty()) {
  8548. body += "; filename=\"" + item.filename + "\"";
  8549. }
  8550. body += "\r\n";
  8551. if (!item.content_type.empty()) {
  8552. body += "Content-Type: " + item.content_type + "\r\n";
  8553. }
  8554. body += "\r\n";
  8555. body += item.content + "\r\n";
  8556. }
  8557. body += "--" + boundary + "--\r\n";
  8558. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8559. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8561. EXPECT_EQ(StatusCode::OK_200, res->status);
  8562. }
  8563. TEST(MultipartFormDataTest, FieldEscaping) {
  8564. Server svr;
  8565. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8566. const ContentReader &content_reader) {
  8567. ASSERT_TRUE(req.is_multipart_form_data());
  8568. std::vector<FormData> received;
  8569. content_reader(
  8570. [&](const FormData &file) {
  8571. received.push_back(file);
  8572. return true;
  8573. },
  8574. [&](const char *data, size_t data_length) {
  8575. received.back().content.append(data, data_length);
  8576. return true;
  8577. });
  8578. // '"', CR and LF in names and filenames are escaped following the
  8579. // WHATWG HTML standard, so each part still parses as a single part
  8580. // with no injected headers. Content types get CR/LF escaped too,
  8581. // while '"' (legal there, e.g. quoted charset) is preserved.
  8582. ASSERT_EQ(4U, received.size());
  8583. EXPECT_EQ("na%22me", received[0].name);
  8584. EXPECT_EQ("quoted name", received[0].content);
  8585. EXPECT_EQ("file", received[1].name);
  8586. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8587. received[1].filename);
  8588. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8589. EXPECT_EQ("injected", received[1].content);
  8590. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8591. EXPECT_EQ("my%22file.txt", received[2].filename);
  8592. EXPECT_EQ("cr lf name", received[2].content);
  8593. EXPECT_EQ("typed", received[3].name);
  8594. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8595. received[3].content_type);
  8596. EXPECT_EQ("typed content", received[3].content);
  8597. });
  8598. auto port = svr.bind_to_any_port("localhost");
  8599. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8600. auto se = detail::scope_exit([&] {
  8601. svr.stop();
  8602. t.join();
  8603. ASSERT_FALSE(svr.is_running());
  8604. });
  8605. svr.wait_until_ready();
  8606. Client cli("localhost", port);
  8607. UploadFormDataItems items = {
  8608. {"na\"me", "quoted name", "", ""},
  8609. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8610. "application/octet-stream"},
  8611. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8612. {"typed", "typed content", "",
  8613. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8614. };
  8615. auto res = cli.Post("/post", items);
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::OK_200, res->status);
  8618. }
  8619. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8620. const UploadFormDataItems items = {
  8621. {"name1", "Content 1", "", ""},
  8622. {"name2", "Content 2", "file2.txt", "text/plain"},
  8623. };
  8624. Server svr;
  8625. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8626. const ContentReader &content_reader) {
  8627. ASSERT_TRUE(req.is_multipart_form_data());
  8628. std::vector<FormData> received;
  8629. content_reader(
  8630. [&](const FormData &file) {
  8631. received.push_back(file);
  8632. return true;
  8633. },
  8634. [&](const char *data, size_t data_length) {
  8635. received.back().content.append(data, data_length);
  8636. return true;
  8637. });
  8638. ASSERT_EQ(2U, received.size());
  8639. EXPECT_EQ("name1", received[0].name);
  8640. EXPECT_EQ("Content 1", received[0].content);
  8641. EXPECT_EQ("name2", received[1].name);
  8642. EXPECT_EQ("Content 2", received[1].content);
  8643. EXPECT_EQ("file2.txt", received[1].filename);
  8644. EXPECT_EQ("text/plain", received[1].content_type);
  8645. });
  8646. auto port = svr.bind_to_any_port("localhost");
  8647. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8648. auto se = detail::scope_exit([&] {
  8649. svr.stop();
  8650. t.join();
  8651. ASSERT_FALSE(svr.is_running());
  8652. });
  8653. svr.wait_until_ready();
  8654. Client cli("localhost", port);
  8655. // Whole-body serialization with a generated boundary
  8656. {
  8657. MultipartFormDataWriter writer;
  8658. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8659. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8660. writer.content_type());
  8661. auto body = writer.serialize(items);
  8662. EXPECT_EQ(body.size(), writer.content_length(items));
  8663. auto res = cli.Post("/post", body, writer.content_type());
  8664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8665. EXPECT_EQ(StatusCode::OK_200, res->status);
  8666. }
  8667. // Per-part framing with a custom boundary via a content provider
  8668. {
  8669. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8670. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8671. MultipartFormDataWriter writer("custom-boundary_123");
  8672. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8673. std::string body;
  8674. for (const auto &item : items) {
  8675. body += writer.item_begin(item);
  8676. body += item.content;
  8677. body += MultipartFormDataWriter::item_end();
  8678. }
  8679. body += writer.finish();
  8680. EXPECT_EQ(body.size(), writer.content_length(items));
  8681. auto res = cli.Post(
  8682. "/post", body.size(),
  8683. [&](size_t offset, size_t length, DataSink &sink) {
  8684. sink.write(body.data() + offset, length);
  8685. return true;
  8686. },
  8687. writer.content_type());
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. }
  8691. }
  8692. TEST_F(ServerTest, PostContentReceiverGzip) {
  8693. cli_.set_compress(true);
  8694. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8696. ASSERT_EQ(StatusCode::OK_200, res->status);
  8697. ASSERT_EQ("content", res->body);
  8698. }
  8699. TEST_F(ServerTest, PutContentReceiver) {
  8700. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8702. ASSERT_EQ(StatusCode::OK_200, res->status);
  8703. ASSERT_EQ("content", res->body);
  8704. }
  8705. TEST_F(ServerTest, PatchContentReceiver) {
  8706. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8708. ASSERT_EQ(StatusCode::OK_200, res->status);
  8709. ASSERT_EQ("content", res->body);
  8710. }
  8711. template <typename ClientType>
  8712. void TestWithHeadersAndContentReceiver(
  8713. ClientType &cli,
  8714. std::function<Result(ClientType &, const std::string &, const Headers &,
  8715. const std::string &, const std::string &,
  8716. ContentReceiver, DownloadProgress)>
  8717. request_func) {
  8718. Headers headers;
  8719. headers.emplace("X-Custom-Header", "test-value");
  8720. std::string received_body;
  8721. auto res = request_func(
  8722. cli, "/content_receiver", headers, "content", "application/json",
  8723. [&](const char *data, size_t data_length) {
  8724. received_body.append(data, data_length);
  8725. return true;
  8726. },
  8727. nullptr);
  8728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8729. EXPECT_EQ(StatusCode::OK_200, res->status);
  8730. EXPECT_EQ("content", received_body);
  8731. }
  8732. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8733. #ifdef CPPHTTPLIB_SSL_ENABLED
  8734. using ClientT = SSLClient;
  8735. #else
  8736. using ClientT = Client;
  8737. #endif
  8738. TestWithHeadersAndContentReceiver<ClientT>(
  8739. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8740. const std::string &body, const std::string &content_type,
  8741. ContentReceiver receiver, DownloadProgress progress) {
  8742. return cli.Post(path, headers, body, content_type, receiver, progress);
  8743. });
  8744. }
  8745. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8746. #ifdef CPPHTTPLIB_SSL_ENABLED
  8747. using ClientT = SSLClient;
  8748. #else
  8749. using ClientT = Client;
  8750. #endif
  8751. TestWithHeadersAndContentReceiver<ClientT>(
  8752. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8753. const std::string &body, const std::string &content_type,
  8754. ContentReceiver receiver, DownloadProgress progress) {
  8755. return cli.Put(path, headers, body, content_type, receiver, progress);
  8756. });
  8757. }
  8758. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8759. #ifdef CPPHTTPLIB_SSL_ENABLED
  8760. using ClientT = SSLClient;
  8761. #else
  8762. using ClientT = Client;
  8763. #endif
  8764. TestWithHeadersAndContentReceiver<ClientT>(
  8765. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8766. const std::string &body, const std::string &content_type,
  8767. ContentReceiver receiver, DownloadProgress progress) {
  8768. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8769. });
  8770. }
  8771. template <typename ClientType>
  8772. void TestWithHeadersAndContentReceiverWithProgress(
  8773. ClientType &cli,
  8774. std::function<Result(ClientType &, const std::string &, const Headers &,
  8775. const std::string &, const std::string &,
  8776. ContentReceiver, DownloadProgress)>
  8777. request_func) {
  8778. Headers headers;
  8779. headers.emplace("X-Test-Header", "progress-test");
  8780. std::string received_body;
  8781. auto progress_called = false;
  8782. auto res = request_func(
  8783. cli, "/content_receiver", headers, "content", "text/plain",
  8784. [&](const char *data, size_t data_length) {
  8785. received_body.append(data, data_length);
  8786. return true;
  8787. },
  8788. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8789. progress_called = true;
  8790. return true;
  8791. });
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. EXPECT_EQ("content", received_body);
  8795. EXPECT_TRUE(progress_called);
  8796. }
  8797. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8798. #ifdef CPPHTTPLIB_SSL_ENABLED
  8799. using ClientT = SSLClient;
  8800. #else
  8801. using ClientT = Client;
  8802. #endif
  8803. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8804. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8805. const std::string &body, const std::string &content_type,
  8806. ContentReceiver receiver, DownloadProgress progress) {
  8807. return cli.Post(path, headers, body, content_type, receiver, progress);
  8808. });
  8809. }
  8810. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8811. #ifdef CPPHTTPLIB_SSL_ENABLED
  8812. using ClientT = SSLClient;
  8813. #else
  8814. using ClientT = Client;
  8815. #endif
  8816. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8817. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8818. const std::string &body, const std::string &content_type,
  8819. ContentReceiver receiver, DownloadProgress progress) {
  8820. return cli.Put(path, headers, body, content_type, receiver, progress);
  8821. });
  8822. }
  8823. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8824. #ifdef CPPHTTPLIB_SSL_ENABLED
  8825. using ClientT = SSLClient;
  8826. #else
  8827. using ClientT = Client;
  8828. #endif
  8829. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8830. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8831. const std::string &body, const std::string &content_type,
  8832. ContentReceiver receiver, DownloadProgress progress) {
  8833. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8834. });
  8835. }
  8836. template <typename ClientType>
  8837. void TestWithHeadersAndContentReceiverError(
  8838. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8839. const Headers &, const std::string &,
  8840. const std::string &, ContentReceiver)>
  8841. request_func) {
  8842. Headers headers;
  8843. headers.emplace("X-Error-Test", "true");
  8844. std::string received_body;
  8845. auto receiver_failed = false;
  8846. auto res =
  8847. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8848. [&](const char *data, size_t data_length) {
  8849. received_body.append(data, data_length);
  8850. receiver_failed = true;
  8851. return false;
  8852. });
  8853. ASSERT_FALSE(res);
  8854. EXPECT_TRUE(receiver_failed);
  8855. }
  8856. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8857. #ifdef CPPHTTPLIB_SSL_ENABLED
  8858. using ClientT = SSLClient;
  8859. #else
  8860. using ClientT = Client;
  8861. #endif
  8862. TestWithHeadersAndContentReceiverError<ClientT>(
  8863. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8864. const std::string &body, const std::string &content_type,
  8865. ContentReceiver receiver) {
  8866. return cli.Post(path, headers, body, content_type, receiver);
  8867. });
  8868. }
  8869. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8870. #ifdef CPPHTTPLIB_SSL_ENABLED
  8871. using ClientT = SSLClient;
  8872. #else
  8873. using ClientT = Client;
  8874. #endif
  8875. TestWithHeadersAndContentReceiverError<ClientT>(
  8876. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8877. const std::string &body, const std::string &content_type,
  8878. ContentReceiver receiver) {
  8879. return cli.Put(path, headers, body, content_type, receiver);
  8880. });
  8881. }
  8882. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8883. #ifdef CPPHTTPLIB_SSL_ENABLED
  8884. using ClientT = SSLClient;
  8885. #else
  8886. using ClientT = Client;
  8887. #endif
  8888. TestWithHeadersAndContentReceiverError<ClientT>(
  8889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8890. const std::string &body, const std::string &content_type,
  8891. ContentReceiver receiver) {
  8892. return cli.Patch(path, headers, body, content_type, receiver);
  8893. });
  8894. }
  8895. TEST_F(ServerTest, PostQueryStringAndBody) {
  8896. auto res =
  8897. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. ASSERT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, HTTP2Magic) {
  8902. Request req;
  8903. req.method = "PRI";
  8904. req.path = "*";
  8905. req.body = "SM";
  8906. auto res = std::make_shared<Response>();
  8907. auto error = Error::Success;
  8908. auto ret = cli_.send(req, *res, error);
  8909. ASSERT_TRUE(ret);
  8910. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8911. }
  8912. TEST_F(ServerTest, KeepAlive) {
  8913. auto res = cli_.Get("/hi");
  8914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8917. EXPECT_EQ("Hello World!", res->body);
  8918. res = cli_.Get("/hi");
  8919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8920. EXPECT_EQ(StatusCode::OK_200, res->status);
  8921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8922. EXPECT_EQ("Hello World!", res->body);
  8923. res = cli_.Get("/hi");
  8924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8925. EXPECT_EQ(StatusCode::OK_200, res->status);
  8926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8927. EXPECT_EQ("Hello World!", res->body);
  8928. res = cli_.Get("/not-exist");
  8929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8931. res = cli_.Post("/empty", "", "text/plain");
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8935. EXPECT_EQ("empty", res->body);
  8936. EXPECT_EQ("close", res->get_header_value("Connection"));
  8937. res = cli_.Post(
  8938. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8939. "text/plain");
  8940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8941. EXPECT_EQ(StatusCode::OK_200, res->status);
  8942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8943. EXPECT_EQ("empty", res->body);
  8944. cli_.set_keep_alive(false);
  8945. res = cli_.Get("/last-request");
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::OK_200, res->status);
  8948. EXPECT_EQ("close", res->get_header_value("Connection"));
  8949. }
  8950. TEST_F(ServerTest, TooManyRedirect) {
  8951. cli_.set_follow_location(true);
  8952. auto res = cli_.Get("/redirect/0");
  8953. ASSERT_TRUE(!res);
  8954. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8955. }
  8956. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8957. Request req;
  8958. req.method = "FOOBAR";
  8959. req.path = "/hi";
  8960. cli_.set_keep_alive(true);
  8961. auto res = cli_.send(req);
  8962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8963. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8964. EXPECT_EQ("close", res->get_header_value("Connection"));
  8965. EXPECT_FALSE(cli_.is_socket_open());
  8966. }
  8967. TEST_F(ServerTest, CustomRouteReadsBody) {
  8968. const std::string xml =
  8969. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8970. Request req;
  8971. req.method = "PROPFIND";
  8972. req.path = "/dav/dir";
  8973. req.set_header("Depth", "1");
  8974. req.body = xml;
  8975. auto res = cli_.send(req);
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8978. EXPECT_EQ(xml, res->body);
  8979. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8980. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8981. }
  8982. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8983. Request req;
  8984. req.method = "PROPFIND";
  8985. req.path = "/dav/42";
  8986. auto res = cli_.send(req);
  8987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8988. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8989. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8990. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8991. }
  8992. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8993. Request req;
  8994. req.method = "PROPFIND";
  8995. req.path = "/dav-re/123";
  8996. auto res = cli_.send(req);
  8997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8998. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8999. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9000. }
  9001. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9002. Request req;
  9003. req.method = "MKCOL";
  9004. req.path = "/dav-mkcol";
  9005. auto res = cli_.send(req);
  9006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9007. EXPECT_EQ(StatusCode::Created_201, res->status);
  9008. }
  9009. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9010. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9011. Request req;
  9012. req.method = "REPORT";
  9013. req.path = "/dav-report";
  9014. req.body = xml;
  9015. auto res = cli_.send(req);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9018. EXPECT_EQ(xml, res->body);
  9019. }
  9020. // A content reader route must fire even when the request carries no body,
  9021. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9022. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9023. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9024. Request req;
  9025. req.method = "REPORT";
  9026. req.path = "/dav-report";
  9027. auto res = cli_.send(req);
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9030. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9031. }
  9032. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9033. Request req;
  9034. req.method = "PROPFIND";
  9035. req.path = "/not-dav";
  9036. auto res = cli_.send(req);
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9039. }
  9040. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9041. Request req;
  9042. req.method = "UNLOCK";
  9043. req.path = "/dav/dir";
  9044. cli_.set_keep_alive(true);
  9045. auto res = cli_.send(req);
  9046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9047. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9048. EXPECT_EQ("close", res->get_header_value("Connection"));
  9049. EXPECT_FALSE(cli_.is_socket_open());
  9050. }
  9051. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9052. // The mount point serves this path, but only for GET and HEAD.
  9053. auto get_res = cli_.Get("/dir/index.html");
  9054. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9055. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9056. Request req;
  9057. req.method = "PROPFIND";
  9058. req.path = "/dir/index.html";
  9059. auto res = cli_.send(req);
  9060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9061. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9062. }
  9063. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9064. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9065. cli_.set_keep_alive(true);
  9066. for (auto i = 0; i < 2; i++) {
  9067. Request req;
  9068. req.method = "PROPFIND";
  9069. req.path = "/dav/dir";
  9070. req.body = xml;
  9071. auto res = cli_.send(req);
  9072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9073. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9074. EXPECT_EQ(xml, res->body);
  9075. EXPECT_TRUE(cli_.is_socket_open());
  9076. }
  9077. // A built-in method must still be served on the same connection.
  9078. cli_.set_keep_alive(false);
  9079. auto res = cli_.Get("/hi");
  9080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9081. EXPECT_EQ(StatusCode::OK_200, res->status);
  9082. EXPECT_EQ("close", res->get_header_value("Connection"));
  9083. }
  9084. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9085. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9086. Request req;
  9087. req.method = "PROPFIND";
  9088. req.path = "/dav/dir";
  9089. req.set_header("Expect", "100-continue");
  9090. req.body = xml;
  9091. auto res = cli_.send(req);
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9094. EXPECT_EQ(xml, res->body);
  9095. }
  9096. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9097. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9098. TEST_F(ServerTest, Gzip) {
  9099. Headers headers;
  9100. headers.emplace("Accept-Encoding", "gzip, deflate");
  9101. auto res = cli_.Get("/compress", headers);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9105. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9107. "7890123456789012345678901234567890",
  9108. res->body);
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. }
  9111. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9112. Headers headers;
  9113. headers.emplace("Accept-Encoding", "gzip, deflate");
  9114. auto res = cli_.Get("/compress-with-charset", headers);
  9115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9116. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9117. EXPECT_EQ("application/json; charset=utf-8",
  9118. res->get_header_value("Content-Type"));
  9119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9120. "7890123456789012345678901234567890",
  9121. res->body);
  9122. EXPECT_EQ(StatusCode::OK_200, res->status);
  9123. }
  9124. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9125. Headers headers;
  9126. headers.emplace("Accept-Encoding", "");
  9127. auto res = cli_.Get("/compress", headers);
  9128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9129. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9130. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9133. "7890123456789012345678901234567890",
  9134. res->body);
  9135. EXPECT_EQ(StatusCode::OK_200, res->status);
  9136. }
  9137. TEST_F(ServerTest, GzipWithContentReceiver) {
  9138. Headers headers;
  9139. headers.emplace("Accept-Encoding", "gzip, deflate");
  9140. std::string body;
  9141. auto res =
  9142. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9143. EXPECT_EQ(100U, data_length);
  9144. body.append(data, data_length);
  9145. return true;
  9146. });
  9147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9148. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9150. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9152. "7890123456789012345678901234567890",
  9153. body);
  9154. EXPECT_EQ(StatusCode::OK_200, res->status);
  9155. }
  9156. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9157. Headers headers;
  9158. headers.emplace("Accept-Encoding", "gzip, deflate");
  9159. cli_.set_decompress(false);
  9160. auto res = cli_.Get("/compress", headers);
  9161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9162. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9163. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9164. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9165. EXPECT_EQ(33U, res->body.size());
  9166. EXPECT_EQ(StatusCode::OK_200, res->status);
  9167. }
  9168. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9169. Headers headers;
  9170. headers.emplace("Accept-Encoding", "");
  9171. std::string body;
  9172. auto res =
  9173. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9174. EXPECT_EQ(100U, data_length);
  9175. body.append(data, data_length);
  9176. return true;
  9177. });
  9178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9179. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9180. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9181. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9182. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9183. "7890123456789012345678901234567890",
  9184. body);
  9185. EXPECT_EQ(StatusCode::OK_200, res->status);
  9186. }
  9187. TEST_F(ServerTest, NoGzip) {
  9188. Headers headers;
  9189. headers.emplace("Accept-Encoding", "gzip, deflate");
  9190. auto res = cli_.Get("/nocompress", headers);
  9191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9192. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9193. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9194. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9196. "7890123456789012345678901234567890",
  9197. res->body);
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9201. Headers headers;
  9202. headers.emplace("Accept-Encoding", "gzip, deflate");
  9203. std::string body;
  9204. auto res = cli_.Get("/nocompress", headers,
  9205. [&](const char *data, size_t data_length) {
  9206. EXPECT_EQ(100U, data_length);
  9207. body.append(data, data_length);
  9208. return true;
  9209. });
  9210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9211. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9212. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9213. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9214. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9215. "7890123456789012345678901234567890",
  9216. body);
  9217. EXPECT_EQ(StatusCode::OK_200, res->status);
  9218. }
  9219. TEST_F(ServerTest, MultipartFormDataGzip) {
  9220. UploadFormDataItems items = {
  9221. {"key1", "test", "", ""},
  9222. {"key2", "--abcdefg123", "", ""},
  9223. };
  9224. cli_.set_compress(true);
  9225. auto res = cli_.Post("/compress-multipart", items);
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. EXPECT_EQ(StatusCode::OK_200, res->status);
  9228. }
  9229. #endif
  9230. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9231. // Static file compression is opt-in, so these run their own server rather than
  9232. // flipping it on for the shared ServerTest fixture, which would silently
  9233. // rewrite what every other static file test is asserting.
  9234. class StaticFileCompressionTest : public ::testing::Test {
  9235. protected:
  9236. void TearDown() override {
  9237. if (t_.joinable()) {
  9238. svr_.stop();
  9239. t_.join();
  9240. }
  9241. }
  9242. int start(const std::function<void(Server &)> &configure = nullptr) {
  9243. // Serves the same tree as a directory of build-time compressed assets
  9244. // would be served: the mount point names the coding the files are already
  9245. // stored in. Registered before "/" so it is the one that matches.
  9246. svr_.set_mount_point("/pre-encoded", "./www",
  9247. {{"Content-Encoding", "gzip"}});
  9248. svr_.set_mount_point("/", "./www");
  9249. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9250. res.set_file_content("./www/dir/index.html", "text/html");
  9251. });
  9252. svr_.Get("/pre-encoded-file-content",
  9253. [](const Request & /*req*/, Response &res) {
  9254. res.set_header("Content-Encoding", "gzip");
  9255. res.set_file_content("./www/dir/index.html", "text/html");
  9256. });
  9257. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9258. res.set_content_provider(
  9259. 6, "text/plain",
  9260. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9261. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9262. return true;
  9263. });
  9264. });
  9265. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9266. res.set_content_provider(
  9267. 1000, "text/plain",
  9268. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9269. if (offset < 100) {
  9270. std::string data(100, 'A');
  9271. sink.write(data.data(), data.size());
  9272. return true;
  9273. }
  9274. std::this_thread::sleep_for(std::chrono::seconds(2));
  9275. std::string data(900, 'B');
  9276. sink.write(data.data(), data.size());
  9277. return true;
  9278. });
  9279. });
  9280. if (configure) { configure(svr_); }
  9281. auto port = svr_.bind_to_any_port(HOST);
  9282. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9283. svr_.wait_until_ready();
  9284. return port;
  9285. }
  9286. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9287. // Every file under ./www except 1MB.txt is smaller than the default
  9288. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9289. // it out of the way.
  9290. static void enable_without_floor(Server &svr) {
  9291. svr.set_static_file_compression(true);
  9292. svr.set_static_file_compression_min_length(0);
  9293. }
  9294. Server svr_;
  9295. std::thread t_;
  9296. };
  9297. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9298. auto port = start();
  9299. Client cli(HOST, port);
  9300. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9302. EXPECT_EQ(StatusCode::OK_200, res->status);
  9303. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9304. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9305. EXPECT_EQ(1048576U, res->body.size());
  9306. }
  9307. TEST_F(StaticFileCompressionTest, MountPoint) {
  9308. auto port = start(enable);
  9309. Client cli(HOST, port);
  9310. cli.set_decompress(false);
  9311. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9313. EXPECT_EQ(StatusCode::OK_200, res->status);
  9314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9315. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9316. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9317. // The response stays self-delimiting: a length, not a chunked body.
  9318. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9319. EXPECT_EQ(std::to_string(res->body.size()),
  9320. res->get_header_value("Content-Length"));
  9321. EXPECT_LT(res->body.size(), 1048576U);
  9322. EXPECT_FALSE(res->body.empty());
  9323. }
  9324. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9325. auto port = start(enable);
  9326. Client cli(HOST, port);
  9327. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9331. EXPECT_EQ(1048576U, res->body.size());
  9332. }
  9333. TEST_F(StaticFileCompressionTest, FileContent) {
  9334. auto port = start(enable_without_floor);
  9335. Client cli(HOST, port);
  9336. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9338. EXPECT_EQ(StatusCode::OK_200, res->status);
  9339. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9341. EXPECT_EQ(104U, res->body.size());
  9342. }
  9343. // A handler that serves an already-encoded file names the coding itself. The
  9344. // file-backed path decided its coding from Accept-Encoding and the content
  9345. // type alone, so it compressed the stored bytes a second time and appended a
  9346. // second Content-Encoding field line.
  9347. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9348. auto port = start(enable_without_floor);
  9349. Client cli(HOST, port);
  9350. cli.set_decompress(false);
  9351. auto res = cli.Get("/pre-encoded-file-content",
  9352. Headers{{"Accept-Encoding", "gzip"}});
  9353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9354. EXPECT_EQ(StatusCode::OK_200, res->status);
  9355. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9356. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9357. // Vary belongs to a coding the server chose, and it chose none here.
  9358. EXPECT_FALSE(res->has_header("Vary"));
  9359. // The file travels exactly as it is stored on disk.
  9360. EXPECT_EQ(104U, res->body.size());
  9361. }
  9362. // The 1MB file clears the default floor, so this one runs the configuration a
  9363. // deployment would actually have.
  9364. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9365. auto port = start(enable);
  9366. Client cli(HOST, port);
  9367. cli.set_decompress(false);
  9368. auto res =
  9369. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9371. EXPECT_EQ(StatusCode::OK_200, res->status);
  9372. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9373. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9374. EXPECT_FALSE(res->has_header("Vary"));
  9375. EXPECT_EQ(1048576U, res->body.size());
  9376. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9377. }
  9378. TEST_F(StaticFileCompressionTest, Head) {
  9379. auto port = start(enable);
  9380. Client cli(HOST, port);
  9381. cli.set_decompress(false);
  9382. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9383. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9384. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9386. EXPECT_EQ(StatusCode::OK_200, res->status);
  9387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9388. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9389. // HEAD still reports the size a GET would return.
  9390. EXPECT_EQ(get->get_header_value("Content-Length"),
  9391. res->get_header_value("Content-Length"));
  9392. EXPECT_TRUE(res->body.empty());
  9393. }
  9394. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9395. auto port = start(enable);
  9396. Client cli(HOST, port);
  9397. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9398. {"Accept-Encoding", "gzip"}});
  9399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9401. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9402. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9403. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9404. EXPECT_EQ("cd", res->body);
  9405. }
  9406. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9407. auto port = start(enable);
  9408. Client cli(HOST, port);
  9409. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9411. EXPECT_EQ(StatusCode::OK_200, res->status);
  9412. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9413. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9414. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9415. }
  9416. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9417. auto port = start(enable);
  9418. Client cli(HOST, port);
  9419. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9421. EXPECT_EQ(StatusCode::OK_200, res->status);
  9422. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9423. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9424. EXPECT_TRUE(res->body.empty());
  9425. }
  9426. TEST_F(StaticFileCompressionTest, MinLength) {
  9427. auto port = start(enable);
  9428. Client cli(HOST, port);
  9429. // 104 bytes, well under the default floor. Compressing it would add the
  9430. // gzip header and trailer to a body that already fits in one packet.
  9431. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9433. EXPECT_EQ(StatusCode::OK_200, res->status);
  9434. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9435. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9436. }
  9437. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9438. auto port = start([](Server &svr) {
  9439. svr.set_static_file_compression(true);
  9440. svr.set_static_file_compression_min_length(1);
  9441. });
  9442. Client cli(HOST, port);
  9443. cli.set_decompress(false);
  9444. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9446. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9447. // A 9-byte file comes back larger than it went in, because gzip's header and
  9448. // trailer outweigh anything deflate can save. That is the end of the range
  9449. // the floor exists to keep out.
  9450. EXPECT_GT(res->body.size(), 9U);
  9451. }
  9452. TEST_F(StaticFileCompressionTest, MaxLength) {
  9453. auto port = start([](Server &svr) {
  9454. svr.set_static_file_compression(true);
  9455. svr.set_static_file_compression_min_length(0);
  9456. svr.set_static_file_compression_max_length(1024);
  9457. });
  9458. Client cli(HOST, port);
  9459. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9460. // defines `small` as a macro on Windows.
  9461. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9462. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9463. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9464. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9465. // Under it: compressed.
  9466. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9467. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9468. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9469. }
  9470. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9471. auto port = start(enable_without_floor);
  9472. Client cli(HOST, port);
  9473. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9474. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9475. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9476. auto identity_etag = identity->get_header_value("ETag");
  9477. ASSERT_FALSE(identity_etag.empty());
  9478. auto gzipped =
  9479. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9480. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9481. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9482. auto gzip_etag = gzipped->get_header_value("ETag");
  9483. ASSERT_FALSE(gzip_etag.empty());
  9484. // Two representations, two validators.
  9485. EXPECT_NE(identity_etag, gzip_etag);
  9486. // Each one revalidates against the request that would produce it...
  9487. auto fresh =
  9488. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9489. {"If-None-Match", gzip_etag}});
  9490. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9491. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9492. auto fresh_identity =
  9493. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9494. {"If-None-Match", identity_etag}});
  9495. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9496. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9497. // ...and not against the other representation.
  9498. auto crossed =
  9499. cli.Get("/dir/index.html",
  9500. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9501. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9502. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9503. }
  9504. // The opt-in covers responses the server reads off disk itself. A caller's own
  9505. // known-length provider keeps its Content-Length and, more importantly, keeps
  9506. // delivering incrementally: routing it through a compressor would hold every
  9507. // write back until zlib's window filled.
  9508. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9509. auto port = start(enable);
  9510. Client cli(HOST, port);
  9511. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9513. EXPECT_EQ(StatusCode::OK_200, res->status);
  9514. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9515. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9516. EXPECT_EQ("aaabbb", res->body);
  9517. }
  9518. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9519. auto port = start(enable);
  9520. Client cli(HOST, port);
  9521. cli.set_read_timeout(1, 0);
  9522. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9523. Headers{{"Accept-Encoding", "gzip"}});
  9524. ASSERT_TRUE(handle.is_valid());
  9525. // The provider writes 100 bytes and then stalls for longer than the read
  9526. // timeout. Those first bytes have to arrive anyway: run the response through
  9527. // a compressor and zlib holds them until its window fills, so the read would
  9528. // come back empty instead.
  9529. char buf[256];
  9530. auto n = handle.read(buf, sizeof(buf));
  9531. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9532. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9533. }
  9534. #endif
  9535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9536. TEST_F(ServerTest, Brotli) {
  9537. Headers headers;
  9538. headers.emplace("Accept-Encoding", "br");
  9539. auto res = cli_.Get("/compress", headers);
  9540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9541. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9543. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9545. "7890123456789012345678901234567890",
  9546. res->body);
  9547. EXPECT_EQ(StatusCode::OK_200, res->status);
  9548. }
  9549. #endif
  9550. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9551. TEST_F(ServerTest, Zstd) {
  9552. Headers headers;
  9553. headers.emplace("Accept-Encoding", "zstd");
  9554. auto res = cli_.Get("/compress", headers);
  9555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9556. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9558. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9559. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9560. "7890123456789012345678901234567890",
  9561. res->body);
  9562. EXPECT_EQ(StatusCode::OK_200, res->status);
  9563. }
  9564. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9565. Headers headers;
  9566. headers.emplace("Accept-Encoding", "");
  9567. auto res = cli_.Get("/compress", headers);
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9573. "7890123456789012345678901234567890",
  9574. res->body);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. }
  9577. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9578. Headers headers;
  9579. headers.emplace("Accept-Encoding", "zstd");
  9580. std::string body;
  9581. auto res =
  9582. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9583. EXPECT_EQ(100U, data_length);
  9584. body.append(data, data_length);
  9585. return true;
  9586. });
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9590. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9591. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9592. "7890123456789012345678901234567890",
  9593. body);
  9594. EXPECT_EQ(StatusCode::OK_200, res->status);
  9595. }
  9596. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9597. Headers headers;
  9598. headers.emplace("Accept-Encoding", "zstd");
  9599. cli_.set_decompress(false);
  9600. auto res = cli_.Get("/compress", headers);
  9601. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9602. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9603. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9604. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9606. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9608. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. ASSERT_EQ(26U, res->body.size());
  9611. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9612. 0);
  9613. }
  9614. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9615. Headers headers;
  9616. headers.emplace("Accept-Encoding", "");
  9617. std::string body;
  9618. auto res =
  9619. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9620. EXPECT_EQ(100U, data_length);
  9621. body.append(data, data_length);
  9622. return true;
  9623. });
  9624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9625. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9626. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9627. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9628. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9629. "7890123456789012345678901234567890",
  9630. body);
  9631. EXPECT_EQ(StatusCode::OK_200, res->status);
  9632. }
  9633. TEST_F(ServerTest, NoZstd) {
  9634. Headers headers;
  9635. headers.emplace("Accept-Encoding", "zstd");
  9636. auto res = cli_.Get("/nocompress", headers);
  9637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9638. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9639. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9640. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9641. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9642. "7890123456789012345678901234567890",
  9643. res->body);
  9644. EXPECT_EQ(StatusCode::OK_200, res->status);
  9645. }
  9646. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9647. Headers headers;
  9648. headers.emplace("Accept-Encoding", "zstd");
  9649. std::string body;
  9650. auto res = cli_.Get("/nocompress", headers,
  9651. [&](const char *data, size_t data_length) {
  9652. EXPECT_EQ(100U, data_length);
  9653. body.append(data, data_length);
  9654. return true;
  9655. });
  9656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9657. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9658. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9659. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9660. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9661. "7890123456789012345678901234567890",
  9662. body);
  9663. EXPECT_EQ(StatusCode::OK_200, res->status);
  9664. }
  9665. // TODO: How to enable zstd ??
  9666. TEST_F(ServerTest, MultipartFormDataZstd) {
  9667. UploadFormDataItems items = {
  9668. {"key1", "test", "", ""},
  9669. {"key2", "--abcdefg123", "", ""},
  9670. };
  9671. Headers headers;
  9672. headers.emplace("Accept-Encoding", "zstd");
  9673. cli_.set_compress(true);
  9674. auto res = cli_.Post("/compress-multipart", headers, items);
  9675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9676. EXPECT_EQ(StatusCode::OK_200, res->status);
  9677. }
  9678. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9679. Headers headers;
  9680. headers.emplace("Accept-Encoding", "zstd");
  9681. cli_.set_compress(true);
  9682. auto res = cli_.Put(
  9683. "/put", headers, 3,
  9684. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9685. sink.os << "PUT";
  9686. return true;
  9687. },
  9688. "text/plain");
  9689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9690. EXPECT_EQ(StatusCode::OK_200, res->status);
  9691. EXPECT_EQ("PUT", res->body);
  9692. }
  9693. // Pre-compression logging tests
  9694. TEST_F(ServerTest, PreCompressionLogging) {
  9695. // Test data for compression (matches the actual /compress endpoint content)
  9696. const std::string test_content =
  9697. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9698. "3456789012345678901234567890";
  9699. // Variables to capture logging data
  9700. std::string pre_compression_body;
  9701. std::string pre_compression_content_type;
  9702. std::string pre_compression_content_encoding;
  9703. std::string post_compression_body;
  9704. std::string post_compression_content_type;
  9705. std::string post_compression_content_encoding;
  9706. // Set up pre-compression logger
  9707. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9708. const Response &res) {
  9709. pre_compression_body = res.body;
  9710. pre_compression_content_type = res.get_header_value("Content-Type");
  9711. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9712. });
  9713. // Set up post-compression logger
  9714. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9715. post_compression_body = res.body;
  9716. post_compression_content_type = res.get_header_value("Content-Type");
  9717. post_compression_content_encoding =
  9718. res.get_header_value("Content-Encoding");
  9719. });
  9720. // Test with gzip compression
  9721. Headers headers;
  9722. headers.emplace("Accept-Encoding", "gzip");
  9723. auto res = cli_.Get("/compress", headers);
  9724. // Verify response was compressed
  9725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9726. EXPECT_EQ(StatusCode::OK_200, res->status);
  9727. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9728. // Verify pre-compression logger captured uncompressed content
  9729. EXPECT_EQ(test_content, pre_compression_body);
  9730. EXPECT_EQ("text/plain", pre_compression_content_type);
  9731. EXPECT_TRUE(pre_compression_content_encoding
  9732. .empty()); // No encoding header before compression
  9733. // Verify post-compression logger captured compressed content
  9734. EXPECT_NE(test_content,
  9735. post_compression_body); // Should be different after compression
  9736. EXPECT_EQ("text/plain", post_compression_content_type);
  9737. EXPECT_EQ("gzip", post_compression_content_encoding);
  9738. // Verify compressed content is smaller
  9739. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9740. }
  9741. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9742. const std::string test_content =
  9743. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9744. "3456789012345678901234567890";
  9745. std::string pre_compression_body;
  9746. std::string post_compression_body;
  9747. svr_.set_pre_compression_logger(
  9748. [&](const Request & /*req*/, const Response &res) {
  9749. pre_compression_body = res.body;
  9750. });
  9751. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9752. post_compression_body = res.body;
  9753. });
  9754. Headers headers;
  9755. headers.emplace("Accept-Encoding", "br");
  9756. auto res = cli_.Get("/compress", headers);
  9757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9758. EXPECT_EQ(StatusCode::OK_200, res->status);
  9759. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9760. // Verify pre-compression content is uncompressed
  9761. EXPECT_EQ(test_content, pre_compression_body);
  9762. // Verify post-compression content is compressed
  9763. EXPECT_NE(test_content, post_compression_body);
  9764. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9765. }
  9766. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9767. const std::string test_content =
  9768. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9769. "3456789012345678901234567890";
  9770. std::string pre_compression_body;
  9771. std::string post_compression_body;
  9772. svr_.set_pre_compression_logger(
  9773. [&](const Request & /*req*/, const Response &res) {
  9774. pre_compression_body = res.body;
  9775. });
  9776. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9777. post_compression_body = res.body;
  9778. });
  9779. // Request without compression (use /nocompress endpoint)
  9780. Headers headers;
  9781. auto res = cli_.Get("/nocompress", headers);
  9782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9783. EXPECT_EQ(StatusCode::OK_200, res->status);
  9784. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9785. // Pre-compression logger should not be called when no compression is applied
  9786. EXPECT_TRUE(
  9787. pre_compression_body.empty()); // Pre-compression logger not called
  9788. EXPECT_EQ(
  9789. test_content,
  9790. post_compression_body); // Post-compression logger captures final content
  9791. }
  9792. TEST_F(ServerTest, LoggerSeesContentLength) {
  9793. size_t logged_content_length = 0;
  9794. std::string logged_content_length_header;
  9795. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9796. logged_content_length = res.content_length_;
  9797. logged_content_length_header = res.get_header_value("Content-Length");
  9798. });
  9799. auto res = cli_.Get("/nocompress");
  9800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9801. EXPECT_EQ(StatusCode::OK_200, res->status);
  9802. EXPECT_EQ(res->body.size(), logged_content_length);
  9803. EXPECT_EQ(std::to_string(logged_content_length),
  9804. logged_content_length_header);
  9805. }
  9806. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9807. const std::string test_content =
  9808. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9809. "3456789012345678901234567890";
  9810. std::string pre_compression_body;
  9811. bool pre_logger_called = false;
  9812. // Set only pre-compression logger
  9813. svr_.set_pre_compression_logger(
  9814. [&](const Request & /*req*/, const Response &res) {
  9815. pre_compression_body = res.body;
  9816. pre_logger_called = true;
  9817. });
  9818. Headers headers;
  9819. headers.emplace("Accept-Encoding", "gzip");
  9820. auto res = cli_.Get("/compress", headers);
  9821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9822. EXPECT_EQ(StatusCode::OK_200, res->status);
  9823. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9824. // Verify pre-compression logger was called
  9825. EXPECT_TRUE(pre_logger_called);
  9826. EXPECT_EQ(test_content, pre_compression_body);
  9827. }
  9828. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9829. {
  9830. // Test with Expect: 100-continue header - success case
  9831. // Server returns 100 Continue, client sends body, server returns 200 OK
  9832. Request req;
  9833. req.method = "POST";
  9834. req.path = "/post-large";
  9835. req.set_header("Expect", "100-continue");
  9836. req.body = LARGE_DATA;
  9837. Response res;
  9838. auto error = Error::Success;
  9839. cli_.set_keep_alive(true);
  9840. auto ret = cli_.send(req, res, error);
  9841. EXPECT_TRUE(ret);
  9842. EXPECT_EQ(StatusCode::OK_200, res.status);
  9843. EXPECT_EQ(LARGE_DATA, res.body);
  9844. }
  9845. {
  9846. // Test with Expect: 100-continue header - error case
  9847. // Client should not send the body when server returns an error
  9848. Request req;
  9849. req.method = "POST";
  9850. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9851. req.set_header("Expect", "100-continue");
  9852. req.body = LARGE_DATA;
  9853. Response res;
  9854. auto error = Error::Success;
  9855. auto start = std::chrono::high_resolution_clock::now();
  9856. cli_.set_keep_alive(true);
  9857. auto ret = cli_.send(req, res, error);
  9858. auto end = std::chrono::high_resolution_clock::now();
  9859. auto elapsed =
  9860. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9861. .count();
  9862. // With Expect: 100-continue, request completes successfully but with error
  9863. EXPECT_TRUE(ret);
  9864. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9865. EXPECT_EQ("close", res.get_header_value("Connection"));
  9866. EXPECT_FALSE(cli_.is_socket_open());
  9867. EXPECT_LE(elapsed, 2000);
  9868. }
  9869. {
  9870. // Send an extra GET request to ensure error recovery without hanging
  9871. Request req;
  9872. req.method = "GET";
  9873. req.path = "/hi";
  9874. auto start = std::chrono::high_resolution_clock::now();
  9875. auto res = cli_.send(req);
  9876. auto end = std::chrono::high_resolution_clock::now();
  9877. auto elapsed =
  9878. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9879. .count();
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. EXPECT_EQ("Hello World!", res->body);
  9883. EXPECT_LE(elapsed, 500);
  9884. }
  9885. }
  9886. TEST(ZstdDecompressor, ChunkedDecompression) {
  9887. std::string data;
  9888. for (size_t i = 0; i < 32 * 1024; ++i) {
  9889. data.push_back(static_cast<char>('a' + i % 26));
  9890. }
  9891. std::string compressed_data;
  9892. {
  9893. httplib::detail::zstd_compressor compressor;
  9894. bool result = compressor.compress(
  9895. data.data(), data.size(),
  9896. /*last=*/true,
  9897. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9898. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9899. compressed_data_size);
  9900. return true;
  9901. });
  9902. ASSERT_TRUE(result);
  9903. }
  9904. std::string decompressed_data;
  9905. {
  9906. httplib::detail::zstd_decompressor decompressor;
  9907. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9908. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9909. size_t chunk_size = 130;
  9910. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9911. chunk_begin += chunk_size) {
  9912. size_t current_chunk_size =
  9913. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9914. bool result = decompressor.decompress(
  9915. compressed_data.data() + chunk_begin, current_chunk_size,
  9916. [&](const char *decompressed_data_chunk,
  9917. size_t decompressed_data_chunk_size) {
  9918. decompressed_data.insert(decompressed_data.size(),
  9919. decompressed_data_chunk,
  9920. decompressed_data_chunk_size);
  9921. return true;
  9922. });
  9923. ASSERT_TRUE(result);
  9924. }
  9925. }
  9926. ASSERT_EQ(data, decompressed_data);
  9927. }
  9928. TEST(ZstdDecompressor, Decompress) {
  9929. std::string original_text = "Compressed with ZSTD";
  9930. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9931. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9932. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9933. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9934. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9935. std::string decompressed_data;
  9936. {
  9937. httplib::detail::zstd_decompressor decompressor;
  9938. bool result = decompressor.decompress(
  9939. compressed_data.data(), compressed_data.size(),
  9940. [&](const char *decompressed_data_chunk,
  9941. size_t decompressed_data_chunk_size) {
  9942. decompressed_data.insert(decompressed_data.size(),
  9943. decompressed_data_chunk,
  9944. decompressed_data_chunk_size);
  9945. return true;
  9946. });
  9947. ASSERT_TRUE(result);
  9948. }
  9949. ASSERT_EQ(original_text, decompressed_data);
  9950. }
  9951. #endif
  9952. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9953. // separate chunks so that the server sees each part in its own read(). Used to
  9954. // place a read boundary at a specific offset of a request body.
  9955. static bool send_request_in_parts(time_t read_timeout_sec,
  9956. const std::vector<std::string> &parts,
  9957. std::string *resp = nullptr,
  9958. int port = PORT) {
  9959. auto error = Error::Success;
  9960. auto client_sock = detail::create_client_socket(
  9961. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9962. /*connection_timeout_sec=*/5, 0,
  9963. /*read_timeout_sec=*/5, 0,
  9964. /*write_timeout_sec=*/5, 0, std::string(), error);
  9965. if (client_sock == INVALID_SOCKET) { return false; }
  9966. auto ret = detail::process_client_socket(
  9967. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9968. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9969. for (size_t i = 0; i < parts.size(); i++) {
  9970. const auto &part = parts[i];
  9971. if (part.size() !=
  9972. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9973. return false;
  9974. }
  9975. if (i + 1 < parts.size()) {
  9976. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9977. }
  9978. }
  9979. char buf[512];
  9980. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9981. while (line_reader.getline()) {
  9982. if (resp) { *resp += line_reader.ptr(); }
  9983. }
  9984. return true;
  9985. });
  9986. detail::close_socket(client_sock);
  9987. return ret;
  9988. }
  9989. // Sends a raw request to a server listening at HOST:PORT.
  9990. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9991. std::string *resp = nullptr, int port = PORT) {
  9992. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9993. }
  9994. #ifdef CPPHTTPLIB_SSL_ENABLED
  9995. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9997. ASSERT_TRUE(svr.is_valid());
  9998. svr.set_read_timeout(1, 0);
  9999. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10000. auto se = detail::scope_exit([&] {
  10001. svr.stop();
  10002. t.join();
  10003. ASSERT_FALSE(svr.is_running());
  10004. });
  10005. svr.wait_until_ready();
  10006. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10007. // keeps each wait well within the read timeout. The server gives up a
  10008. // second in, so the bytes sent after that fail.
  10009. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10010. parts.resize(26, std::string(1, '\0'));
  10011. EXPECT_FALSE(send_request_in_parts(5, parts));
  10012. }
  10013. #endif
  10014. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10015. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10016. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10017. const std::vector<std::string> &parts,
  10018. std::string *resp = nullptr,
  10019. int port = PORT) {
  10020. auto error = Error::Success;
  10021. auto sock = detail::create_client_socket(
  10022. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10023. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10024. /*write_timeout_sec=*/5, 0, std::string(), error);
  10025. if (sock == INVALID_SOCKET) { return false; }
  10026. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10027. auto ctx = SSL_CTX_new(TLS_client_method());
  10028. auto ssl = SSL_new(ctx);
  10029. auto ssl_se = detail::scope_exit([&] {
  10030. SSL_free(ssl);
  10031. SSL_CTX_free(ctx);
  10032. });
  10033. SSL_set_fd(ssl, static_cast<int>(sock));
  10034. if (SSL_connect(ssl) != 1) { return false; }
  10035. for (size_t i = 0; i < parts.size(); i++) {
  10036. const auto &part = parts[i];
  10037. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10038. static_cast<int>(part.size())) {
  10039. return false;
  10040. }
  10041. if (i + 1 < parts.size()) {
  10042. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10043. }
  10044. }
  10045. char buf[512];
  10046. int n;
  10047. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10048. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10049. }
  10050. return true;
  10051. }
  10052. #endif
  10053. // The request line, then a header value a byte at a time.
  10054. static std::vector<std::string> slow_request_head_parts() {
  10055. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10056. parts.resize(26, "a");
  10057. parts.emplace_back("\r\n\r\n");
  10058. return parts;
  10059. }
  10060. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10061. // within the one-second read timeout. The server gives up a second in, before
  10062. // the head is complete.
  10063. static void
  10064. expect_slow_request_head_dropped(Server &svr,
  10065. const std::function<std::string()> &send) {
  10066. std::atomic<bool> handled(false);
  10067. svr.Get("/", [&](const Request &, Response &res) {
  10068. handled = true;
  10069. res.set_content("ok", "text/plain");
  10070. });
  10071. svr.set_read_timeout(1, 0);
  10072. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. t.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. auto resp = send();
  10080. EXPECT_FALSE(handled);
  10081. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10082. }
  10083. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10084. Server svr;
  10085. expect_slow_request_head_dropped(svr, [] {
  10086. std::string resp;
  10087. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10088. return resp;
  10089. });
  10090. }
  10091. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10092. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10094. ASSERT_TRUE(svr.is_valid());
  10095. expect_slow_request_head_dropped(svr, [] {
  10096. std::string resp;
  10097. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10098. return resp;
  10099. });
  10100. }
  10101. #endif
  10102. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10103. Server svr;
  10104. std::string header_value;
  10105. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10106. header_value = req.get_header_value("foo");
  10107. res.set_content("ok", "text/plain");
  10108. });
  10109. thread t = thread([&] { svr.listen(HOST, PORT); });
  10110. auto se = detail::scope_exit([&] {
  10111. svr.stop();
  10112. t.join();
  10113. ASSERT_FALSE(svr.is_running());
  10114. });
  10115. svr.wait_until_ready();
  10116. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10117. // like characters are not treated the same - use vertical tab and escape.
  10118. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10119. "foo: \t \v bar \x1B\t \r\n"
  10120. "Connection: close\r\n"
  10121. "\r\n";
  10122. std::string res;
  10123. ASSERT_TRUE(send_request(5, req, &res));
  10124. EXPECT_EQ(header_value, "");
  10125. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10126. }
  10127. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10128. Server svr;
  10129. std::string received;
  10130. svr.Get("/order", [&](const Request &req, Response &res) {
  10131. received = entries_to_string(req.headers);
  10132. res.set_content("ok", "text/plain");
  10133. });
  10134. auto port = svr.bind_to_any_port(HOST);
  10135. thread t = thread([&] { svr.listen_after_bind(); });
  10136. auto se = detail::scope_exit([&] {
  10137. svr.stop();
  10138. t.join();
  10139. ASSERT_FALSE(svr.is_running());
  10140. });
  10141. svr.wait_until_ready();
  10142. const std::string req = "GET /order HTTP/1.1\r\n"
  10143. "Host: localhost\r\n"
  10144. "X-First: 1\r\n"
  10145. "X-Dup: a\r\n"
  10146. "X-Second: 2\r\n"
  10147. "X-Dup: b\r\n"
  10148. "Connection: close\r\n"
  10149. "\r\n";
  10150. std::string res;
  10151. ASSERT_TRUE(send_request(5, req, &res, port));
  10152. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10153. EXPECT_EQ(
  10154. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10155. received);
  10156. }
  10157. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10158. Server svr;
  10159. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10160. res.set_header("Set-Cookie", "first=1");
  10161. res.set_header("X-Between", "y");
  10162. res.set_header("Set-Cookie", "second=2");
  10163. res.set_content("ok", "text/plain");
  10164. });
  10165. auto port = svr.bind_to_any_port(HOST);
  10166. thread t = thread([&] { svr.listen_after_bind(); });
  10167. auto se = detail::scope_exit([&] {
  10168. svr.stop();
  10169. t.join();
  10170. ASSERT_FALSE(svr.is_running());
  10171. });
  10172. svr.wait_until_ready();
  10173. Client cli(HOST, port);
  10174. auto res = cli.Get("/cookies");
  10175. ASSERT_TRUE(res);
  10176. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10177. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10178. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10179. }
  10180. // A stream may send a byte at a time with a small extension on each chunk,
  10181. // however long it runs
  10182. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10183. Server svr;
  10184. svr.Post("/count", [](const Request &req, Response &res) {
  10185. res.set_content(std::to_string(req.body.size()), "text/plain");
  10186. });
  10187. auto port = svr.bind_to_any_port(HOST);
  10188. ASSERT_LT(0, port);
  10189. thread t = thread([&] { svr.listen_after_bind(); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10197. "\r\nTransfer-Encoding: chunked\r\n"
  10198. "Connection: close\r\n\r\n";
  10199. for (auto i = 0; i < 4096; i++) {
  10200. req += "1;a=b\r\nx\r\n";
  10201. }
  10202. req += "0\r\n\r\n";
  10203. std::string res;
  10204. ASSERT_TRUE(send_request(5, req, &res, port));
  10205. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10206. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10207. }
  10208. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10209. Server svr;
  10210. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10211. auto i = new int(0);
  10212. res.set_header("Trailer", "X-Safe, X-Reflected");
  10213. res.set_chunked_content_provider(
  10214. "text/plain",
  10215. [i](size_t /*offset*/, DataSink &sink) {
  10216. if (*i == 0) {
  10217. sink.os << "body";
  10218. } else {
  10219. Headers trailer;
  10220. // A valid trailer that must survive.
  10221. trailer.emplace("X-Safe", "safe");
  10222. // Attacker-controlled value carrying CR/LF (response splitting).
  10223. trailer.emplace("X-Reflected",
  10224. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10225. // Attacker-controlled name carrying CR/LF.
  10226. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10227. sink.done_with_trailer(trailer);
  10228. }
  10229. (*i)++;
  10230. return true;
  10231. },
  10232. [i](bool /*success*/) { delete i; });
  10233. });
  10234. thread t = thread([&] { svr.listen(HOST, PORT); });
  10235. auto se = detail::scope_exit([&] {
  10236. svr.stop();
  10237. t.join();
  10238. ASSERT_FALSE(svr.is_running());
  10239. });
  10240. svr.wait_until_ready();
  10241. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10242. "Host: " + HOST +
  10243. "\r\n"
  10244. "Connection: close\r\n"
  10245. "\r\n";
  10246. std::string res;
  10247. ASSERT_TRUE(send_request(5, req, &res));
  10248. // The injected fields must not appear anywhere in the raw response.
  10249. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10250. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10251. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10252. // Invalid trailers are dropped entirely, matching set_header().
  10253. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10254. // The valid trailer still passes through.
  10255. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10256. }
  10257. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10258. // A custom header writer gets only the fields the default one writes
  10259. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10260. std::string s;
  10261. for (const auto &h : hdrs) {
  10262. s += h.first + ": " + h.second + "\r\n";
  10263. }
  10264. s += "\r\n";
  10265. return strm.write(s.data(), s.size());
  10266. };
  10267. for (auto custom_writer : {false, true}) {
  10268. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10269. Server svr;
  10270. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10271. svr.set_post_routing_handler([](const Request &, Response &res) {
  10272. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10273. });
  10274. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10275. // res.headers is a public field an application can populate directly,
  10276. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10277. // A valid header that must survive.
  10278. res.headers.emplace("X-Safe", "safe");
  10279. // Attacker-controlled value carrying CR/LF (response splitting).
  10280. res.headers.emplace("X-Reflected",
  10281. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10282. // Attacker-controlled name carrying CR/LF.
  10283. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10284. res.set_content("body", "text/plain");
  10285. });
  10286. thread t = thread([&] { svr.listen(HOST, PORT); });
  10287. auto se = detail::scope_exit([&] {
  10288. svr.stop();
  10289. t.join();
  10290. ASSERT_FALSE(svr.is_running());
  10291. });
  10292. svr.wait_until_ready();
  10293. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10294. "Host: " + HOST +
  10295. "\r\n"
  10296. "Connection: close\r\n"
  10297. "\r\n";
  10298. std::string res;
  10299. ASSERT_TRUE(send_request(5, req, &res));
  10300. // The injected fields must not appear anywhere in the raw response.
  10301. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10302. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10303. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10304. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10305. // Invalid headers are dropped entirely, matching set_header().
  10306. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10307. // The valid header still passes through.
  10308. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10309. }
  10310. }
  10311. // Forward declaration: in split builds split.py strips `inline` and moves the
  10312. // definition into httplib.cc, so detail::write_request_line is not visible from
  10313. // the public httplib.h. Re-declaring it here lets the tests link against the
  10314. // symbol in both header-only and split builds.
  10315. namespace httplib {
  10316. namespace detail {
  10317. ssize_t write_request_line(Stream &strm, const std::string &method,
  10318. const std::string &path);
  10319. } // namespace detail
  10320. } // namespace httplib
  10321. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10322. // A well-formed target is written verbatim.
  10323. {
  10324. detail::BufferStream strm;
  10325. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10326. EXPECT_GT(n, 0);
  10327. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10328. }
  10329. // A target carrying CR/LF, SP or other control octets must be rejected
  10330. // before anything reaches the wire, otherwise it splits the request line and
  10331. // injects a header or a whole request.
  10332. const std::string evil_targets[] = {
  10333. "/a\r\nInjected: pwned",
  10334. "/a\rInjected",
  10335. "/a\nInjected",
  10336. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10337. "/a b",
  10338. "/a\tb",
  10339. "/a\x7f",
  10340. };
  10341. for (const auto &evil : evil_targets) {
  10342. detail::BufferStream strm;
  10343. auto n = detail::write_request_line(strm, "GET", evil);
  10344. EXPECT_LT(n, 0);
  10345. EXPECT_TRUE(strm.get_buffer().empty());
  10346. }
  10347. }
  10348. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10349. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10350. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10351. // target reaches write_request. The client must fail cleanly with
  10352. // Error::Write instead of putting a request-line-less, header-injecting
  10353. // request on the wire.
  10354. Server svr;
  10355. svr.Get("/a", [](const Request &, Response &res) {
  10356. res.set_content("ok", "text/plain");
  10357. });
  10358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10359. auto se = detail::scope_exit([&] {
  10360. svr.stop();
  10361. thread.join();
  10362. ASSERT_FALSE(svr.is_running());
  10363. });
  10364. svr.wait_until_ready();
  10365. {
  10366. Client cli(HOST, PORT);
  10367. cli.set_path_encode(false);
  10368. // The request is rejected before anything is written, so the connection
  10369. // stays silent and the subsequent response read would otherwise block for
  10370. // the full default read timeout. Shorten it -- the assertion is on the
  10371. // error, not the timeout.
  10372. cli.set_read_timeout(1, 0);
  10373. auto res = cli.Get("/a\r\nInjected: pwned");
  10374. EXPECT_FALSE(res);
  10375. EXPECT_EQ(Error::Write, res.error());
  10376. }
  10377. }
  10378. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10379. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10380. // including extension methods.
  10381. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10382. for (const auto &method : good_methods) {
  10383. detail::BufferStream strm;
  10384. auto n = detail::write_request_line(strm, method, "/");
  10385. EXPECT_GT(n, 0);
  10386. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10387. }
  10388. // A method carrying CR/LF would split the request line and smuggle a whole
  10389. // request ahead of the real one. A space or an empty method corrupts the
  10390. // request line. All must be rejected before anything reaches the wire.
  10391. const std::string evil_methods[] = {
  10392. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10393. "GET\r\nInjected: pwned",
  10394. "GET\r",
  10395. "GET\n",
  10396. "GE T",
  10397. "",
  10398. };
  10399. for (const auto &evil : evil_methods) {
  10400. detail::BufferStream strm;
  10401. auto n = detail::write_request_line(strm, evil, "/");
  10402. EXPECT_LT(n, 0);
  10403. EXPECT_TRUE(strm.get_buffer().empty());
  10404. }
  10405. }
  10406. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10407. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10408. // through Client::send must fail with Error::Write and no request, neither
  10409. // the smuggled one nor the real one, may reach the server.
  10410. Server svr;
  10411. std::atomic<int> request_count(0);
  10412. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10413. request_count++;
  10414. res.status = StatusCode::OK_200;
  10415. return Server::HandlerResponse::Handled;
  10416. });
  10417. auto port = svr.bind_to_any_port(HOST);
  10418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. thread.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. {
  10426. Client cli(HOST, port);
  10427. const std::string evil_methods[] = {
  10428. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10429. "GE T",
  10430. "",
  10431. };
  10432. for (const auto &evil : evil_methods) {
  10433. Request req;
  10434. req.method = evil;
  10435. req.path = "/";
  10436. auto res = cli.send(req);
  10437. EXPECT_FALSE(res);
  10438. EXPECT_EQ(Error::Write, res.error());
  10439. }
  10440. auto handle =
  10441. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10442. EXPECT_FALSE(handle.is_valid());
  10443. EXPECT_EQ(Error::Write, handle.error);
  10444. // A valid request on the same client still goes through.
  10445. auto res = cli.Get("/");
  10446. ASSERT_TRUE(res);
  10447. EXPECT_EQ(StatusCode::OK_200, res->status);
  10448. }
  10449. EXPECT_EQ(1, request_count.load());
  10450. }
  10451. // Sends a raw request and verifies that there isn't a crash or exception.
  10452. static void test_raw_request(const std::string &req,
  10453. std::string *out = nullptr) {
  10454. Server svr;
  10455. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10456. res.set_content("ok", "text/plain");
  10457. });
  10458. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10459. res.set_content("ok", "text/plain");
  10460. });
  10461. svr.Get("/header_field_value_check",
  10462. [&](const Request & /*req*/, Response &res) {
  10463. res.set_content("ok", "text/plain");
  10464. });
  10465. svr.CustomRoute("PROPFIND", "/dav",
  10466. [&](const Request & /*req*/, Response &res) {
  10467. res.status = StatusCode::MultiStatus_207;
  10468. });
  10469. // Server read timeout must be longer than the client read timeout for the
  10470. // bug to reproduce, probably to force the server to process a request
  10471. // without a trailing blank line.
  10472. const time_t client_read_timeout_sec = 1;
  10473. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10474. bool listen_thread_ok = false;
  10475. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. ASSERT_FALSE(svr.is_running());
  10480. EXPECT_TRUE(listen_thread_ok);
  10481. });
  10482. svr.wait_until_ready();
  10483. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10484. }
  10485. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10486. // A certain header line causes an exception if the header property is parsed
  10487. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10488. test_raw_request(
  10489. "GET /hi HTTP/1.1\r\n"
  10490. " : "
  10491. " "
  10492. " ");
  10493. }
  10494. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10495. // A certain header line causes an exception if the header property *name* is
  10496. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10497. // greedy matcher and requires backtracking when there are a lot of ":"
  10498. // characters.
  10499. // This occurs with libc++ but not libstdc++.
  10500. test_raw_request(
  10501. "GET /hi HTTP/1.1\r\n"
  10502. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10503. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10504. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10505. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10506. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10507. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10508. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10509. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10510. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10511. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10512. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10513. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10514. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10515. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10516. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10517. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10518. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10519. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10520. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10521. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10522. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10523. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10524. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10525. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10526. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10527. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10528. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10529. "&&&%%%");
  10530. }
  10531. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10532. // Make sure this doesn't crash the server.
  10533. // In a previous version of the header line regex, the "\r" rendered the line
  10534. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10535. // a new position where the leading white space ended and the field value
  10536. // began.
  10537. // The crash occurs with libc++ but not libstdc++.
  10538. test_raw_request("GET /hi HTTP/1.1\r\n"
  10539. "a:" +
  10540. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10541. "\r\n"
  10542. "\r\n");
  10543. }
  10544. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10545. const char *rejected[] = {
  10546. // RFC 9112 §3: one SP between the parts, and nothing else
  10547. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10548. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10549. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10550. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10551. // A request-target has no fragment
  10552. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10553. // An HTTP/1.1 request needs a Host
  10554. "GET /hi HTTP/1.1\r\n\r\n",
  10555. };
  10556. for (auto request : rejected) {
  10557. std::string out;
  10558. test_raw_request(request, &out);
  10559. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10560. }
  10561. std::string out;
  10562. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10563. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10564. }
  10565. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10566. // RFC 9112 §6.1
  10567. const char *requests[] = {
  10568. "PUT /put_hi HTTP/1.1\r\n"
  10569. "Host: localhost\r\n"
  10570. "Content-Length: 0\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "\r\n"
  10573. "0\r\n\r\n",
  10574. "PUT /put_hi HTTP/1.0\r\n"
  10575. "Connection: keep-alive\r\n"
  10576. "Transfer-Encoding: chunked\r\n"
  10577. "\r\n"
  10578. "0\r\n\r\n",
  10579. };
  10580. for (auto request : requests) {
  10581. std::string out;
  10582. test_raw_request(request, &out);
  10583. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10584. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10585. }
  10586. }
  10587. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10588. std::string out;
  10589. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10590. "Content-Type: text/plain\r\n"
  10591. "Transfer-Encoding: chunked\r\n"
  10592. "\r\n"
  10593. "nothex\r\n",
  10594. &out);
  10595. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10596. }
  10597. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10598. std::string out;
  10599. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10600. "Content-Type: text/plain\r\n"
  10601. "Transfer-Encoding: chunked\r\n"
  10602. "\r\n"
  10603. "3\r\n"
  10604. "xyz\r\n"
  10605. "NaN\r\n",
  10606. &out);
  10607. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10608. }
  10609. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10610. std::string out;
  10611. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10612. "Content-Type: text/plain\r\n"
  10613. "Transfer-Encoding: chunked\r\n"
  10614. "\r\n"
  10615. // Length is too large for 64 bits.
  10616. "1ffffffffffffffff\r\n"
  10617. "xyz\r\n",
  10618. &out);
  10619. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10620. }
  10621. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10622. test_raw_request("GET /hi HTTP/1.1\r\n"
  10623. "Content-Type: text/plain\r\n\r");
  10624. }
  10625. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10626. std::string out;
  10627. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10628. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10629. }
  10630. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10631. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10632. std::string out;
  10633. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10634. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10635. }
  10636. }
  10637. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10638. std::string out;
  10639. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10640. "Host: localhost\r\n"
  10641. "Connection: close\r\n\r\n",
  10642. &out);
  10643. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10644. }
  10645. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10646. Server svr;
  10647. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10648. EXPECT_TRUE(!req.remote_addr.empty());
  10649. });
  10650. thread t = thread([&] { svr.listen(HOST, PORT); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. t.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. // Send an invalid request line to trigger Bad Request
  10658. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10659. std::string out;
  10660. ASSERT_TRUE(send_request(5, bad_req, &out));
  10661. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10662. }
  10663. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10664. // answered right away rather than blocking on a read that waits for EOF.
  10665. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10666. std::string out;
  10667. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10668. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10669. }
  10670. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10671. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10672. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10673. for (const auto *method : methods) {
  10674. Server svr;
  10675. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10676. EXPECT_FALSE(svr.is_valid()) << method;
  10677. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10678. }
  10679. }
  10680. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10681. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10682. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10683. for (const auto *method : methods) {
  10684. Server svr;
  10685. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10686. EXPECT_FALSE(svr.is_valid()) << method;
  10687. }
  10688. }
  10689. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10690. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10691. "COPY", "MOVE", "LOCK",
  10692. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10693. Server svr;
  10694. for (const auto *method : methods) {
  10695. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10696. }
  10697. EXPECT_TRUE(svr.is_valid());
  10698. }
  10699. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10700. Server svr;
  10701. svr.CustomRoute("POST", "/x",
  10702. [](const Request &, Response &, const ContentReader &) {});
  10703. EXPECT_FALSE(svr.is_valid());
  10704. }
  10705. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10706. Server svr;
  10707. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10708. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10709. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10710. EXPECT_FALSE(svr.is_valid());
  10711. }
  10712. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10713. Server svr;
  10714. auto captured = Error::Success;
  10715. svr.set_error_logger(
  10716. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10717. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10718. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10719. }
  10720. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10721. std::string out;
  10722. std::string request(
  10723. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10724. test_raw_request(request, &out);
  10725. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10726. }
  10727. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10728. std::string out;
  10729. std::string request(
  10730. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10731. test_raw_request(request, &out);
  10732. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10733. }
  10734. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10735. std::string out;
  10736. std::string request(
  10737. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10738. test_raw_request(request, &out);
  10739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10740. }
  10741. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10742. std::string out;
  10743. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10744. "Host: localhost\r\n"
  10745. "Test: \r\n\r\n",
  10746. &out);
  10747. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10748. }
  10749. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10750. Server svr;
  10751. std::string x_custom;
  10752. std::string cookie;
  10753. std::string xff;
  10754. std::string x_unicode;
  10755. std::string x_iis;
  10756. svr.Get("/check", [&](const Request &req, Response &res) {
  10757. x_custom = req.get_header_value("X-Custom");
  10758. cookie = req.get_header_value("Cookie");
  10759. xff = req.get_header_value("X-Forwarded-For");
  10760. x_unicode = req.get_header_value("X-Unicode");
  10761. x_iis = req.get_header_value("X-IIS");
  10762. res.set_content("ok", "text/plain");
  10763. });
  10764. thread t = thread([&] { svr.listen(HOST, PORT); });
  10765. auto se = detail::scope_exit([&] {
  10766. svr.stop();
  10767. t.join();
  10768. ASSERT_FALSE(svr.is_running());
  10769. });
  10770. svr.wait_until_ready();
  10771. const std::string req = "GET /check HTTP/1.1\r\n"
  10772. "Host: localhost\r\n"
  10773. "X-Custom: a%0D%0AInjected: b\r\n"
  10774. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10775. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10776. "X-Unicode: %E3%81%82\r\n"
  10777. "X-IIS: %u00E9\r\n"
  10778. "Connection: close\r\n"
  10779. "\r\n";
  10780. std::string res;
  10781. ASSERT_TRUE(send_request(5, req, &res));
  10782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10783. // Every value must be returned verbatim (wire form), with no decoding.
  10784. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10785. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10786. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10787. EXPECT_EQ("%E3%81%82", x_unicode);
  10788. EXPECT_EQ("%u00E9", x_iis);
  10789. }
  10790. // Applications that previously relied on automatic percent-decoding can
  10791. // reproduce the old behavior by explicitly calling decode_path_component()
  10792. // or, for RFC 3986 conformance, decode_uri_component().
  10793. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10794. Server svr;
  10795. std::string decoded;
  10796. svr.Get("/check", [&](const Request &req, Response &res) {
  10797. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10798. res.set_content("ok", "text/plain");
  10799. });
  10800. thread t = thread([&] { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. t.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. const std::string req = "GET /check HTTP/1.1\r\n"
  10808. "Host: localhost\r\n"
  10809. "X-Custom: hello%20world\r\n"
  10810. "Connection: close\r\n"
  10811. "\r\n";
  10812. std::string res;
  10813. ASSERT_TRUE(send_request(5, req, &res));
  10814. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10815. EXPECT_EQ("hello world", decoded);
  10816. }
  10817. // Regression test for #2033. Browsers send Referer values that include
  10818. // percent-encoded characters such as %0A inside the URL. Decoding the
  10819. // header value would either trip the post-decode CR/LF/NUL guard (the
  10820. // original bug, returning 400) or, after that guard was relaxed, silently
  10821. // store a literal LF — both unacceptable. The wire form must round-trip.
  10822. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10823. Server svr;
  10824. std::string referer;
  10825. svr.Get("/check", [&](const Request &req, Response &res) {
  10826. referer = req.get_header_value("Referer");
  10827. res.set_content("ok", "text/plain");
  10828. });
  10829. thread t = thread([&] { svr.listen(HOST, PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. t.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. const std::string req = "GET /check HTTP/1.1\r\n"
  10837. "Host: localhost\r\n"
  10838. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10839. "Connection: close\r\n"
  10840. "\r\n";
  10841. std::string res;
  10842. ASSERT_TRUE(send_request(5, req, &res));
  10843. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10844. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10845. }
  10846. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10847. Server svr;
  10848. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10849. res.set_header("Cache-Control", "no-cache");
  10850. res.set_chunked_content_provider(
  10851. "text/event-stream", [](size_t offset, DataSink &sink) {
  10852. std::string s = "data:";
  10853. s += std::to_string(offset);
  10854. s += "\n\n";
  10855. auto ret = sink.write(s.data(), s.size());
  10856. EXPECT_TRUE(ret);
  10857. std::this_thread::sleep_for(std::chrono::seconds(1));
  10858. return true;
  10859. });
  10860. });
  10861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10862. svr.wait_until_ready();
  10863. Client client(HOST, PORT);
  10864. const Headers headers = {{"Accept", "text/event-stream"}};
  10865. auto get_thread = std::thread([&client, &headers]() {
  10866. auto res = client.Get(
  10867. "/events", headers,
  10868. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10869. });
  10870. auto se = detail::scope_exit([&] {
  10871. svr.stop();
  10872. get_thread.join();
  10873. listen_thread.join();
  10874. ASSERT_FALSE(svr.is_running());
  10875. });
  10876. // Give GET time to get a few messages.
  10877. std::this_thread::sleep_for(std::chrono::seconds(2));
  10878. }
  10879. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10880. httplib::Server svr;
  10881. svr.Post("/hi",
  10882. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10883. res.status = StatusCode::OK_200;
  10884. });
  10885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10886. svr.wait_until_ready();
  10887. Client cli(HOST, PORT);
  10888. auto res = cli.Post("/hi", "data", "text/plain");
  10889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10890. EXPECT_EQ(StatusCode::OK_200, res->status);
  10891. svr.stop();
  10892. thread.join();
  10893. ASSERT_FALSE(svr.is_running());
  10894. res = cli.Post("/hi", "data", "text/plain");
  10895. ASSERT_FALSE(res);
  10896. }
  10897. TEST(ServerStopTest, ListenFailure) {
  10898. Server svr;
  10899. auto t = thread([&]() {
  10900. auto ret = svr.listen("????", PORT);
  10901. EXPECT_FALSE(ret);
  10902. });
  10903. svr.wait_until_ready();
  10904. svr.stop();
  10905. t.join();
  10906. }
  10907. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10908. TEST(ServerStopTest, Decommision) {
  10909. Server svr;
  10910. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10911. for (int i = 0; i < 4; i++) {
  10912. auto is_even = !(i % 2);
  10913. std::thread t{[&] {
  10914. try {
  10915. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10916. if (is_even) {
  10917. throw std::runtime_error("Some thing that happens to go wrong.");
  10918. }
  10919. svr.listen(HOST, PORT);
  10920. } catch (...) { svr.decommission(); }
  10921. }};
  10922. svr.wait_until_ready();
  10923. // Server is up
  10924. {
  10925. Client cli(HOST, PORT);
  10926. auto res = cli.Get("/hi");
  10927. if (is_even) {
  10928. EXPECT_FALSE(res);
  10929. } else {
  10930. EXPECT_TRUE(res);
  10931. EXPECT_EQ("hi...", res->body);
  10932. }
  10933. }
  10934. svr.stop();
  10935. t.join();
  10936. // Server is down...
  10937. {
  10938. Client cli(HOST, PORT);
  10939. auto res = cli.Get("/hi");
  10940. EXPECT_FALSE(res);
  10941. }
  10942. }
  10943. }
  10944. #endif
  10945. // Helper function for string body upload progress tests
  10946. template <typename SetupHandler, typename ClientCall>
  10947. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10948. ClientCall &&client_call,
  10949. const string &body) {
  10950. Server svr;
  10951. setup_handler(svr);
  10952. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10953. auto se = detail::scope_exit([&] {
  10954. svr.stop();
  10955. t.join();
  10956. });
  10957. svr.wait_until_ready();
  10958. Client cli(HOST, PORT);
  10959. vector<uint64_t> progress_values;
  10960. bool progress_called = false;
  10961. auto res =
  10962. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10963. progress_values.push_back(current);
  10964. progress_called = true;
  10965. return true;
  10966. });
  10967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10968. EXPECT_EQ(200, res->status);
  10969. EXPECT_TRUE(progress_called);
  10970. }
  10971. TEST(UploadProgressTest, PostStringBodyBasic) {
  10972. TestStringBodyUploadProgress(
  10973. [](Server &svr) {
  10974. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10975. res.set_content("received", "text/plain");
  10976. });
  10977. },
  10978. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10979. return cli.Post("/test", body, "text/plain", progress_callback);
  10980. },
  10981. "test data for upload progress");
  10982. }
  10983. TEST(UploadProgressTest, PutStringBodyBasic) {
  10984. TestStringBodyUploadProgress(
  10985. [](Server &svr) {
  10986. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10987. res.set_content("put received", "text/plain");
  10988. });
  10989. },
  10990. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10991. return cli.Put("/test", body, "text/plain", progress_callback);
  10992. },
  10993. "put test data for upload progress");
  10994. }
  10995. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10996. TestStringBodyUploadProgress(
  10997. [](Server &svr) {
  10998. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10999. res.set_content("patch received", "text/plain");
  11000. });
  11001. },
  11002. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11003. return cli.Patch("/test", body, "text/plain", progress_callback);
  11004. },
  11005. "patch test data for upload progress");
  11006. }
  11007. // Helper function for content provider upload progress tests
  11008. template <typename SetupHandler, typename ClientCall>
  11009. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11010. ClientCall &&client_call) {
  11011. Server svr;
  11012. setup_handler(svr);
  11013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11014. auto se = detail::scope_exit([&] {
  11015. svr.stop();
  11016. t.join();
  11017. });
  11018. svr.wait_until_ready();
  11019. Client cli(HOST, PORT);
  11020. vector<uint64_t> progress_values;
  11021. auto res =
  11022. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11023. progress_values.push_back(current);
  11024. return true;
  11025. });
  11026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11027. EXPECT_EQ(200, res->status);
  11028. EXPECT_FALSE(progress_values.empty());
  11029. }
  11030. TEST(UploadProgressTest, PostContentProviderProgress) {
  11031. TestContentProviderUploadProgress(
  11032. [](Server &svr) {
  11033. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("provider received", "text/plain");
  11035. });
  11036. },
  11037. [](Client &cli, UploadProgress progress_callback) {
  11038. return cli.Post(
  11039. "/test", 9,
  11040. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11041. sink.os << "test data";
  11042. return true;
  11043. },
  11044. "text/plain", progress_callback);
  11045. });
  11046. }
  11047. // Helper function for multipart upload progress tests
  11048. template <typename SetupHandler, typename ClientCall>
  11049. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11050. ClientCall &&client_call,
  11051. const string &endpoint) {
  11052. Server svr;
  11053. setup_handler(svr);
  11054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11055. auto se = detail::scope_exit([&] {
  11056. svr.stop();
  11057. t.join();
  11058. });
  11059. svr.wait_until_ready();
  11060. Client cli(HOST, PORT);
  11061. vector<uint64_t> progress_values;
  11062. UploadFormDataItems items = {
  11063. {"field1", "value1", "", ""},
  11064. {"field2", "longer value for progress tracking test", "", ""},
  11065. {"file1", "file content data for upload progress", "test.txt",
  11066. "text/plain"}};
  11067. auto res = client_call(cli, endpoint, items,
  11068. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11069. progress_values.push_back(current);
  11070. return true;
  11071. });
  11072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11073. EXPECT_EQ(200, res->status);
  11074. EXPECT_FALSE(progress_values.empty());
  11075. }
  11076. TEST(UploadProgressTest, PostMultipartProgress) {
  11077. TestMultipartUploadProgress(
  11078. [](Server &svr) {
  11079. svr.Post("/multipart", [](const Request &req, Response &res) {
  11080. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11081. res.set_content("multipart received", "text/plain");
  11082. });
  11083. },
  11084. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11085. UploadProgress progress_callback) {
  11086. return cli.Post(endpoint, items, progress_callback);
  11087. },
  11088. "/multipart");
  11089. }
  11090. // Helper function for basic download progress tests
  11091. template <typename SetupHandler, typename ClientCall>
  11092. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11093. ClientCall &&client_call, const string &endpoint,
  11094. size_t expected_content_size) {
  11095. Server svr;
  11096. setup_handler(svr);
  11097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11098. auto se = detail::scope_exit([&] {
  11099. svr.stop();
  11100. t.join();
  11101. });
  11102. svr.wait_until_ready();
  11103. Client cli(HOST, PORT);
  11104. vector<uint64_t> progress_values;
  11105. auto res = client_call(cli, endpoint,
  11106. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11107. progress_values.push_back(current);
  11108. return true;
  11109. });
  11110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11111. EXPECT_EQ(200, res->status);
  11112. EXPECT_FALSE(progress_values.empty());
  11113. EXPECT_EQ(expected_content_size, res->body.size());
  11114. }
  11115. TEST(DownloadProgressTest, GetBasic) {
  11116. TestBasicDownloadProgress(
  11117. [](Server &svr) {
  11118. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11119. string content(1000, 'D');
  11120. res.set_content(content, "text/plain");
  11121. });
  11122. },
  11123. [](Client &cli, const string &endpoint,
  11124. DownloadProgress progress_callback) {
  11125. return cli.Get(endpoint, progress_callback);
  11126. },
  11127. "/download", 1000u);
  11128. }
  11129. // Helper function for content receiver download progress tests
  11130. template <typename SetupHandler, typename ClientCall>
  11131. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11132. ClientCall &&client_call,
  11133. const string &endpoint,
  11134. size_t expected_content_size) {
  11135. Server svr;
  11136. setup_handler(svr);
  11137. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11138. auto se = detail::scope_exit([&] {
  11139. svr.stop();
  11140. t.join();
  11141. });
  11142. svr.wait_until_ready();
  11143. Client cli(HOST, PORT);
  11144. vector<uint64_t> progress_values;
  11145. string received_body;
  11146. auto res = client_call(
  11147. cli, endpoint,
  11148. [&](const char *data, size_t data_length) -> bool {
  11149. received_body.append(data, data_length);
  11150. return true;
  11151. },
  11152. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11153. progress_values.push_back(current);
  11154. return true;
  11155. });
  11156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11157. EXPECT_EQ(200, res->status);
  11158. EXPECT_FALSE(progress_values.empty());
  11159. EXPECT_EQ(expected_content_size, received_body.size());
  11160. EXPECT_TRUE(res->body.empty());
  11161. }
  11162. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11163. TestContentReceiverDownloadProgress(
  11164. [](Server &svr) {
  11165. svr.Get("/download-receiver",
  11166. [](const Request & /*req*/, Response &res) {
  11167. string content(2000, 'R');
  11168. res.set_content(content, "text/plain");
  11169. });
  11170. },
  11171. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11172. DownloadProgress progress_callback) {
  11173. return cli.Get(endpoint, content_receiver, progress_callback);
  11174. },
  11175. "/download-receiver", 2000u);
  11176. }
  11177. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11178. // A provider reaching a pass with nothing to hand over - an empty buffer
  11179. // popped off a queue, say - must not be taken to mean the body is finished.
  11180. // It used to end the loop with the terminating chunk unwritten while the
  11181. // server still considered the response complete, so the peer waited for an
  11182. // end that never arrived.
  11183. Server svr;
  11184. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11185. auto step = std::make_shared<int>(0);
  11186. res.set_chunked_content_provider("text/plain",
  11187. [step](size_t /*offset*/, DataSink &sink) {
  11188. switch ((*step)++) {
  11189. case 0: sink.write("", 0); break;
  11190. case 1: sink.write("hello", 5); break;
  11191. default: sink.done(); break;
  11192. }
  11193. return true;
  11194. });
  11195. });
  11196. auto port = svr.bind_to_any_port(HOST);
  11197. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11198. auto listen_se = detail::scope_exit([&] {
  11199. svr.stop();
  11200. listen_thread.join();
  11201. ASSERT_FALSE(svr.is_running());
  11202. });
  11203. svr.wait_until_ready();
  11204. Client cli(HOST, port);
  11205. // Without the fix the body is never terminated, so bound the wait rather
  11206. // than letting the test hang on the default read timeout.
  11207. cli.set_read_timeout(5, 0);
  11208. auto res = cli.Get("/stream");
  11209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11210. EXPECT_EQ(StatusCode::OK_200, res->status);
  11211. EXPECT_EQ("hello", res->body);
  11212. }
  11213. TEST(StreamingTest, NoContentLengthStreaming) {
  11214. Server svr;
  11215. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11216. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11217. if (offset < 6) {
  11218. sink.os << (offset < 3 ? "a" : "b");
  11219. } else {
  11220. sink.done();
  11221. }
  11222. return true;
  11223. });
  11224. });
  11225. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11226. auto listen_se = detail::scope_exit([&] {
  11227. svr.stop();
  11228. listen_thread.join();
  11229. ASSERT_FALSE(svr.is_running());
  11230. });
  11231. svr.wait_until_ready();
  11232. Client client(HOST, PORT);
  11233. auto get_thread = std::thread([&client]() {
  11234. std::string s;
  11235. auto res =
  11236. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11237. s += std::string(data, len);
  11238. return true;
  11239. });
  11240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11241. EXPECT_EQ(StatusCode::OK_200, res->status);
  11242. EXPECT_EQ("aaabbb", s);
  11243. });
  11244. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11245. // Give GET time to get a few messages.
  11246. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11247. }
  11248. TEST(MountTest, Unmount) {
  11249. Server svr;
  11250. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11251. auto se = detail::scope_exit([&] {
  11252. svr.stop();
  11253. listen_thread.join();
  11254. ASSERT_FALSE(svr.is_running());
  11255. });
  11256. svr.wait_until_ready();
  11257. Client cli("localhost", PORT);
  11258. svr.set_mount_point("/mount2", "./www2");
  11259. auto res = cli.Get("/");
  11260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11262. res = cli.Get("/mount2/dir/test.html");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::OK_200, res->status);
  11265. svr.set_mount_point("/", "./www");
  11266. res = cli.Get("/dir/");
  11267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. svr.remove_mount_point("/");
  11270. res = cli.Get("/dir/");
  11271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11273. svr.remove_mount_point("/mount2");
  11274. res = cli.Get("/mount2/dir/test.html");
  11275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11277. }
  11278. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11279. Server svr;
  11280. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11281. svr.Get("/api/hello", [](const Request &, Response &res) {
  11282. res.set_content("api", "text/plain");
  11283. });
  11284. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11285. auto se = detail::scope_exit([&] {
  11286. svr.stop();
  11287. listen_thread.join();
  11288. ASSERT_FALSE(svr.is_running());
  11289. });
  11290. svr.wait_until_ready();
  11291. Client cli(HOST, PORT);
  11292. auto res = cli.Get("/dir/test.html");
  11293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11294. EXPECT_EQ(StatusCode::OK_200, res->status);
  11295. res = cli.Get("/api/hello");
  11296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11297. EXPECT_EQ(StatusCode::OK_200, res->status);
  11298. EXPECT_EQ("api", res->body);
  11299. }
  11300. TEST(MountTest, PathSegmentBoundary) {
  11301. Server svr;
  11302. svr.set_mount_point("/mount2", "./www2");
  11303. svr.set_mount_point("/", "./www");
  11304. auto port = svr.bind_to_any_port(HOST);
  11305. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11306. auto se = detail::scope_exit([&] {
  11307. svr.stop();
  11308. listen_thread.join();
  11309. ASSERT_FALSE(svr.is_running());
  11310. });
  11311. svr.wait_until_ready();
  11312. Client cli(HOST, port);
  11313. auto res = cli.Get("/mount2/dir/test.html");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::OK_200, res->status);
  11316. // "/mount2" must not match part-way through a path segment.
  11317. res = cli.Get("/mount2dir/test.html");
  11318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11320. // A mount point ending in '/' keeps matching every path below it.
  11321. res = cli.Get("/dir/test.html");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. EXPECT_EQ(StatusCode::OK_200, res->status);
  11324. }
  11325. TEST(MountTest, Redicect) {
  11326. Server svr;
  11327. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. listen_thread.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. });
  11333. svr.set_mount_point("/", "./www");
  11334. svr.wait_until_ready();
  11335. Client cli("localhost", PORT);
  11336. auto res = cli.Get("/dir/");
  11337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11338. EXPECT_EQ(StatusCode::OK_200, res->status);
  11339. res = cli.Get("/dir");
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11342. res = cli.Get("/file");
  11343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11344. EXPECT_EQ(StatusCode::OK_200, res->status);
  11345. res = cli.Get("/file/");
  11346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11348. cli.set_follow_location(true);
  11349. res = cli.Get("/dir");
  11350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11351. EXPECT_EQ(StatusCode::OK_200, res->status);
  11352. }
  11353. TEST(MountTest, MultibytesPathName) {
  11354. Server svr;
  11355. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11356. auto se = detail::scope_exit([&] {
  11357. svr.stop();
  11358. listen_thread.join();
  11359. ASSERT_FALSE(svr.is_running());
  11360. });
  11361. svr.set_mount_point("/", "./www");
  11362. svr.wait_until_ready();
  11363. Client cli("localhost", PORT);
  11364. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. EXPECT_EQ(StatusCode::OK_200, res->status);
  11367. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11368. }
  11369. // A mount point serves no path with an empty segment or one ending in '.' or
  11370. // a space, so a guard in the pre-routing handler sees the path of every file
  11371. // that is served
  11372. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11373. Server svr;
  11374. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11375. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11376. if (req.path == "/dir/test.html") {
  11377. res.status = StatusCode::Unauthorized_401;
  11378. return Server::HandlerResponse::Handled;
  11379. }
  11380. return Server::HandlerResponse::Unhandled;
  11381. });
  11382. auto port = svr.bind_to_any_port(HOST);
  11383. ASSERT_LT(0, port);
  11384. thread t = thread([&] { svr.listen_after_bind(); });
  11385. auto se = detail::scope_exit([&] {
  11386. svr.stop();
  11387. t.join();
  11388. ASSERT_FALSE(svr.is_running());
  11389. });
  11390. svr.wait_until_ready();
  11391. Client cli(HOST, port);
  11392. for (auto path :
  11393. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11394. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11395. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11396. "/dir/test.html%3A%3A$DATA"}) {
  11397. SCOPED_TRACE(path);
  11398. auto res = cli.Get(path);
  11399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11401. }
  11402. }
  11403. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11404. Server svr;
  11405. svr.set_mount_point("/", "./www");
  11406. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11407. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11408. auto port = svr.bind_to_any_port(HOST);
  11409. ASSERT_GT(port, 0);
  11410. thread t = thread([&] { svr.listen_after_bind(); });
  11411. auto se = detail::scope_exit([&] {
  11412. svr.stop();
  11413. t.join();
  11414. ASSERT_FALSE(svr.is_running());
  11415. });
  11416. svr.wait_until_ready();
  11417. Client cli(HOST, port);
  11418. auto res = cli.Get("/dir/test.abcde");
  11419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11420. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11421. res = cli.Get("/dir/test.html");
  11422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11423. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11424. }
  11425. #ifdef _WIN32
  11426. // Issue #2435: mmap::open() must succeed even when another handle holds
  11427. // the file open for writing (e.g. an active log file).
  11428. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11429. const char *path = "mmap_concurrent_writer_test.txt";
  11430. const char *content = "hello";
  11431. {
  11432. std::ofstream f(path, std::ios::binary);
  11433. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11434. }
  11435. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11436. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11437. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11438. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11439. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11440. detail::mmap m(path);
  11441. ASSERT_TRUE(m.is_open());
  11442. EXPECT_EQ(strlen(content), m.size());
  11443. char buf[8];
  11444. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11445. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11446. }
  11447. #endif
  11448. #ifndef _WIN32
  11449. // A directory or a device has no size to serve.
  11450. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11451. const char *path = "./mmap_not_regular_test_dir";
  11452. ASSERT_EQ(0, ::mkdir(path, 0755));
  11453. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11454. for (auto p : {path, "/dev/null"}) {
  11455. detail::mmap m(p);
  11456. EXPECT_FALSE(m.is_open()) << p;
  11457. EXPECT_EQ(0U, m.size()) << p;
  11458. }
  11459. Server svr;
  11460. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11461. res.set_file_content("/dev/null");
  11462. });
  11463. auto port = svr.bind_to_any_port(HOST);
  11464. thread t = thread([&] { svr.listen_after_bind(); });
  11465. auto se = detail::scope_exit([&] {
  11466. svr.stop();
  11467. t.join();
  11468. });
  11469. svr.wait_until_ready();
  11470. auto res = Client(HOST, port).Get("/null");
  11471. ASSERT_TRUE(res);
  11472. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11473. }
  11474. #endif
  11475. #ifdef __linux__
  11476. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11477. TEST(MmapTest, FileIsNotMapped) {
  11478. const char *path = "mmap_not_mapped_test.txt";
  11479. {
  11480. std::ofstream f(path, std::ios::binary);
  11481. f << "hello";
  11482. }
  11483. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11484. detail::mmap m(path);
  11485. ASSERT_TRUE(m.is_open());
  11486. std::ifstream maps("/proc/self/maps");
  11487. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11488. std::istreambuf_iterator<char>());
  11489. EXPECT_EQ(std::string::npos, mappings.find(path));
  11490. }
  11491. #endif
  11492. TEST(KeepAliveTest, ReadTimeout) {
  11493. Server svr;
  11494. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11495. std::this_thread::sleep_for(std::chrono::seconds(2));
  11496. res.set_content("a", "text/plain");
  11497. });
  11498. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11499. res.set_content("b", "text/plain");
  11500. });
  11501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11502. auto se = detail::scope_exit([&] {
  11503. svr.stop();
  11504. listen_thread.join();
  11505. ASSERT_FALSE(svr.is_running());
  11506. });
  11507. svr.wait_until_ready();
  11508. Client cli("localhost", PORT);
  11509. cli.set_keep_alive(true);
  11510. cli.set_read_timeout(std::chrono::seconds(1));
  11511. auto resa = cli.Get("/a");
  11512. ASSERT_FALSE(resa);
  11513. EXPECT_EQ(Error::Read, resa.error());
  11514. auto resb = cli.Get("/b");
  11515. ASSERT_TRUE(resb);
  11516. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11517. EXPECT_EQ("b", resb->body);
  11518. }
  11519. TEST(KeepAliveTest, MaxCount) {
  11520. size_t keep_alive_max_count = 3;
  11521. Server svr;
  11522. svr.set_keep_alive_max_count(keep_alive_max_count);
  11523. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11524. res.set_content("Hello World!", "text/plain");
  11525. });
  11526. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11527. auto se = detail::scope_exit([&] {
  11528. svr.stop();
  11529. listen_thread.join();
  11530. ASSERT_FALSE(svr.is_running());
  11531. });
  11532. svr.wait_until_ready();
  11533. Client cli(HOST, PORT);
  11534. cli.set_keep_alive(true);
  11535. for (size_t i = 0; i < 5; i++) {
  11536. auto result = cli.Get("/hi");
  11537. ASSERT_TRUE(result);
  11538. EXPECT_EQ(StatusCode::OK_200, result->status);
  11539. if (i == keep_alive_max_count - 1) {
  11540. EXPECT_EQ("close", result->get_header_value("Connection"));
  11541. } else {
  11542. EXPECT_FALSE(result->has_header("Connection"));
  11543. }
  11544. }
  11545. }
  11546. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11547. // can pull the next one into the server's buffer. The server must serve it
  11548. // without waiting for the socket to become readable again. The keep-alive
  11549. // timeout outlasts the client's read timeout, so a request left waiting for it
  11550. // shows up as a missing response.
  11551. static void serve_pipelining_routes(Server &svr,
  11552. const std::function<void(int)> &client) {
  11553. svr.set_keep_alive_timeout(5);
  11554. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11555. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11556. });
  11557. svr.Post("/echo", [](const Request &req, Response &res) {
  11558. res.set_content("echo " + req.body, "text/plain");
  11559. });
  11560. auto port = svr.bind_to_any_port(HOST);
  11561. thread t = thread([&] { svr.listen_after_bind(); });
  11562. auto se = detail::scope_exit([&] {
  11563. svr.stop();
  11564. t.join();
  11565. });
  11566. svr.wait_until_ready();
  11567. client(port);
  11568. }
  11569. static std::string
  11570. send_pipelined_requests(const std::vector<std::string> &parts) {
  11571. Server svr;
  11572. std::string res;
  11573. serve_pipelining_routes(svr, [&](int port) {
  11574. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11575. });
  11576. return res;
  11577. }
  11578. static void expect_in_order(const std::string &res,
  11579. const std::vector<std::string> &bodies) {
  11580. size_t pos = 0;
  11581. for (const auto &body : bodies) {
  11582. pos = res.find(body, pos);
  11583. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11584. pos += body.size();
  11585. }
  11586. }
  11587. TEST(KeepAliveTest, PipelinedRequests) {
  11588. auto res = send_pipelined_requests(
  11589. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11590. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11591. "Content-Length: 4\r\n\r\nbody"
  11592. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11593. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11594. }
  11595. // The second request starts in the server's buffer and ends on the socket.
  11596. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11597. auto res =
  11598. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11599. "GET /hi/2 HTTP/1.1\r\nHo",
  11600. "st: localhost\r\nConnection: close\r\n\r\n"});
  11601. expect_in_order(res, {"hi 1", "hi 2"});
  11602. }
  11603. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11604. // CRLF after a body does not turn into a 400 for the next request.
  11605. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11606. auto res = send_pipelined_requests(
  11607. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11608. "Content-Length: 4\r\n\r\nbody\r\n"
  11609. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11610. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11611. expect_in_order(res, {"echo body", "hi 2"});
  11612. }
  11613. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11614. // must not be served as the next request.
  11615. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11616. auto res = send_pipelined_requests(
  11617. {"INVALID REQUEST LINE\r\n\r\n"
  11618. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11619. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11620. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11621. }
  11622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11623. // Over TLS, the next request is held by the TLS library as already decrypted
  11624. // data rather than on the socket.
  11625. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11627. std::string res;
  11628. serve_pipelining_routes(svr, [&](int port) {
  11629. // One part, so all three requests arrive in one TLS record
  11630. EXPECT_TRUE(send_ssl_request_in_parts(
  11631. 2,
  11632. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11633. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11634. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11635. &res, port));
  11636. });
  11637. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11638. }
  11639. #endif
  11640. TEST(KeepAliveTest, Issue1041) {
  11641. Server svr;
  11642. svr.set_keep_alive_timeout(3);
  11643. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11644. res.set_content("Hello World!", "text/plain");
  11645. });
  11646. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11647. auto se = detail::scope_exit([&] {
  11648. svr.stop();
  11649. listen_thread.join();
  11650. ASSERT_FALSE(svr.is_running());
  11651. });
  11652. svr.wait_until_ready();
  11653. Client cli(HOST, PORT);
  11654. cli.set_keep_alive(true);
  11655. auto result = cli.Get("/hi");
  11656. ASSERT_TRUE(result);
  11657. EXPECT_EQ(StatusCode::OK_200, result->status);
  11658. std::this_thread::sleep_for(std::chrono::seconds(5));
  11659. result = cli.Get("/hi");
  11660. ASSERT_TRUE(result);
  11661. EXPECT_EQ(StatusCode::OK_200, result->status);
  11662. }
  11663. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11664. Server svr;
  11665. svr.set_keep_alive_max_count(0);
  11666. std::set<int> remote_ports;
  11667. svr.Get("/hi", [&](const Request &req, Response &res) {
  11668. remote_ports.insert(req.remote_port);
  11669. res.set_content("hi", "text/plain");
  11670. });
  11671. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11672. auto se = detail::scope_exit([&] {
  11673. svr.stop();
  11674. listen_thread.join();
  11675. ASSERT_FALSE(svr.is_running());
  11676. });
  11677. svr.wait_until_ready();
  11678. Client cli(HOST, PORT);
  11679. cli.set_keep_alive(true);
  11680. for (int i = 0; i < 3; i++) {
  11681. auto res = cli.Get("/hi");
  11682. ASSERT_TRUE(res);
  11683. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11684. }
  11685. // All three over one connection
  11686. EXPECT_EQ(1u, remote_ports.size());
  11687. }
  11688. // Forward declaration (see the base64_encode note).
  11689. namespace httplib {
  11690. namespace detail {
  11691. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11692. } // namespace detail
  11693. } // namespace httplib
  11694. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11695. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11696. #ifndef _WIN32
  11697. signal(SIGPIPE, SIG_IGN);
  11698. #endif
  11699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11700. ASSERT_NE(INVALID_SOCKET, srv);
  11701. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11702. default_socket_options(srv);
  11703. sockaddr_in addr{};
  11704. addr.sin_family = AF_INET;
  11705. addr.sin_port = 0;
  11706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11707. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11708. ASSERT_EQ(0, ::listen(srv, 2));
  11709. socklen_t addr_len = sizeof(addr);
  11710. ASSERT_EQ(0,
  11711. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11712. auto port = ntohs(addr.sin_port);
  11713. struct Peer {
  11714. socket_t sock = INVALID_SOCKET;
  11715. #ifdef CPPHTTPLIB_SSL_ENABLED
  11716. tls::session_t session = nullptr;
  11717. #endif
  11718. };
  11719. #ifdef CPPHTTPLIB_SSL_ENABLED
  11720. tls::ctx_t ctx = nullptr;
  11721. if (use_tls) {
  11722. ctx = tls::create_server_context();
  11723. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11724. nullptr);
  11725. }
  11726. auto ctx_se = detail::scope_exit([&] {
  11727. if (ctx) { tls::free_context(ctx); }
  11728. });
  11729. #endif
  11730. auto close_peer = [](Peer &peer) {
  11731. #ifdef CPPHTTPLIB_SSL_ENABLED
  11732. if (peer.session) { tls::free_session(peer.session); }
  11733. #endif
  11734. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11735. };
  11736. auto accept_peer = [&]() {
  11737. Peer peer;
  11738. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11739. peer.sock = ::accept(srv, nullptr, nullptr);
  11740. if (peer.sock == INVALID_SOCKET) { return peer; }
  11741. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11742. #ifdef CPPHTTPLIB_SSL_ENABLED
  11743. if (use_tls) {
  11744. peer.session = tls::create_session(ctx, peer.sock);
  11745. tls::TlsError err;
  11746. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11747. nullptr)) {
  11748. close_peer(peer);
  11749. return Peer();
  11750. }
  11751. }
  11752. #endif
  11753. return peer;
  11754. };
  11755. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11756. #ifdef CPPHTTPLIB_SSL_ENABLED
  11757. tls::TlsError err;
  11758. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11759. #endif
  11760. return detail::read_socket(peer.sock, buf, len, 0);
  11761. };
  11762. auto read_head = [&](const Peer &peer) {
  11763. std::string head;
  11764. char buf[1024];
  11765. while (head.find("\r\n\r\n") == std::string::npos) {
  11766. auto n = read_some(peer, buf, sizeof(buf));
  11767. if (n <= 0) { break; }
  11768. head.append(buf, static_cast<size_t>(n));
  11769. }
  11770. };
  11771. auto send_text = [](const Peer &peer, const std::string &text) {
  11772. #ifdef CPPHTTPLIB_SSL_ENABLED
  11773. tls::TlsError err;
  11774. if (peer.session) {
  11775. tls::write(peer.session, text.data(), text.size(), err);
  11776. return;
  11777. }
  11778. #endif
  11779. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11780. };
  11781. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11782. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11783. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11784. // Sent once the first response is read, so that it lands on an idle socket
  11785. std::promise<void> first_response_read;
  11786. auto first_response_read_future = first_response_read.get_future();
  11787. auto server_thread = std::thread([&] {
  11788. auto peer1 = accept_peer();
  11789. if (peer1.sock == INVALID_SOCKET) { return; }
  11790. read_head(peer1);
  11791. if (same_write) {
  11792. send_text(peer1, first + stray);
  11793. } else {
  11794. send_text(peer1, first);
  11795. first_response_read_future.wait_for(std::chrono::seconds(5));
  11796. send_text(peer1, stray);
  11797. }
  11798. // peer1 stays open, so only the unread data can tell the client
  11799. auto peer2 = accept_peer();
  11800. if (peer2.sock != INVALID_SOCKET) {
  11801. read_head(peer2);
  11802. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11803. "Connection: close\r\n\r\nsecond");
  11804. close_peer(peer2);
  11805. }
  11806. close_peer(peer1);
  11807. });
  11808. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11809. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11810. std::to_string(port));
  11811. #ifdef CPPHTTPLIB_SSL_ENABLED
  11812. cli.enable_server_certificate_verification(false);
  11813. #endif
  11814. cli.set_keep_alive(true);
  11815. cli.set_read_timeout(5, 0);
  11816. auto res = cli.Get("/1");
  11817. first_response_read.set_value();
  11818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11819. EXPECT_EQ("first", res->body);
  11820. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11821. res = cli.Get("/2");
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. EXPECT_EQ(StatusCode::OK_200, res->status);
  11824. EXPECT_EQ("second", res->body);
  11825. }
  11826. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11827. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11828. }
  11829. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11830. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11831. }
  11832. #ifdef CPPHTTPLIB_SSL_ENABLED
  11833. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11834. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11835. }
  11836. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11837. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11838. }
  11839. #endif
  11840. TEST(KeepAliveTest, Issue1959) {
  11841. Server svr;
  11842. svr.set_keep_alive_timeout(5);
  11843. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11844. res.set_content("a", "text/plain");
  11845. });
  11846. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11847. auto se = detail::scope_exit([&] {
  11848. if (!svr.is_running()) return;
  11849. svr.stop();
  11850. listen_thread.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. Client cli("localhost", PORT);
  11855. cli.set_keep_alive(true);
  11856. using namespace std::chrono;
  11857. auto start = steady_clock::now();
  11858. cli.Get("/a");
  11859. svr.stop();
  11860. listen_thread.join();
  11861. auto end = steady_clock::now();
  11862. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11863. EXPECT_LT(elapsed, 5000);
  11864. }
  11865. #ifdef CPPHTTPLIB_SSL_ENABLED
  11866. TEST(KeepAliveTest, SSLClientReconnection) {
  11867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11868. ASSERT_TRUE(svr.is_valid());
  11869. svr.set_keep_alive_timeout(1);
  11870. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11871. res.set_content("Hello World!", "text/plain");
  11872. });
  11873. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11874. auto se = detail::scope_exit([&] {
  11875. svr.stop();
  11876. listen_thread.join();
  11877. ASSERT_FALSE(svr.is_running());
  11878. });
  11879. svr.wait_until_ready();
  11880. SSLClient cli(HOST, PORT);
  11881. cli.enable_server_certificate_verification(false);
  11882. cli.set_keep_alive(true);
  11883. auto result = cli.Get("/hi");
  11884. ASSERT_TRUE(result);
  11885. EXPECT_EQ(StatusCode::OK_200, result->status);
  11886. result = cli.Get("/hi");
  11887. ASSERT_TRUE(result);
  11888. EXPECT_EQ(StatusCode::OK_200, result->status);
  11889. std::this_thread::sleep_for(std::chrono::seconds(2));
  11890. // Recoonect
  11891. result = cli.Get("/hi");
  11892. ASSERT_TRUE(result);
  11893. EXPECT_EQ(StatusCode::OK_200, result->status);
  11894. result = cli.Get("/hi");
  11895. ASSERT_TRUE(result);
  11896. EXPECT_EQ(StatusCode::OK_200, result->status);
  11897. }
  11898. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11900. ASSERT_TRUE(svr.is_valid());
  11901. svr.set_keep_alive_timeout(1);
  11902. std::string content = "reconnect";
  11903. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11904. res.set_content("Hello World!", "text/plain");
  11905. });
  11906. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11907. auto se = detail::scope_exit([&] {
  11908. svr.stop();
  11909. listen_thread.join();
  11910. ASSERT_FALSE(svr.is_running());
  11911. });
  11912. svr.wait_until_ready();
  11913. SSLClient cli(HOST, PORT);
  11914. cli.enable_server_certificate_verification(false);
  11915. cli.set_keep_alive(true);
  11916. auto result = cli.Post(
  11917. "/hi", content.size(),
  11918. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11919. sink.write(content.c_str(), content.size());
  11920. return true;
  11921. },
  11922. "text/plain");
  11923. ASSERT_TRUE(result);
  11924. EXPECT_EQ(200, result->status);
  11925. std::this_thread::sleep_for(std::chrono::seconds(2));
  11926. // Recoonect
  11927. result = cli.Post(
  11928. "/hi", content.size(),
  11929. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11930. sink.write(content.c_str(), content.size());
  11931. return true;
  11932. },
  11933. "text/plain");
  11934. ASSERT_TRUE(result);
  11935. EXPECT_EQ(200, result->status);
  11936. result = cli.Post(
  11937. "/hi", content.size(),
  11938. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11939. sink.write(content.c_str(), content.size());
  11940. return true;
  11941. },
  11942. "text/plain");
  11943. ASSERT_TRUE(result);
  11944. EXPECT_EQ(200, result->status);
  11945. }
  11946. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11947. using namespace httplib::tls;
  11948. {
  11949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11950. ASSERT_TRUE(svr.is_valid());
  11951. svr.Get("/sni", [&](const Request &req, Response &res) {
  11952. std::string expected = req.sni();
  11953. EXPECT_EQ(expected, req.get_param_value("expected"));
  11954. res.set_content("ok", "text/plain");
  11955. });
  11956. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11957. auto se = detail::scope_exit([&] {
  11958. svr.stop();
  11959. listen_thread.join();
  11960. ASSERT_FALSE(svr.is_running());
  11961. });
  11962. svr.wait_until_ready();
  11963. {
  11964. SSLClient cli("localhost", PORT);
  11965. cli.enable_server_certificate_verification(false);
  11966. auto res = cli.Get("/sni?expected=localhost");
  11967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11968. }
  11969. {
  11970. SSLClient cli("::1", PORT);
  11971. cli.enable_server_certificate_verification(false);
  11972. auto res = cli.Get("/sni?expected=");
  11973. // NOTE: This may fail if the server is listening on IPv4 only
  11974. // (e.g., when localhost resolves to 127.0.0.1 only)
  11975. if (res) {
  11976. EXPECT_EQ(StatusCode::OK_200, res->status);
  11977. } else {
  11978. EXPECT_EQ(Error::Connection, res.error());
  11979. }
  11980. }
  11981. }
  11982. }
  11983. // The SNI of a failed handshake does not reach the next connection that the
  11984. // same worker thread serves
  11985. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11987. ASSERT_TRUE(svr.is_valid());
  11988. svr.new_task_queue = [] { return new ThreadPool(1); };
  11989. svr.Get("/sni", [](const Request &req, Response &res) {
  11990. res.set_content(req.sni(), "text/plain");
  11991. });
  11992. auto port = svr.bind_to_any_port("127.0.0.1");
  11993. ASSERT_LT(0, port);
  11994. thread t = thread([&] { svr.listen_after_bind(); });
  11995. auto se = detail::scope_exit([&] {
  11996. svr.stop();
  11997. t.join();
  11998. ASSERT_FALSE(svr.is_running());
  11999. });
  12000. svr.wait_until_ready();
  12001. {
  12002. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12003. SSLClient cli("localhost", port);
  12004. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12005. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12006. auto res = cli.Get("/sni");
  12007. ASSERT_FALSE(res);
  12008. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12009. }
  12010. // An IP host sends no SNI (RFC 6066)
  12011. SSLClient cli("127.0.0.1", port);
  12012. cli.enable_server_certificate_verification(false);
  12013. auto res = cli.Get("/sni");
  12014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12015. EXPECT_EQ("", res->body);
  12016. }
  12017. #endif
  12018. TEST(ClientProblemDetectionTest, ContentProvider) {
  12019. Server svr;
  12020. size_t content_length = 1024 * 1024;
  12021. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12022. res.set_content_provider(
  12023. content_length, "text/plain",
  12024. [&](size_t offset, size_t length, DataSink &sink) {
  12025. auto out_len = std::min(length, static_cast<size_t>(1024));
  12026. std::string out(out_len, '@');
  12027. sink.write(out.data(), out_len);
  12028. return offset < 4096;
  12029. },
  12030. [](bool success) { ASSERT_FALSE(success); });
  12031. });
  12032. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12033. res.set_content_provider(
  12034. 0, "text/plain",
  12035. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12036. EXPECT_TRUE(false);
  12037. return true;
  12038. },
  12039. [](bool success) { ASSERT_FALSE(success); });
  12040. });
  12041. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. listen_thread.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. });
  12047. svr.wait_until_ready();
  12048. Client cli("localhost", PORT);
  12049. {
  12050. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12051. size_t /*data_length*/) { return false; });
  12052. ASSERT_FALSE(res);
  12053. }
  12054. {
  12055. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12056. size_t /*data_length*/) { return false; });
  12057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12058. }
  12059. }
  12060. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12061. // A provider that reports success without writing anything and without
  12062. // calling done() used to be handed the same offset and length again on every
  12063. // pass, so it spun for as long as the peer stayed connected.
  12064. Server svr;
  12065. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12066. res.set_content("ok", "text/plain");
  12067. });
  12068. auto port = svr.bind_to_any_port(HOST);
  12069. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12070. auto se = detail::scope_exit([&] {
  12071. svr.stop();
  12072. listen_thread.join();
  12073. ASSERT_FALSE(svr.is_running());
  12074. });
  12075. svr.wait_until_ready();
  12076. std::atomic<int> call_count{0};
  12077. Client cli(HOST, port);
  12078. auto res = cli.Post(
  12079. "/", 1024,
  12080. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12081. // Give up after enough passes to show the spin, so that losing the
  12082. // check below fails this test instead of hanging it.
  12083. return ++call_count < 100;
  12084. },
  12085. "text/plain");
  12086. ASSERT_FALSE(res);
  12087. EXPECT_EQ(Error::Write, res.error());
  12088. EXPECT_EQ(1, call_count.load());
  12089. }
  12090. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12091. // A writer only has to assign `write`. The other three used to be left as
  12092. // empty std::functions, so a provider calling one threw
  12093. // std::bad_function_call out of the thread running it and took the whole
  12094. // process down.
  12095. DataSink sink;
  12096. std::string written;
  12097. sink.write = [&](const char *data, size_t data_len) {
  12098. written.append(data, data_len);
  12099. return true;
  12100. };
  12101. EXPECT_TRUE(sink.is_writable());
  12102. sink.done();
  12103. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12104. EXPECT_TRUE(written.empty());
  12105. }
  12106. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12107. // A sink that cannot carry trailers still has to finish.
  12108. DataSink sink;
  12109. auto done_count = 0;
  12110. sink.done = [&]() { done_count++; };
  12111. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12112. EXPECT_EQ(1, done_count);
  12113. }
  12114. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12115. Server svr;
  12116. const std::string body(4096, 'x');
  12117. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12118. res.set_content_provider(body.size(), "text/plain",
  12119. [&](size_t offset, size_t length, DataSink &sink) {
  12120. sink.write(body.data() + offset, length);
  12121. sink.done();
  12122. return true;
  12123. });
  12124. });
  12125. auto port = svr.bind_to_any_port(HOST);
  12126. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12127. auto se = detail::scope_exit([&] {
  12128. svr.stop();
  12129. listen_thread.join();
  12130. ASSERT_FALSE(svr.is_running());
  12131. });
  12132. svr.wait_until_ready();
  12133. Client cli(HOST, port);
  12134. auto res = cli.Get("/");
  12135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12136. EXPECT_EQ(StatusCode::OK_200, res->status);
  12137. EXPECT_EQ(body, res->body);
  12138. }
  12139. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12140. Server svr;
  12141. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12142. res.set_content_provider(
  12143. 1024, "text/plain",
  12144. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12145. sink.write("hello", 5);
  12146. sink.done(); // short of the 1024 bytes the response promised
  12147. return true;
  12148. });
  12149. });
  12150. auto port = svr.bind_to_any_port(HOST);
  12151. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12152. auto se = detail::scope_exit([&] {
  12153. svr.stop();
  12154. listen_thread.join();
  12155. ASSERT_FALSE(svr.is_running());
  12156. });
  12157. svr.wait_until_ready();
  12158. Client cli(HOST, port);
  12159. cli.set_read_timeout(5, 0);
  12160. // The response is short of its Content-Length, so the client cannot read a
  12161. // complete body. What matters is that this returns at all: a no-op done()
  12162. // would leave the writer looping over a provider that never makes progress.
  12163. auto res = cli.Get("/");
  12164. EXPECT_FALSE(res);
  12165. }
  12166. // Read as the next response by a peer that sees it after a framed body.
  12167. static const std::string smuggled_response =
  12168. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12169. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12170. Server svr;
  12171. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12172. res.set_content_provider(
  12173. 5, "text/plain",
  12174. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12175. auto data = "AAAAA" + smuggled_response;
  12176. sink.write(data.data(), data.size());
  12177. return true;
  12178. });
  12179. });
  12180. thread t = thread([&] { svr.listen(HOST, PORT); });
  12181. auto se = detail::scope_exit([&] {
  12182. svr.stop();
  12183. t.join();
  12184. ASSERT_FALSE(svr.is_running());
  12185. });
  12186. svr.wait_until_ready();
  12187. std::string resp;
  12188. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12189. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12190. resp.clear();
  12191. ASSERT_TRUE(send_request(
  12192. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12193. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12194. }
  12195. TEST(NoContentTest, BodyIsNotSent) {
  12196. Server svr;
  12197. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12198. res.status = StatusCode::NoContent_204;
  12199. res.set_content(smuggled_response, "text/plain");
  12200. });
  12201. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12202. res.status = StatusCode::NotModified_304;
  12203. res.set_chunked_content_provider(
  12204. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12205. sink.write(smuggled_response.data(), smuggled_response.size());
  12206. sink.done();
  12207. return true;
  12208. });
  12209. });
  12210. thread t = thread([&] { svr.listen(HOST, PORT); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. t.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. });
  12216. svr.wait_until_ready();
  12217. for (auto path : {"/204", "/304"}) {
  12218. std::string resp;
  12219. ASSERT_TRUE(send_request(
  12220. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12221. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12222. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12223. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12224. }
  12225. }
  12226. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12227. Server svr;
  12228. std::atomic<bool> smuggled(false);
  12229. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12230. res.set_content("ok", "text/plain");
  12231. });
  12232. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12233. smuggled = true;
  12234. });
  12235. auto port = svr.bind_to_any_port(HOST);
  12236. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. listen_thread.join();
  12240. ASSERT_FALSE(svr.is_running());
  12241. });
  12242. svr.wait_until_ready();
  12243. // What follows the body would be read as the next request.
  12244. Client cli(HOST, port);
  12245. auto res = cli.Post(
  12246. "/", 5,
  12247. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12248. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12249. sink.write(data.data(), data.size());
  12250. return true;
  12251. },
  12252. "text/plain");
  12253. ASSERT_FALSE(res);
  12254. EXPECT_EQ(Error::Write, res.error());
  12255. EXPECT_FALSE(smuggled);
  12256. }
  12257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12258. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12259. // The compressed path builds the whole body before connecting, so this
  12260. // fails client-side and never reaches a server.
  12261. Client cli(HOST, PORT);
  12262. cli.set_compress(true);
  12263. auto res = cli.Post(
  12264. "/", 1024,
  12265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12266. sink.write("hello", 5);
  12267. sink.done(); // short of the 1024 bytes the request announced
  12268. return true;
  12269. },
  12270. "text/plain");
  12271. ASSERT_FALSE(res);
  12272. EXPECT_EQ(Error::Write, res.error());
  12273. }
  12274. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12275. Server svr;
  12276. std::string received;
  12277. size_t content_length_count = 0;
  12278. bool has_transfer_encoding = true;
  12279. svr.Post("/echo", [&](const Request &req, Response &res) {
  12280. received = req.body;
  12281. content_length_count = req.get_header_value_count("Content-Length");
  12282. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12283. res.set_content("ok", "text/plain");
  12284. });
  12285. svr.Get("/next", [](const Request &, Response &res) {
  12286. res.set_content("next", "text/plain");
  12287. });
  12288. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12289. auto se = detail::scope_exit([&] {
  12290. svr.stop();
  12291. listen_thread.join();
  12292. ASSERT_FALSE(svr.is_running());
  12293. });
  12294. svr.wait_until_ready();
  12295. Client cli(HOST, PORT);
  12296. cli.set_keep_alive(true);
  12297. cli.set_compress(true);
  12298. const std::string body = "hello world";
  12299. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12300. auto res = cli.Post("/echo", headers, body, "text/plain");
  12301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12302. EXPECT_EQ(StatusCode::OK_200, res->status);
  12303. EXPECT_EQ(body, received);
  12304. EXPECT_EQ(1u, content_length_count);
  12305. EXPECT_FALSE(has_transfer_encoding);
  12306. // The rest of a truncated body would be read as this request
  12307. auto res2 = cli.Get("/next");
  12308. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12309. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12310. EXPECT_EQ("next", res2->body);
  12311. }
  12312. #endif
  12313. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12314. Server svr;
  12315. std::string received;
  12316. size_t content_length_count = 1;
  12317. bool has_transfer_encoding = false;
  12318. svr.Post("/echo", [&](const Request &req, Response &res) {
  12319. received = req.body;
  12320. content_length_count = req.get_header_value_count("Content-Length");
  12321. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12322. res.set_content("ok", "text/plain");
  12323. });
  12324. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12325. auto se = detail::scope_exit([&] {
  12326. svr.stop();
  12327. listen_thread.join();
  12328. ASSERT_FALSE(svr.is_running());
  12329. });
  12330. svr.wait_until_ready();
  12331. Client cli(HOST, PORT);
  12332. cli.set_keep_alive(true);
  12333. const std::string body = "hello world";
  12334. Headers headers = {{"Content-Length", "5"}};
  12335. auto res = cli.Post(
  12336. "/echo", headers,
  12337. [&](size_t /*offset*/, DataSink &sink) {
  12338. sink.write(body.data(), body.size());
  12339. sink.done();
  12340. return true;
  12341. },
  12342. "text/plain");
  12343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12344. EXPECT_EQ(StatusCode::OK_200, res->status);
  12345. EXPECT_EQ(body, received);
  12346. EXPECT_EQ(0u, content_length_count);
  12347. EXPECT_TRUE(has_transfer_encoding);
  12348. }
  12349. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12350. Server svr;
  12351. svr.set_error_handler([](Request const &, Response &res) -> void {
  12352. res.set_chunked_content_provider(
  12353. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12354. sink.os << "hello";
  12355. sink.os << "world";
  12356. sink.done();
  12357. return true;
  12358. });
  12359. });
  12360. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12361. auto se = detail::scope_exit([&] {
  12362. svr.stop();
  12363. listen_thread.join();
  12364. ASSERT_FALSE(svr.is_running());
  12365. });
  12366. svr.wait_until_ready();
  12367. Client cli("localhost", PORT);
  12368. auto res = cli.Get("/");
  12369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12371. EXPECT_EQ("helloworld", res->body);
  12372. }
  12373. // A body set after a content provider must replace it, not be sent through it.
  12374. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12375. Server svr;
  12376. svr.set_mount_point("/", "./www");
  12377. svr.set_file_request_handler([](const Request &req, Response &res) {
  12378. if (req.path == "/dir/test.html") {
  12379. res.status = StatusCode::Forbidden_403;
  12380. res.set_content(std::string(5000, 'D'), "text/plain");
  12381. } else if (req.path == "/file") {
  12382. res.status = StatusCode::Forbidden_403;
  12383. res.body = "Denied";
  12384. }
  12385. });
  12386. auto port = svr.bind_to_any_port(HOST);
  12387. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12388. auto se = detail::scope_exit([&] {
  12389. svr.stop();
  12390. t.join();
  12391. ASSERT_FALSE(svr.is_running());
  12392. });
  12393. svr.wait_until_ready();
  12394. Client cli(HOST, port);
  12395. {
  12396. auto res = cli.Get("/dir/test.html");
  12397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12398. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12399. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12400. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12401. }
  12402. {
  12403. auto res = cli.Get("/file");
  12404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12405. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12406. EXPECT_EQ("Denied", res->body);
  12407. }
  12408. {
  12409. auto res = cli.Get("/dir/index.html");
  12410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12411. EXPECT_EQ(StatusCode::OK_200, res->status);
  12412. EXPECT_EQ(0U, res->body.find("<html>"));
  12413. }
  12414. }
  12415. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12416. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12417. Server svr;
  12418. std::vector<bool> released;
  12419. std::mutex released_mutex;
  12420. auto releaser = [&](bool success) {
  12421. std::lock_guard<std::mutex> guard(released_mutex);
  12422. released.push_back(success);
  12423. };
  12424. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12425. return sink.write(&"hello"[offset], length);
  12426. };
  12427. svr.Get("/sized", [&](const Request &, Response &res) {
  12428. res.status = StatusCode::NotFound_404;
  12429. res.set_content_provider(5, "text/plain", provider, releaser);
  12430. });
  12431. svr.Get("/chunked", [&](const Request &, Response &res) {
  12432. res.status = StatusCode::ServiceUnavailable_503;
  12433. res.set_chunked_content_provider(
  12434. "text/plain",
  12435. [](size_t, DataSink &sink) {
  12436. sink.os << "chunk";
  12437. sink.done();
  12438. return true;
  12439. },
  12440. releaser);
  12441. });
  12442. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12443. res.set_content_provider(5, "text/plain", provider, releaser);
  12444. throw std::runtime_error("after the provider");
  12445. });
  12446. svr.set_error_handler([](const Request &req, Response &res) {
  12447. // Leave the exception handler's content to it.
  12448. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12449. res.set_content(std::string(1000, 'E'), "text/html");
  12450. return Server::HandlerResponse::Handled;
  12451. });
  12452. svr.set_exception_handler(
  12453. [](const Request &, Response &res, std::exception_ptr) {
  12454. res.status = StatusCode::InternalServerError_500;
  12455. res.set_content(std::string(1000, 'X'), "text/html");
  12456. });
  12457. auto port = svr.bind_to_any_port(HOST);
  12458. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12459. auto se = detail::scope_exit([&] {
  12460. svr.stop();
  12461. t.join();
  12462. ASSERT_FALSE(svr.is_running());
  12463. });
  12464. svr.wait_until_ready();
  12465. Client cli(HOST, port);
  12466. {
  12467. auto res = cli.Get("/sized");
  12468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12470. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12472. }
  12473. {
  12474. auto res = cli.Get("/chunked");
  12475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12477. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12478. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12479. }
  12480. {
  12481. auto res = cli.Get("/throw");
  12482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12483. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12484. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12485. }
  12486. std::lock_guard<std::mutex> guard(released_mutex);
  12487. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12488. }
  12489. #endif
  12490. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12491. Server svr;
  12492. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12493. return sink.write(&"abc"[offset], length);
  12494. };
  12495. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12496. res.set_file_content("./www/dir/test.html");
  12497. res.set_content("body", "text/plain");
  12498. });
  12499. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12500. res.set_content(std::string(100, 'B'), "text/plain");
  12501. res.set_file_content("./www/dir/test.html");
  12502. });
  12503. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12504. res.set_content(std::string(100, 'B'), "text/plain");
  12505. res.set_content_provider(3, "text/x-provider", abc);
  12506. });
  12507. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12508. res.set_content_provider(3, "text/x-provider", abc);
  12509. res.set_content(std::string(100, 'B'), "text/plain");
  12510. });
  12511. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12512. res.set_content_provider(3, "text/x-provider", abc);
  12513. res.set_file_content("./www/dir/test.html", "text/x-file");
  12514. });
  12515. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12516. res.set_file_content("./www/dir/test.html");
  12517. res.set_header("Content-Type", "text/x-handler");
  12518. });
  12519. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12520. res.set_content_provider(3, "text/plain", abc);
  12521. res.body = "direct";
  12522. });
  12523. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12524. res.set_file_content("./www/dir/test.html");
  12525. res.body = "direct";
  12526. });
  12527. auto port = svr.bind_to_any_port(HOST);
  12528. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12529. auto se = detail::scope_exit([&] {
  12530. svr.stop();
  12531. t.join();
  12532. ASSERT_FALSE(svr.is_running());
  12533. });
  12534. svr.wait_until_ready();
  12535. Client cli(HOST, port);
  12536. auto expect_body = [&](const char *path, const std::string &body,
  12537. const std::string &type) {
  12538. // Uncompressed, so Content-Length can be compared with the body.
  12539. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12540. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12541. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12542. EXPECT_EQ(body, res->body) << path;
  12543. EXPECT_EQ(std::to_string(body.size()),
  12544. res->get_header_value("Content-Length"))
  12545. << path;
  12546. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12547. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12548. };
  12549. expect_body("/file-then-body", "body", "text/plain");
  12550. expect_body("/body-then-file", "test.html", "text/html");
  12551. expect_body("/body-then-provider", "abc", "text/x-provider");
  12552. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12553. expect_body("/provider-then-file", "test.html", "text/x-file");
  12554. expect_body("/file-then-header", "test.html", "text/x-handler");
  12555. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12556. expect_body("/file-then-direct-body", "direct", "text/plain");
  12557. // Ranges are checked against the body, not the dropped provider.
  12558. {
  12559. auto res = cli.Get("/provider-then-direct-body",
  12560. Headers{{make_range_header({{1, 2}})}});
  12561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12562. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12563. EXPECT_EQ("ir", res->body);
  12564. }
  12565. {
  12566. auto res = cli.Get("/file-then-direct-body",
  12567. Headers{{make_range_header({{7, 8}})}});
  12568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12569. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12570. }
  12571. }
  12572. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12573. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12574. const char *path = "./truncated_while_served.txt";
  12575. const size_t size = 32 * 1024 * 1024;
  12576. {
  12577. std::ofstream f(path, std::ios::binary);
  12578. f << std::string(size, 'x');
  12579. }
  12580. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12581. // Over TLS, where the bytes are encrypted in this process rather than
  12582. // copied by send().
  12583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12584. svr.Get("/file", [&](const Request &, Response &res) {
  12585. res.set_file_content(path, "text/plain");
  12586. });
  12587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12588. auto se = detail::scope_exit([&] {
  12589. svr.stop();
  12590. thread.join();
  12591. ASSERT_FALSE(svr.is_running());
  12592. });
  12593. svr.wait_until_ready();
  12594. // The file shrinks once the first bytes are in, as a rewrite in place
  12595. // would, and reading the mapping past its new end used to raise SIGBUS.
  12596. SSLClient cli(HOST, PORT);
  12597. cli.enable_server_certificate_verification(false);
  12598. size_t received = 0;
  12599. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12600. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12601. received += len;
  12602. return true;
  12603. });
  12604. EXPECT_FALSE(res);
  12605. EXPECT_LT(received, size);
  12606. }
  12607. #endif
  12608. // Forward declaration (see the base64_encode note).
  12609. namespace httplib {
  12610. namespace detail {
  12611. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12612. const std::string &content_type,
  12613. EncodingType encoding);
  12614. } // namespace detail
  12615. } // namespace httplib
  12616. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12617. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12618. ASSERT_TRUE(mm->is_open());
  12619. Response res;
  12620. detail::set_file_content_provider(res, mm, "text/html",
  12621. detail::EncodingType::None);
  12622. std::string out;
  12623. DataSink sink;
  12624. sink.write = [&](const char *d, size_t l) {
  12625. out.append(d, l);
  12626. return true;
  12627. };
  12628. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12629. EXPECT_EQ("test.html", out);
  12630. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12631. EXPECT_EQ("test.html", out);
  12632. }
  12633. TEST(LongPollingTest, ClientCloseDetection) {
  12634. Server svr;
  12635. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12636. res.set_chunked_content_provider(
  12637. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12638. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12639. sink.os << "hello";
  12640. auto count = 10;
  12641. while (count > 0 && sink.is_writable()) {
  12642. this_thread::sleep_for(chrono::milliseconds(10));
  12643. count--;
  12644. }
  12645. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12646. return true;
  12647. });
  12648. });
  12649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12650. auto se = detail::scope_exit([&] {
  12651. svr.stop();
  12652. listen_thread.join();
  12653. ASSERT_FALSE(svr.is_running());
  12654. });
  12655. svr.wait_until_ready();
  12656. Client cli("localhost", PORT);
  12657. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12658. EXPECT_EQ("hello", string(data, data_length));
  12659. return false; // close the socket immediately.
  12660. });
  12661. ASSERT_FALSE(res);
  12662. }
  12663. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12664. Server svr;
  12665. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12666. res.set_chunked_content_provider(
  12667. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12668. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12669. sink.os << "hello";
  12670. EXPECT_TRUE(sink.os.good());
  12671. // Wait for the client to close the connection
  12672. auto count = 10;
  12673. while (count > 0 && sink.is_writable()) {
  12674. this_thread::sleep_for(chrono::milliseconds(10));
  12675. count--;
  12676. }
  12677. // After client disconnect, write repeatedly until the socket
  12678. // write actually fails (small writes may be absorbed by the
  12679. // kernel buffer)
  12680. std::string chunk(1024, 'x');
  12681. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12682. sink.os << chunk;
  12683. }
  12684. EXPECT_TRUE(sink.os.fail());
  12685. return true;
  12686. });
  12687. });
  12688. auto port = svr.bind_to_any_port("localhost");
  12689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12690. auto se = detail::scope_exit([&] {
  12691. svr.stop();
  12692. listen_thread.join();
  12693. ASSERT_FALSE(svr.is_running());
  12694. });
  12695. svr.wait_until_ready();
  12696. Client cli("localhost", port);
  12697. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12698. EXPECT_EQ("hello", string(data, data_length));
  12699. return false; // close the socket immediately.
  12700. });
  12701. ASSERT_FALSE(res);
  12702. }
  12703. TEST(GetWithParametersTest, GetWithParameters) {
  12704. Server svr;
  12705. svr.Get("/", [&](const Request &req, Response &) {
  12706. EXPECT_EQ("world", req.get_param_value("hello"));
  12707. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12708. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12709. });
  12710. svr.Get("/params", [&](const Request &req, Response &) {
  12711. EXPECT_EQ("world", req.get_param_value("hello"));
  12712. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12713. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12714. });
  12715. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12716. EXPECT_EQ("resource-id", req.matches[1]);
  12717. EXPECT_EQ("foo", req.get_param_value("param1"));
  12718. EXPECT_EQ("bar", req.get_param_value("param2"));
  12719. });
  12720. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12721. EXPECT_EQ("user-id", req.path_params.at("id"));
  12722. EXPECT_EQ("foo", req.get_param_value("param1"));
  12723. EXPECT_EQ("bar", req.get_param_value("param2"));
  12724. });
  12725. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12726. auto se = detail::scope_exit([&] {
  12727. svr.stop();
  12728. listen_thread.join();
  12729. ASSERT_FALSE(svr.is_running());
  12730. });
  12731. svr.wait_until_ready();
  12732. {
  12733. Client cli(HOST, PORT);
  12734. Params params;
  12735. params.emplace("hello", "world");
  12736. params.emplace("hello2", "world2");
  12737. params.emplace("hello3", "world3");
  12738. auto res = cli.Get("/", params, Headers{});
  12739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12740. EXPECT_EQ(StatusCode::OK_200, res->status);
  12741. }
  12742. {
  12743. Client cli(HOST, PORT);
  12744. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12746. EXPECT_EQ(StatusCode::OK_200, res->status);
  12747. }
  12748. {
  12749. Client cli(HOST, PORT);
  12750. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12752. EXPECT_EQ(StatusCode::OK_200, res->status);
  12753. }
  12754. {
  12755. Client cli(HOST, PORT);
  12756. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12758. EXPECT_EQ(StatusCode::OK_200, res->status);
  12759. }
  12760. }
  12761. TEST(GetWithParametersTest, GetWithParameters2) {
  12762. Server svr;
  12763. svr.Get("/", [&](const Request &req, Response &res) {
  12764. auto text = req.get_param_value("hello");
  12765. res.set_content(text, "text/plain");
  12766. });
  12767. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. listen_thread.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. Client cli("localhost", PORT);
  12775. Params params;
  12776. params.emplace("hello", "world");
  12777. std::string body;
  12778. auto res = cli.Get("/", params, Headers{},
  12779. [&](const char *data, size_t data_length) {
  12780. body.append(data, data_length);
  12781. return true;
  12782. });
  12783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12784. EXPECT_EQ(StatusCode::OK_200, res->status);
  12785. EXPECT_EQ("world", body);
  12786. }
  12787. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12788. Server svr;
  12789. svr.Get("/search", [&](const Request &req, Response &res) {
  12790. auto q = req.get_param_value("q");
  12791. res.set_content(q, "text/plain");
  12792. });
  12793. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12794. auto se = detail::scope_exit([&] {
  12795. svr.stop();
  12796. listen_thread.join();
  12797. ASSERT_FALSE(svr.is_running());
  12798. });
  12799. svr.wait_until_ready();
  12800. Client cli("localhost", PORT);
  12801. // Verify that Get(path, params) works without requiring Headers argument
  12802. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12804. EXPECT_EQ(StatusCode::OK_200, res->status);
  12805. EXPECT_EQ("cpp-httplib", res->body);
  12806. }
  12807. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12808. auto host = "httpbingo.org";
  12809. auto path = std::string{"/range/32"};
  12810. #ifdef CPPHTTPLIB_SSL_ENABLED
  12811. SSLClient cli(host);
  12812. #else
  12813. Client cli(host);
  12814. #endif
  12815. cli.set_default_headers({make_range_header({{1, 10}})});
  12816. cli.set_connection_timeout(5);
  12817. {
  12818. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12819. SKIP_ON_GATEWAY_ERROR(res);
  12820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12821. EXPECT_EQ("bcdefghijk", res->body);
  12822. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12823. }
  12824. {
  12825. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12826. SKIP_ON_GATEWAY_ERROR(res);
  12827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12828. EXPECT_EQ("bcdefghijk", res->body);
  12829. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12830. }
  12831. }
  12832. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12833. Server svr;
  12834. svr.set_default_headers({{"Hello", "World"}});
  12835. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12836. res.set_content("ok", "text/plain");
  12837. });
  12838. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12839. auto se = detail::scope_exit([&] {
  12840. svr.stop();
  12841. listen_thread.join();
  12842. ASSERT_FALSE(svr.is_running());
  12843. });
  12844. svr.wait_until_ready();
  12845. Client cli("localhost", PORT);
  12846. auto res = cli.Get("/");
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. EXPECT_EQ(StatusCode::OK_200, res->status);
  12849. EXPECT_EQ("ok", res->body);
  12850. EXPECT_EQ("World", res->get_header_value("Hello"));
  12851. }
  12852. #ifdef CPPHTTPLIB_SSL_ENABLED
  12853. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12855. ASSERT_TRUE(svr.is_valid());
  12856. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12857. std::this_thread::sleep_for(std::chrono::seconds(2));
  12858. res.set_content("a", "text/plain");
  12859. });
  12860. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12861. res.set_content("b", "text/plain");
  12862. });
  12863. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12864. auto se = detail::scope_exit([&] {
  12865. svr.stop();
  12866. listen_thread.join();
  12867. ASSERT_FALSE(svr.is_running());
  12868. });
  12869. svr.wait_until_ready();
  12870. SSLClient cli("localhost", PORT);
  12871. cli.enable_server_certificate_verification(false);
  12872. cli.set_keep_alive(true);
  12873. cli.set_read_timeout(std::chrono::seconds(1));
  12874. auto resa = cli.Get("/a");
  12875. ASSERT_TRUE(!resa);
  12876. EXPECT_EQ(Error::Read, resa.error());
  12877. auto resb = cli.Get("/b");
  12878. ASSERT_TRUE(resb);
  12879. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12880. EXPECT_EQ("b", resb->body);
  12881. }
  12882. // Closing an idle keep-alive connection sends close_notify and returns. The
  12883. // server must not wait for the client's close_notify: an idle client never
  12884. // sends one, so the worker would be held until the read timeout expires, and
  12885. // stop() would wait for it.
  12886. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12888. ASSERT_TRUE(svr.is_valid());
  12889. svr.set_keep_alive_timeout(1);
  12890. svr.set_read_timeout(10, 0);
  12891. svr.Get("/", [](const Request &, Response &res) {
  12892. res.set_content("ok", "text/plain");
  12893. });
  12894. auto port = svr.bind_to_any_port(HOST);
  12895. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12896. auto se = detail::scope_exit([&] {
  12897. if (listen_thread.joinable()) {
  12898. svr.stop();
  12899. listen_thread.join();
  12900. }
  12901. });
  12902. svr.wait_until_ready();
  12903. SSLClient cli(HOST, port);
  12904. cli.enable_server_certificate_verification(false);
  12905. cli.set_keep_alive(true);
  12906. auto res = cli.Get("/");
  12907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12908. EXPECT_EQ(StatusCode::OK_200, res->status);
  12909. // Stay idle past the keep-alive timeout so the server closes the connection.
  12910. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12911. auto start = std::chrono::steady_clock::now();
  12912. svr.stop();
  12913. listen_thread.join();
  12914. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12915. std::chrono::steady_clock::now() - start)
  12916. .count();
  12917. EXPECT_LT(elapsed, 3000);
  12918. }
  12919. #endif
  12920. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12921. protected:
  12922. ServerTestWithAI_PASSIVE()
  12923. : cli_(HOST, PORT)
  12924. #ifdef CPPHTTPLIB_SSL_ENABLED
  12925. ,
  12926. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12927. #endif
  12928. {
  12929. #ifdef CPPHTTPLIB_SSL_ENABLED
  12930. cli_.enable_server_certificate_verification(false);
  12931. #endif
  12932. }
  12933. virtual void SetUp() {
  12934. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12935. res.set_content("Hello World!", "text/plain");
  12936. });
  12937. t_ = thread(
  12938. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12939. svr_.wait_until_ready();
  12940. }
  12941. virtual void TearDown() {
  12942. svr_.stop();
  12943. t_.join();
  12944. }
  12945. #ifdef CPPHTTPLIB_SSL_ENABLED
  12946. SSLClient cli_;
  12947. SSLServer svr_;
  12948. #else
  12949. Client cli_;
  12950. Server svr_;
  12951. #endif
  12952. thread t_;
  12953. };
  12954. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12955. auto res = cli_.Get("/hi");
  12956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12957. EXPECT_EQ(StatusCode::OK_200, res->status);
  12958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12959. EXPECT_EQ("Hello World!", res->body);
  12960. }
  12961. class ServerUpDownTest : public ::testing::Test {
  12962. protected:
  12963. ServerUpDownTest() : cli_(HOST, PORT) {}
  12964. virtual void SetUp() {
  12965. t_ = thread([&]() {
  12966. svr_.bind_to_any_port(HOST);
  12967. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12968. ASSERT_TRUE(svr_.listen_after_bind());
  12969. });
  12970. svr_.wait_until_ready();
  12971. }
  12972. virtual void TearDown() {
  12973. svr_.stop();
  12974. t_.join();
  12975. }
  12976. Client cli_;
  12977. Server svr_;
  12978. thread t_;
  12979. };
  12980. TEST_F(ServerUpDownTest, QuickStartStop) {
  12981. // Should not crash, especially when run with
  12982. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12983. }
  12984. class PayloadMaxLengthTest : public ::testing::Test {
  12985. protected:
  12986. PayloadMaxLengthTest()
  12987. : cli_(HOST, PORT)
  12988. #ifdef CPPHTTPLIB_SSL_ENABLED
  12989. ,
  12990. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12991. #endif
  12992. {
  12993. #ifdef CPPHTTPLIB_SSL_ENABLED
  12994. cli_.enable_server_certificate_verification(false);
  12995. #endif
  12996. }
  12997. virtual void SetUp() {
  12998. svr_.set_payload_max_length(8);
  12999. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13000. res.set_content("test", "text/plain");
  13001. });
  13002. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13003. svr_.wait_until_ready();
  13004. }
  13005. virtual void TearDown() {
  13006. svr_.stop();
  13007. t_.join();
  13008. }
  13009. #ifdef CPPHTTPLIB_SSL_ENABLED
  13010. SSLClient cli_;
  13011. SSLServer svr_;
  13012. #else
  13013. Client cli_;
  13014. Server svr_;
  13015. #endif
  13016. thread t_;
  13017. };
  13018. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13019. auto res = cli_.Post("/test", "123456789", "text/plain");
  13020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13021. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13022. res = cli_.Post("/test", "12345678", "text/plain");
  13023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13024. EXPECT_EQ(StatusCode::OK_200, res->status);
  13025. }
  13026. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13027. // Test chunked encoding with payload exceeding the 8-byte limit
  13028. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13029. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13031. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13032. }
  13033. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13034. // Test chunked encoding with payload within the 8-byte limit
  13035. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13036. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13038. EXPECT_EQ(StatusCode::OK_200, res->status);
  13039. }
  13040. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13041. // Test using send_request to send chunked data exceeding payload limit
  13042. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13043. "Host: " +
  13044. std::string(HOST) + ":" + std::to_string(PORT) +
  13045. "\r\n"
  13046. "Transfer-Encoding: chunked\r\n"
  13047. "Connection: close\r\n"
  13048. "\r\n"
  13049. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13050. "0123456789\r\n"
  13051. "0\r\n" // End chunk
  13052. "\r\n";
  13053. std::string response;
  13054. bool result = send_request(1, chunked_request, &response);
  13055. if (!result) {
  13056. // If send_request fails, it might be because the server closed the
  13057. // connection due to payload limit enforcement, which is acceptable
  13058. SUCCEED()
  13059. << "Server rejected oversized chunked request (connection closed)";
  13060. } else {
  13061. // If we got a response, check if it's an error response or connection was
  13062. // closed early Short response length indicates connection was closed due to
  13063. // payload limit
  13064. if (response.length() <= 10) {
  13065. SUCCEED() << "Server closed connection for oversized chunked request";
  13066. } else {
  13067. // Check for error status codes
  13068. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13069. response.find("Payload Too Large") != std::string::npos ||
  13070. response.find("400") != std::string::npos);
  13071. }
  13072. }
  13073. }
  13074. class LargePayloadMaxLengthTest : public ::testing::Test {
  13075. protected:
  13076. LargePayloadMaxLengthTest()
  13077. : cli_(HOST, PORT)
  13078. #ifdef CPPHTTPLIB_SSL_ENABLED
  13079. ,
  13080. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13081. #endif
  13082. {
  13083. #ifdef CPPHTTPLIB_SSL_ENABLED
  13084. cli_.enable_server_certificate_verification(false);
  13085. #endif
  13086. }
  13087. virtual void SetUp() {
  13088. // Set 10MB payload limit
  13089. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13090. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13091. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13092. res.set_content("Large payload test", "text/plain");
  13093. });
  13094. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13095. svr_.wait_until_ready();
  13096. }
  13097. virtual void TearDown() {
  13098. svr_.stop();
  13099. t_.join();
  13100. }
  13101. #ifdef CPPHTTPLIB_SSL_ENABLED
  13102. SSLClient cli_;
  13103. SSLServer svr_;
  13104. #else
  13105. Client cli_;
  13106. Server svr_;
  13107. #endif
  13108. thread t_;
  13109. };
  13110. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13111. // Test chunked encoding with payload within 10MB limit
  13112. std::string medium_payload(5 * 1024 * 1024,
  13113. 'A'); // 5MB payload, within 10MB limit
  13114. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13116. EXPECT_EQ(StatusCode::OK_200, res->status);
  13117. }
  13118. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13119. // Test chunked encoding with payload exceeding 10MB limit
  13120. std::string large_payload(12 * 1024 * 1024,
  13121. 'B'); // 12MB payload, exceeds 10MB limit
  13122. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13123. // Server may either return 413 or close the connection
  13124. if (res) {
  13125. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13126. } else {
  13127. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13128. }
  13129. }
  13130. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13131. Server svr;
  13132. svr.Get("/", [](const Request &, Response &res) {
  13133. // Claims the most the client accepts, far more than it sends, then drops
  13134. // the connection.
  13135. res.set_content_provider(std::string().max_size(), "text/plain",
  13136. [](size_t, size_t, DataSink &sink) {
  13137. sink.write("abc", 3);
  13138. return false;
  13139. });
  13140. });
  13141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13142. auto se = detail::scope_exit([&] {
  13143. svr.stop();
  13144. thread.join();
  13145. ASSERT_FALSE(svr.is_running());
  13146. });
  13147. svr.wait_until_ready();
  13148. Client cli(HOST, PORT);
  13149. cli.set_payload_max_length(0);
  13150. EXPECT_FALSE(cli.Get("/"));
  13151. }
  13152. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13153. // Stream API does, not as a plain read failure
  13154. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13155. Server svr;
  13156. svr.Get("/big", [](const Request &, Response &res) {
  13157. res.set_content(std::string(100000, 'b'), "text/plain");
  13158. });
  13159. auto port = svr.bind_to_any_port(HOST);
  13160. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13161. auto se = detail::scope_exit([&] {
  13162. svr.stop();
  13163. thread.join();
  13164. });
  13165. svr.wait_until_ready();
  13166. Client cli(HOST, port);
  13167. cli.set_payload_max_length(1000);
  13168. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13169. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13170. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13171. [](const char *, size_t) { return true; });
  13172. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13173. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13174. // Small on the wire, over the limit once decompressed
  13175. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13176. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13177. #endif
  13178. }
  13179. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13180. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13181. // path.
  13182. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13183. Server svr;
  13184. const size_t LIMIT = 64 * 1024; // 64KB
  13185. svr.set_payload_max_length(LIMIT);
  13186. size_t total = 0;
  13187. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13188. const ContentReader &content_reader) {
  13189. content_reader([&](const char * /*data*/, size_t len) {
  13190. total += len;
  13191. return true;
  13192. });
  13193. res.status = 200;
  13194. res.set_content("stream_ok", "text/plain");
  13195. });
  13196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13197. auto se = detail::scope_exit([&] {
  13198. svr.stop();
  13199. thread.join();
  13200. ASSERT_FALSE(svr.is_running());
  13201. });
  13202. svr.wait_until_ready();
  13203. // Prepare 256KB raw data and gzip-compress it
  13204. std::string raw(256 * 1024, 'A');
  13205. std::string gz;
  13206. {
  13207. z_stream zs{};
  13208. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13209. Z_DEFAULT_STRATEGY);
  13210. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13211. zs.avail_in = static_cast<uInt>(raw.size());
  13212. char outbuf[4096];
  13213. int ret;
  13214. do {
  13215. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13216. zs.avail_out = sizeof(outbuf);
  13217. ret = deflate(&zs, Z_FINISH);
  13218. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13219. } while (ret != Z_STREAM_END);
  13220. deflateEnd(&zs);
  13221. }
  13222. Client cli(HOST, PORT);
  13223. cli.set_connection_timeout(std::chrono::seconds(5));
  13224. Headers headers = {{"Content-Encoding", "gzip"}};
  13225. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13226. "application/octet-stream");
  13227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13228. // Server must reject oversized decompressed payloads with 413.
  13229. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13230. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13231. EXPECT_LE(total, LIMIT);
  13232. }
  13233. #endif
  13234. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13235. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13236. // the payload must be passed through untouched instead of being rejected.
  13237. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13238. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13239. Server svr;
  13240. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13241. res.set_content(body, "image/jpeg");
  13242. res.set_header("Content-Encoding", "UTF-8");
  13243. });
  13244. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13245. res.set_content(body, "image/jpeg");
  13246. res.set_header("Content-Encoding", "identity");
  13247. });
  13248. svr.Post("/echo", [](const Request &req, Response &res) {
  13249. res.set_content(req.body, "image/jpeg");
  13250. });
  13251. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13252. auto se = detail::scope_exit([&] {
  13253. svr.stop();
  13254. t.join();
  13255. ASSERT_FALSE(svr.is_running());
  13256. });
  13257. svr.wait_until_ready();
  13258. Client cli(HOST, PORT);
  13259. {
  13260. auto res = cli.Get("/image");
  13261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13262. EXPECT_EQ(StatusCode::OK_200, res->status);
  13263. EXPECT_EQ(body, res->body);
  13264. }
  13265. {
  13266. auto res = cli.Get("/identity");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_EQ(StatusCode::OK_200, res->status);
  13269. EXPECT_EQ(body, res->body);
  13270. }
  13271. {
  13272. // The same applies to a request body reaching the server.
  13273. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13274. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. EXPECT_EQ(StatusCode::OK_200, res->status);
  13277. EXPECT_EQ(body, res->body);
  13278. }
  13279. }
  13280. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13281. // gzip-encoded response even when the build has no zlib support.
  13282. static const char GZIPPED_HELLO_WORLD[] = {
  13283. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13284. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13285. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13286. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13287. // A content coding is a whole token, not something the field value merely
  13288. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13289. // as "fibre" look like Brotli, and turned a multi-coding value like
  13290. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13291. // it was never meant to see.
  13292. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13293. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13294. Server svr;
  13295. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13296. res.set_content(body, "image/jpeg");
  13297. res.set_header("Content-Encoding", "fibre");
  13298. });
  13299. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13300. res.set_content(body, "image/jpeg");
  13301. res.set_header("Content-Encoding", "gzip, br");
  13302. });
  13303. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13304. res.set_content(body, "image/jpeg");
  13305. res.set_header("Content-Encoding", "x-zstd-ish");
  13306. });
  13307. auto port = svr.bind_to_any_port(HOST);
  13308. thread t = thread([&]() { svr.listen_after_bind(); });
  13309. auto se = detail::scope_exit([&] {
  13310. svr.stop();
  13311. t.join();
  13312. ASSERT_FALSE(svr.is_running());
  13313. });
  13314. svr.wait_until_ready();
  13315. Client cli(HOST, port);
  13316. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13317. auto res = cli.Get(path);
  13318. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13319. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13320. // Not a coding we recognize, so the payload comes back untouched
  13321. EXPECT_EQ(body, res->body) << path;
  13322. }
  13323. }
  13324. // A content coding cpp-httplib recognizes but was not built with must be
  13325. // reported as such. Handing the still-compressed payload back to the caller
  13326. // would silently corrupt it.
  13327. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13328. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13329. Server svr;
  13330. // "image/jpeg" keeps the server from applying a content coding of its own,
  13331. // so the hand-crafted Content-Encoding below survives.
  13332. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13333. res.set_content(gzipped, "image/jpeg");
  13334. res.set_header("Content-Encoding", "gzip");
  13335. });
  13336. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13337. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13338. res.set_content(gzipped, "image/jpeg");
  13339. res.set_header("Content-Encoding", "GZIP");
  13340. });
  13341. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. ASSERT_FALSE(svr.is_running());
  13346. });
  13347. svr.wait_until_ready();
  13348. Client cli(HOST, PORT);
  13349. {
  13350. auto res = cli.Get("/gzipped");
  13351. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13353. EXPECT_EQ("Hello World!", res->body);
  13354. #else
  13355. ASSERT_FALSE(res);
  13356. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13357. #endif
  13358. }
  13359. {
  13360. // open_stream() must behave the same way.
  13361. auto handle = cli.open_stream("GET", "/gzipped");
  13362. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13363. ASSERT_TRUE(handle.is_valid());
  13364. std::string received;
  13365. char buf[256];
  13366. ssize_t n;
  13367. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13368. received.append(buf, static_cast<size_t>(n));
  13369. }
  13370. EXPECT_EQ("Hello World!", received);
  13371. #else
  13372. EXPECT_FALSE(handle.is_valid());
  13373. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13374. #endif
  13375. }
  13376. {
  13377. // A differently-cased coding must not be mistaken for an unknown one, or
  13378. // the body would be handed back still compressed.
  13379. auto res = cli.Get("/gzipped-uppercase");
  13380. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13382. EXPECT_EQ("Hello World!", res->body);
  13383. #else
  13384. ASSERT_FALSE(res);
  13385. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13386. #endif
  13387. }
  13388. }
  13389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13390. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13391. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13392. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13393. // body a second time and appending a second Content-Encoding field line, so
  13394. // clients that decode one coding per listed value handed back raw gzip bytes.
  13395. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13396. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13397. Server svr;
  13398. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13399. // keeps the server from applying a coding of its own.
  13400. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13401. res.set_content(gzipped, "text/plain");
  13402. res.set_header("Content-Encoding", "gzip");
  13403. });
  13404. auto port = svr.bind_to_any_port(HOST);
  13405. thread t = thread([&]() { svr.listen_after_bind(); });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. Client cli(HOST, port);
  13413. Headers headers = {{"Accept-Encoding", "gzip"}};
  13414. auto res = cli.Get("/pre-gzipped", headers);
  13415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13416. EXPECT_EQ(StatusCode::OK_200, res->status);
  13417. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13418. EXPECT_EQ("Hello World!", res->body);
  13419. }
  13420. // set_compress(false) sends every handler response as it is, buffered or
  13421. // streamed
  13422. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13423. const std::string text(1000, 'a');
  13424. Server svr;
  13425. svr.set_compress(false);
  13426. svr.Get("/buffered", [&](const Request &, Response &res) {
  13427. res.set_content(text, "text/plain");
  13428. });
  13429. svr.Get("/streamed", [&](const Request &, Response &res) {
  13430. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13431. sink.write(text.data(), text.size());
  13432. sink.done();
  13433. return true;
  13434. });
  13435. });
  13436. auto port = svr.bind_to_any_port(HOST);
  13437. ASSERT_LT(0, port);
  13438. thread t = thread([&] { svr.listen_after_bind(); });
  13439. auto se = detail::scope_exit([&] {
  13440. svr.stop();
  13441. t.join();
  13442. ASSERT_FALSE(svr.is_running());
  13443. });
  13444. svr.wait_until_ready();
  13445. Client cli(HOST, port);
  13446. cli.set_decompress(false);
  13447. for (auto path : {"/buffered", "/streamed"}) {
  13448. SCOPED_TRACE(path);
  13449. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13451. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13452. EXPECT_EQ(text, res->body);
  13453. }
  13454. }
  13455. // A chunked provider settles its coding where the headers are written and
  13456. // reuses it at write time. Both ends of that have to hold: a handler's own
  13457. // Content-Encoding suppresses the coding, and a response without one is still
  13458. // compressed as it always was.
  13459. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13460. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13461. const std::string plain = "Hello World! Hello World! Hello World!";
  13462. Server svr;
  13463. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13464. res.set_header("Content-Encoding", "gzip");
  13465. res.set_chunked_content_provider(
  13466. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13467. sink.write(gzipped.data(), gzipped.size());
  13468. sink.done();
  13469. return true;
  13470. });
  13471. });
  13472. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13473. res.set_chunked_content_provider(
  13474. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13475. sink.write(plain.data(), plain.size());
  13476. sink.done();
  13477. return true;
  13478. });
  13479. });
  13480. auto port = svr.bind_to_any_port(HOST);
  13481. thread t = thread([&]() { svr.listen_after_bind(); });
  13482. auto se = detail::scope_exit([&] {
  13483. svr.stop();
  13484. t.join();
  13485. ASSERT_FALSE(svr.is_running());
  13486. });
  13487. svr.wait_until_ready();
  13488. Client cli(HOST, port);
  13489. Headers headers = {{"Accept-Encoding", "gzip"}};
  13490. {
  13491. auto res = cli.Get("/pre-gzipped", headers);
  13492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13493. EXPECT_EQ(StatusCode::OK_200, res->status);
  13494. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13495. EXPECT_EQ("Hello World!", res->body);
  13496. }
  13497. {
  13498. auto res = cli.Get("/negotiated", headers);
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13500. EXPECT_EQ(StatusCode::OK_200, res->status);
  13501. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13502. EXPECT_EQ(plain, res->body);
  13503. }
  13504. }
  13505. #endif
  13506. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13507. // the same message as the comma-joined one, so both have to be read the same
  13508. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13509. // single gzip coding, and a body the sender says was encoded twice was handed
  13510. // back after one pass, still compressed but presented as decoded.
  13511. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13512. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13513. Server svr;
  13514. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13515. res.set_content(body, "image/jpeg");
  13516. res.headers.emplace("Content-Encoding", "gzip");
  13517. res.headers.emplace("Content-Encoding", "gzip");
  13518. });
  13519. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13520. res.set_content(body, "image/jpeg");
  13521. res.set_header("Content-Encoding", "gzip, gzip");
  13522. });
  13523. auto port = svr.bind_to_any_port(HOST);
  13524. thread t = thread([&]() { svr.listen_after_bind(); });
  13525. auto se = detail::scope_exit([&] {
  13526. svr.stop();
  13527. t.join();
  13528. ASSERT_FALSE(svr.is_running());
  13529. });
  13530. svr.wait_until_ready();
  13531. Client cli(HOST, port);
  13532. // Two codings is not something cpp-httplib decodes, so both representations
  13533. // take the pass-through path rather than one of them being gunzipped once.
  13534. for (const char *path : {"/split", "/joined"}) {
  13535. auto res = cli.Get(path);
  13536. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13537. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13538. EXPECT_EQ(body, res->body) << path;
  13539. }
  13540. }
  13541. // Regression test for DoS vulnerability: a malicious server sending a response
  13542. // without Content-Length header must not cause unbounded memory consumption on
  13543. // the client side. The client should stop reading after a reasonable limit,
  13544. // similar to the server-side set_payload_max_length protection.
  13545. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13546. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13547. #ifndef _WIN32
  13548. signal(SIGPIPE, SIG_IGN);
  13549. #endif
  13550. auto server_thread = std::thread([] {
  13551. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13552. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13553. default_socket_options(srv);
  13554. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13555. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13556. sockaddr_in addr{};
  13557. addr.sin_family = AF_INET;
  13558. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13559. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13560. int opt = 1;
  13561. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13562. #ifdef _WIN32
  13563. reinterpret_cast<const char *>(&opt),
  13564. #else
  13565. &opt,
  13566. #endif
  13567. sizeof(opt));
  13568. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13569. ::listen(srv, 1);
  13570. sockaddr_in cli_addr{};
  13571. socklen_t cli_len = sizeof(cli_addr);
  13572. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13573. if (cli != INVALID_SOCKET) {
  13574. char buf[4096];
  13575. ::recv(cli, buf, sizeof(buf), 0);
  13576. // Malicious response: no Content-Length, no chunked encoding
  13577. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13578. "Connection: close\r\n"
  13579. "\r\n";
  13580. ::send(cli,
  13581. #ifdef _WIN32
  13582. static_cast<const char *>(response_header.c_str()),
  13583. static_cast<int>(response_header.size()),
  13584. #else
  13585. response_header.c_str(), response_header.size(),
  13586. #endif
  13587. 0);
  13588. // Send 10MB of data
  13589. std::string chunk(64 * 1024, 'A');
  13590. size_t total_sent = 0;
  13591. while (total_sent < MALICIOUS_DATA_SIZE) {
  13592. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13593. auto sent = ::send(cli,
  13594. #ifdef _WIN32
  13595. static_cast<const char *>(chunk.c_str()),
  13596. static_cast<int>(to_send),
  13597. #else
  13598. chunk.c_str(), to_send,
  13599. #endif
  13600. 0);
  13601. if (sent <= 0) break;
  13602. total_sent += static_cast<size_t>(sent);
  13603. }
  13604. detail::close_socket(cli);
  13605. }
  13606. detail::close_socket(srv);
  13607. });
  13608. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13609. size_t total_read = 0;
  13610. {
  13611. Client cli("127.0.0.1", PORT + 2);
  13612. cli.set_read_timeout(5, 0);
  13613. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13614. auto stream = cli.open_stream("GET", "/malicious");
  13615. ASSERT_TRUE(stream.is_valid());
  13616. char buffer[64 * 1024];
  13617. ssize_t n;
  13618. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13619. total_read += static_cast<size_t>(n);
  13620. }
  13621. } // StreamHandle and Client destroyed here, closing the socket
  13622. server_thread.join();
  13623. // With set_payload_max_length, the client must stop reading before consuming
  13624. // all 10MB. The read loop should be cut off at or near the configured limit.
  13625. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13626. << "Client read " << total_read << " bytes, exceeding the configured "
  13627. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13628. }
  13629. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13630. // the entire response body without truncation.
  13631. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13632. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13633. #ifndef _WIN32
  13634. signal(SIGPIPE, SIG_IGN);
  13635. #endif
  13636. auto server_thread = std::thread([] {
  13637. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13638. default_socket_options(srv);
  13639. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13641. sockaddr_in addr{};
  13642. addr.sin_family = AF_INET;
  13643. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13644. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13645. int opt = 1;
  13646. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13647. #ifdef _WIN32
  13648. reinterpret_cast<const char *>(&opt),
  13649. #else
  13650. &opt,
  13651. #endif
  13652. sizeof(opt));
  13653. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13654. ::listen(srv, 1);
  13655. sockaddr_in cli_addr{};
  13656. socklen_t cli_len = sizeof(cli_addr);
  13657. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13658. if (cli != INVALID_SOCKET) {
  13659. char buf[4096];
  13660. ::recv(cli, buf, sizeof(buf), 0);
  13661. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13662. "Connection: close\r\n"
  13663. "\r\n";
  13664. ::send(cli,
  13665. #ifdef _WIN32
  13666. static_cast<const char *>(response_header.c_str()),
  13667. static_cast<int>(response_header.size()),
  13668. #else
  13669. response_header.c_str(), response_header.size(),
  13670. #endif
  13671. 0);
  13672. std::string chunk(64 * 1024, 'A');
  13673. size_t total_sent = 0;
  13674. while (total_sent < DATA_SIZE) {
  13675. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13676. auto sent = ::send(cli,
  13677. #ifdef _WIN32
  13678. static_cast<const char *>(chunk.c_str()),
  13679. static_cast<int>(to_send),
  13680. #else
  13681. chunk.c_str(), to_send,
  13682. #endif
  13683. 0);
  13684. if (sent <= 0) break;
  13685. total_sent += static_cast<size_t>(sent);
  13686. }
  13687. #ifdef _WIN32
  13688. ::shutdown(cli, SD_SEND);
  13689. #else
  13690. ::shutdown(cli, SHUT_WR);
  13691. #endif
  13692. // Drain until the client closes its end, ensuring all data is delivered
  13693. char drain[1024];
  13694. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13695. detail::close_socket(cli);
  13696. }
  13697. detail::close_socket(srv);
  13698. });
  13699. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13700. size_t total_read = 0;
  13701. {
  13702. Client cli("127.0.0.1", PORT + 2);
  13703. cli.set_read_timeout(5, 0);
  13704. cli.set_payload_max_length(0); // 0 means no limit
  13705. auto stream = cli.open_stream("GET", "/data");
  13706. ASSERT_TRUE(stream.is_valid());
  13707. char buffer[64 * 1024];
  13708. ssize_t n;
  13709. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13710. total_read += static_cast<size_t>(n);
  13711. }
  13712. }
  13713. server_thread.join();
  13714. EXPECT_EQ(total_read, DATA_SIZE)
  13715. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13716. << " bytes without truncation, but only read " << total_read << " bytes.";
  13717. }
  13718. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13719. // enormous Content-Length must not cause the client to pre-allocate a huge
  13720. // response body buffer. The reservation is capped at payload_max_length_, and
  13721. // the read itself fails when the body exceeds the limit.
  13722. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13723. #ifndef _WIN32
  13724. signal(SIGPIPE, SIG_IGN);
  13725. #endif
  13726. auto server_thread = std::thread([] {
  13727. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13728. default_socket_options(srv);
  13729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13730. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13731. sockaddr_in addr{};
  13732. addr.sin_family = AF_INET;
  13733. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13734. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13735. int opt = 1;
  13736. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13737. #ifdef _WIN32
  13738. reinterpret_cast<const char *>(&opt),
  13739. #else
  13740. &opt,
  13741. #endif
  13742. sizeof(opt));
  13743. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13744. ::listen(srv, 1);
  13745. sockaddr_in cli_addr{};
  13746. socklen_t cli_len = sizeof(cli_addr);
  13747. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13748. if (cli != INVALID_SOCKET) {
  13749. char buf[4096];
  13750. ::recv(cli, buf, sizeof(buf), 0);
  13751. // Malicious response: claim a 20GB body but send only a tiny payload.
  13752. std::string response = "HTTP/1.1 200 OK\r\n"
  13753. "Content-Length: 20000000000\r\n"
  13754. "\r\n"
  13755. "abc";
  13756. ::send(cli,
  13757. #ifdef _WIN32
  13758. static_cast<const char *>(response.c_str()),
  13759. static_cast<int>(response.size()),
  13760. #else
  13761. response.c_str(), response.size(),
  13762. #endif
  13763. 0);
  13764. detail::close_socket(cli);
  13765. }
  13766. detail::close_socket(srv);
  13767. });
  13768. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13769. {
  13770. Client cli("127.0.0.1", PORT + 2);
  13771. cli.set_read_timeout(5, 0);
  13772. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13773. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13774. // (server claims more bytes than payload_max_length permits), but it must
  13775. // not exhaust memory before getting there.
  13776. auto res = cli.Get("/malicious");
  13777. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13778. }
  13779. server_thread.join();
  13780. }
  13781. // Verify that content_receiver bypasses the default payload_max_length,
  13782. // allowing streaming downloads larger than 100MB without requiring an explicit
  13783. // set_payload_max_length call.
  13784. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13785. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13786. #ifndef _WIN32
  13787. signal(SIGPIPE, SIG_IGN);
  13788. #endif
  13789. auto server_thread = std::thread([] {
  13790. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13791. default_socket_options(srv);
  13792. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13793. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13794. sockaddr_in addr{};
  13795. addr.sin_family = AF_INET;
  13796. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13797. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13798. int opt = 1;
  13799. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13800. #ifdef _WIN32
  13801. reinterpret_cast<const char *>(&opt),
  13802. #else
  13803. &opt,
  13804. #endif
  13805. sizeof(opt));
  13806. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13807. ::listen(srv, 1);
  13808. sockaddr_in cli_addr{};
  13809. socklen_t cli_len = sizeof(cli_addr);
  13810. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13811. if (cli != INVALID_SOCKET) {
  13812. char buf[4096];
  13813. ::recv(cli, buf, sizeof(buf), 0);
  13814. // Response with Content-Length larger than default 100MB limit
  13815. auto content_length = std::to_string(DATA_SIZE);
  13816. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13817. "Content-Length: " +
  13818. content_length +
  13819. "\r\n"
  13820. "Connection: close\r\n"
  13821. "\r\n";
  13822. ::send(cli,
  13823. #ifdef _WIN32
  13824. static_cast<const char *>(response_header.c_str()),
  13825. static_cast<int>(response_header.size()),
  13826. #else
  13827. response_header.c_str(), response_header.size(),
  13828. #endif
  13829. 0);
  13830. std::string chunk(64 * 1024, 'A');
  13831. size_t total_sent = 0;
  13832. while (total_sent < DATA_SIZE) {
  13833. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13834. auto sent = ::send(cli,
  13835. #ifdef _WIN32
  13836. static_cast<const char *>(chunk.c_str()),
  13837. static_cast<int>(to_send),
  13838. #else
  13839. chunk.c_str(), to_send,
  13840. #endif
  13841. 0);
  13842. if (sent <= 0) break;
  13843. total_sent += static_cast<size_t>(sent);
  13844. }
  13845. detail::close_socket(cli);
  13846. }
  13847. detail::close_socket(srv);
  13848. });
  13849. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13850. size_t total_received = 0;
  13851. {
  13852. Client cli("127.0.0.1", PORT + 2);
  13853. cli.set_read_timeout(10, 0);
  13854. // Do NOT call set_payload_max_length — use the default 100MB limit
  13855. auto res =
  13856. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13857. total_received += data_length;
  13858. return true;
  13859. });
  13860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13861. EXPECT_EQ(StatusCode::OK_200, res->status);
  13862. }
  13863. server_thread.join();
  13864. EXPECT_EQ(total_received, DATA_SIZE)
  13865. << "With content_receiver, the client should read all " << DATA_SIZE
  13866. << " bytes despite the default 100MB payload_max_length, but only read "
  13867. << total_received << " bytes.";
  13868. }
  13869. // Verify that an explicit set_payload_max_length smaller than the response is
  13870. // enforced even when a content_receiver is used.
  13871. TEST(ClientVulnerabilityTest,
  13872. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13873. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13874. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13875. #ifndef _WIN32
  13876. signal(SIGPIPE, SIG_IGN);
  13877. #endif
  13878. auto server_thread = std::thread([] {
  13879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13880. default_socket_options(srv);
  13881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13883. sockaddr_in addr{};
  13884. addr.sin_family = AF_INET;
  13885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13887. int opt = 1;
  13888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13889. #ifdef _WIN32
  13890. reinterpret_cast<const char *>(&opt),
  13891. #else
  13892. &opt,
  13893. #endif
  13894. sizeof(opt));
  13895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13896. ::listen(srv, 1);
  13897. sockaddr_in cli_addr{};
  13898. socklen_t cli_len = sizeof(cli_addr);
  13899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13900. if (cli != INVALID_SOCKET) {
  13901. char buf[4096];
  13902. ::recv(cli, buf, sizeof(buf), 0);
  13903. auto content_length = std::to_string(DATA_SIZE);
  13904. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13905. "Content-Length: " +
  13906. content_length +
  13907. "\r\n"
  13908. "Connection: close\r\n"
  13909. "\r\n";
  13910. ::send(cli,
  13911. #ifdef _WIN32
  13912. static_cast<const char *>(response_header.c_str()),
  13913. static_cast<int>(response_header.size()),
  13914. #else
  13915. response_header.c_str(), response_header.size(),
  13916. #endif
  13917. 0);
  13918. std::string chunk(64 * 1024, 'A');
  13919. size_t total_sent = 0;
  13920. while (total_sent < DATA_SIZE) {
  13921. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13922. auto sent = ::send(cli,
  13923. #ifdef _WIN32
  13924. static_cast<const char *>(chunk.c_str()),
  13925. static_cast<int>(to_send),
  13926. #else
  13927. chunk.c_str(), to_send,
  13928. #endif
  13929. 0);
  13930. if (sent <= 0) break;
  13931. total_sent += static_cast<size_t>(sent);
  13932. }
  13933. detail::close_socket(cli);
  13934. }
  13935. detail::close_socket(srv);
  13936. });
  13937. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13938. size_t total_received = 0;
  13939. {
  13940. Client cli("127.0.0.1", PORT + 2);
  13941. cli.set_read_timeout(10, 0);
  13942. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13943. auto res =
  13944. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13945. total_received += data_length;
  13946. return true;
  13947. });
  13948. // Should fail because 200MB exceeds the explicit 150MB limit
  13949. EXPECT_FALSE(res);
  13950. }
  13951. server_thread.join();
  13952. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13953. << "Client with content_receiver should respect the explicit "
  13954. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13955. << total_received << " bytes.";
  13956. }
  13957. // Verify that an explicit set_payload_max_length larger than the response
  13958. // allows the content_receiver to read all data successfully.
  13959. TEST(ClientVulnerabilityTest,
  13960. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13961. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13962. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13963. #ifndef _WIN32
  13964. signal(SIGPIPE, SIG_IGN);
  13965. #endif
  13966. auto server_thread = std::thread([] {
  13967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13968. default_socket_options(srv);
  13969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13971. sockaddr_in addr{};
  13972. addr.sin_family = AF_INET;
  13973. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13975. int opt = 1;
  13976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13977. #ifdef _WIN32
  13978. reinterpret_cast<const char *>(&opt),
  13979. #else
  13980. &opt,
  13981. #endif
  13982. sizeof(opt));
  13983. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13984. ::listen(srv, 1);
  13985. sockaddr_in cli_addr{};
  13986. socklen_t cli_len = sizeof(cli_addr);
  13987. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13988. if (cli != INVALID_SOCKET) {
  13989. char buf[4096];
  13990. ::recv(cli, buf, sizeof(buf), 0);
  13991. auto content_length = std::to_string(DATA_SIZE);
  13992. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13993. "Content-Length: " +
  13994. content_length +
  13995. "\r\n"
  13996. "Connection: close\r\n"
  13997. "\r\n";
  13998. ::send(cli,
  13999. #ifdef _WIN32
  14000. static_cast<const char *>(response_header.c_str()),
  14001. static_cast<int>(response_header.size()),
  14002. #else
  14003. response_header.c_str(), response_header.size(),
  14004. #endif
  14005. 0);
  14006. std::string chunk(64 * 1024, 'A');
  14007. size_t total_sent = 0;
  14008. while (total_sent < DATA_SIZE) {
  14009. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14010. auto sent = ::send(cli,
  14011. #ifdef _WIN32
  14012. static_cast<const char *>(chunk.c_str()),
  14013. static_cast<int>(to_send),
  14014. #else
  14015. chunk.c_str(), to_send,
  14016. #endif
  14017. 0);
  14018. if (sent <= 0) break;
  14019. total_sent += static_cast<size_t>(sent);
  14020. }
  14021. #ifdef _WIN32
  14022. ::shutdown(cli, SD_SEND);
  14023. #else
  14024. ::shutdown(cli, SHUT_WR);
  14025. #endif
  14026. char drain[1024];
  14027. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14028. detail::close_socket(cli);
  14029. }
  14030. detail::close_socket(srv);
  14031. });
  14032. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14033. size_t total_received = 0;
  14034. {
  14035. Client cli("127.0.0.1", PORT + 2);
  14036. cli.set_read_timeout(10, 0);
  14037. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14038. auto res =
  14039. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14040. total_received += data_length;
  14041. return true;
  14042. });
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. EXPECT_EQ(StatusCode::OK_200, res->status);
  14045. }
  14046. server_thread.join();
  14047. EXPECT_EQ(total_received, DATA_SIZE)
  14048. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14049. << " bytes (larger than " << DATA_SIZE
  14050. << " bytes response), content_receiver should read all data, but only "
  14051. "read "
  14052. << total_received << " bytes.";
  14053. }
  14054. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14055. // Regression test for "zip bomb" attack on the client side: a malicious server
  14056. // sends a small gzip-compressed response that decompresses to a huge payload.
  14057. // The client must enforce payload_max_length on the decompressed size.
  14058. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14059. constexpr size_t DECOMPRESSED_SIZE =
  14060. 10 * 1024 * 1024; // 10MB after decompression
  14061. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14062. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14063. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14064. std::string compressed;
  14065. {
  14066. httplib::detail::gzip_compressor compressor;
  14067. bool ok =
  14068. compressor.compress(uncompressed.data(), uncompressed.size(),
  14069. /*last=*/true, [&](const char *buf, size_t len) {
  14070. compressed.append(buf, len);
  14071. return true;
  14072. });
  14073. ASSERT_TRUE(ok);
  14074. }
  14075. // Sanity: compressed data should be much smaller than the decompressed size
  14076. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14077. #ifndef _WIN32
  14078. signal(SIGPIPE, SIG_IGN);
  14079. #endif
  14080. // Set up the listening socket in the main thread so the server is guaranteed
  14081. // to be ready before the client connects (eliminates race condition).
  14082. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14083. default_socket_options(srv);
  14084. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14085. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14086. sockaddr_in addr{};
  14087. addr.sin_family = AF_INET;
  14088. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14089. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14090. int opt = 1;
  14091. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14092. #ifdef _WIN32
  14093. reinterpret_cast<const char *>(&opt),
  14094. #else
  14095. &opt,
  14096. #endif
  14097. sizeof(opt));
  14098. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14099. ASSERT_EQ(0, ::listen(srv, 1));
  14100. auto server_thread = std::thread([&compressed, srv] {
  14101. sockaddr_in cli_addr{};
  14102. socklen_t cli_len = sizeof(cli_addr);
  14103. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14104. if (cli != INVALID_SOCKET) {
  14105. // Read the full HTTP request (until \r\n\r\n)
  14106. char buf[4096];
  14107. size_t total = 0;
  14108. while (total < sizeof(buf)) {
  14109. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14110. if (n <= 0) break;
  14111. total += static_cast<size_t>(n);
  14112. // Check for end of headers
  14113. if (total >= 4) {
  14114. std::string req(buf, total);
  14115. if (req.find("\r\n\r\n") != std::string::npos) break;
  14116. }
  14117. }
  14118. // Malicious response: gzip-compressed body, no Content-Length
  14119. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14120. "Content-Encoding: gzip\r\n"
  14121. "Connection: close\r\n"
  14122. "\r\n";
  14123. ::send(cli,
  14124. #ifdef _WIN32
  14125. static_cast<const char *>(response_header.c_str()),
  14126. static_cast<int>(response_header.size()),
  14127. #else
  14128. response_header.c_str(), response_header.size(),
  14129. #endif
  14130. 0);
  14131. // Send the compressed payload (small on the wire, huge when decompressed)
  14132. size_t total_sent = 0;
  14133. while (total_sent < compressed.size()) {
  14134. auto to_send = std::min(compressed.size() - total_sent,
  14135. static_cast<size_t>(64 * 1024));
  14136. auto sent =
  14137. ::send(cli,
  14138. #ifdef _WIN32
  14139. static_cast<const char *>(compressed.c_str() + total_sent),
  14140. static_cast<int>(to_send),
  14141. #else
  14142. compressed.c_str() + total_sent, to_send,
  14143. #endif
  14144. 0);
  14145. if (sent <= 0) break;
  14146. total_sent += static_cast<size_t>(sent);
  14147. }
  14148. detail::close_socket(cli);
  14149. }
  14150. });
  14151. auto se = detail::scope_exit([&] {
  14152. detail::close_socket(srv);
  14153. server_thread.join();
  14154. });
  14155. size_t total_decompressed = 0;
  14156. {
  14157. Client cli("127.0.0.1", PORT + 3);
  14158. cli.set_read_timeout(5, 0);
  14159. cli.set_decompress(true);
  14160. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14161. auto stream = cli.open_stream("GET", "/zipbomb");
  14162. ASSERT_TRUE(stream.is_valid());
  14163. char buffer[64 * 1024];
  14164. ssize_t n;
  14165. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14166. total_decompressed += static_cast<size_t>(n);
  14167. }
  14168. }
  14169. // The decompressed size must be capped by payload_max_length. Without
  14170. // protection, the client would decompress the full 10MB from a tiny
  14171. // compressed payload, enabling a zip bomb DoS attack.
  14172. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14173. << "Client decompressed " << total_decompressed
  14174. << " bytes from a gzip response. The decompressed size should be "
  14175. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14176. }
  14177. #endif
  14178. TEST(HostAndPortPropertiesTest, NoSSL) {
  14179. httplib::Client cli("www.google.com", 1234);
  14180. ASSERT_EQ("www.google.com", cli.host());
  14181. ASSERT_EQ(1234, cli.port());
  14182. }
  14183. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14184. httplib::Client cli("www.google.com:1234");
  14185. ASSERT_EQ("www.google.com", cli.host());
  14186. ASSERT_EQ(1234, cli.port());
  14187. }
  14188. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14189. // Port number that overflows int — should not crash, client becomes invalid
  14190. httplib::Client cli("http://www.google.com:99999999999999999999");
  14191. ASSERT_FALSE(cli.is_valid());
  14192. }
  14193. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14194. // Port 99999 exceeds valid range (1-65535) — should not crash
  14195. httplib::Client cli("http://www.google.com:99999");
  14196. ASSERT_FALSE(cli.is_valid());
  14197. auto res = cli.Get("/");
  14198. EXPECT_FALSE(res);
  14199. EXPECT_EQ(Error::Connection, res.error());
  14200. }
  14201. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14202. httplib::Client cli("http://user:pass@localhost:1234");
  14203. ASSERT_FALSE(cli.is_valid());
  14204. EXPECT_FALSE(cli.Get("/"));
  14205. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14206. }
  14207. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14208. httplib::Client cli("http://www.google.com:80abc");
  14209. ASSERT_FALSE(cli.is_valid());
  14210. }
  14211. #ifdef CPPHTTPLIB_SSL_ENABLED
  14212. TEST(HostAndPortPropertiesTest, SSL) {
  14213. httplib::SSLClient cli("www.google.com");
  14214. ASSERT_EQ("www.google.com", cli.host());
  14215. ASSERT_EQ(443, cli.port());
  14216. }
  14217. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14218. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14219. std::string cert;
  14220. read_file(CA_CERT_FILE, cert);
  14221. httplib::SSLClient httplib_client("www.google.com");
  14222. // Load CA store first time
  14223. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14224. // Load CA store second time (update)
  14225. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14226. // Verify client is still valid and can make connections
  14227. httplib_client.enable_server_certificate_verification(true);
  14228. auto res = httplib_client.Get("/");
  14229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14230. // Google may return 200 or 301 depending on various factors
  14231. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14232. res->status == StatusCode::MovedPermanently_301);
  14233. }
  14234. TEST(SSLClientTest, ServerNameIndication_Online) {
  14235. auto host = "httpbingo.org";
  14236. auto path = std::string{"/get"};
  14237. SSLClient cli(host, 443);
  14238. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  14239. SKIP_ON_GATEWAY_ERROR(res);
  14240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14241. ASSERT_EQ(StatusCode::OK_200, res->status);
  14242. }
  14243. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14244. // Use a site that will cause SSL verification failure due to self-signed cert
  14245. SSLClient cli("self-signed.badssl.com", 443);
  14246. cli.enable_server_certificate_verification(true);
  14247. auto res = cli.Get("/");
  14248. ASSERT_TRUE(!res);
  14249. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14250. // Verify backend error is captured for SSLServerVerification
  14251. // This occurs when certificate verification fails
  14252. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14253. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14254. EXPECT_NE(0UL, res.ssl_backend_error());
  14255. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14256. res.ssl_error());
  14257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14258. #if !defined(_WIN32) || \
  14259. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14260. // On non-Windows or when Windows Schannel is disabled, the error comes
  14261. // from OpenSSL's verification
  14262. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14263. res.ssl_backend_error());
  14264. #endif
  14265. #endif
  14266. }
  14267. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14268. // Use a site where hostname doesn't match the certificate
  14269. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14270. SSLClient cli("wrong.host.badssl.com", 443);
  14271. cli.enable_server_certificate_verification(true);
  14272. cli.enable_server_hostname_verification(true);
  14273. auto res = cli.Get("/");
  14274. ASSERT_TRUE(!res);
  14275. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14276. // Verify backend error is captured for hostname verification failure
  14277. EXPECT_NE(0UL, res.ssl_backend_error());
  14278. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14279. res.ssl_error());
  14280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14281. #if !defined(_WIN32) || \
  14282. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14283. // On non-Windows or when Windows Schannel is disabled, the error comes
  14284. // from OpenSSL's hostname verification
  14285. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14286. res.ssl_backend_error());
  14287. #endif
  14288. #endif
  14289. }
  14290. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14291. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14292. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14293. SSLClient cli("www.google.com", 443);
  14294. cli.enable_server_certificate_verification(true);
  14295. auto res = cli.Get("/");
  14296. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14297. }
  14298. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14299. SSLClient cli("www.google.com", 443);
  14300. cli.enable_server_certificate_verification(true);
  14301. cli.enable_windows_certificate_verification(false);
  14302. auto res = cli.Get("/");
  14303. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14304. }
  14305. // The server sends an intermediate cross-signed by a root Windows trusts,
  14306. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14307. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14308. SSLClient cli("accounts.spotify.com", 443);
  14309. auto res = cli.Get("/");
  14310. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14311. << " ssl_backend_error=" << res.ssl_backend_error();
  14312. }
  14313. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14314. // policy status, which no backend reports for a self-signed certificate.
  14315. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14316. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14317. ASSERT_TRUE(svr.is_valid());
  14318. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14319. auto se = detail::scope_exit([&] {
  14320. svr.stop();
  14321. t.join();
  14322. ASSERT_FALSE(svr.is_running());
  14323. });
  14324. svr.wait_until_ready();
  14325. SSLClient cli("127.0.0.1", PORT);
  14326. cli.set_connection_timeout(30);
  14327. auto res = cli.Get("/");
  14328. ASSERT_FALSE(res);
  14329. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14330. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14331. }
  14332. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14333. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14336. auto se = detail::scope_exit([&] {
  14337. svr.stop();
  14338. t.join();
  14339. ASSERT_FALSE(svr.is_running());
  14340. });
  14341. svr.wait_until_ready();
  14342. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14343. {
  14344. ws::WebSocketClient client(url);
  14345. auto res = client.connect();
  14346. ASSERT_FALSE(res);
  14347. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14348. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14349. res.ssl_backend_error());
  14350. }
  14351. {
  14352. ws::WebSocketClient client(url);
  14353. client.enable_windows_certificate_verification(false);
  14354. auto res = client.connect();
  14355. ASSERT_FALSE(res);
  14356. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14357. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14358. res.ssl_backend_error());
  14359. }
  14360. }
  14361. #endif
  14362. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14363. Client cli("https://google.com");
  14364. auto res = cli.Get("/");
  14365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14366. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14367. }
  14368. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14369. SSLClient cli("google.com");
  14370. cli.set_ca_cert_path(CA_CERT_FILE);
  14371. auto res = cli.Get("/");
  14372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14373. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14374. }
  14375. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14376. SSLClient cli("google.com");
  14377. cli.enable_server_certificate_verification(true);
  14378. cli.set_ca_cert_path("hello");
  14379. auto res = cli.Get("/");
  14380. ASSERT_TRUE(!res);
  14381. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14382. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14383. // should be set
  14384. EXPECT_EQ(0, res.ssl_error());
  14385. // Verify backend error is captured for SSLLoadingCerts
  14386. // This error occurs when loading CA certificates fails
  14387. EXPECT_NE(0UL, res.ssl_backend_error());
  14388. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14389. // OpenSSL specific error codes:
  14390. // > openssl errstr 0x80000002
  14391. // error:80000002:system library::No such file or directory
  14392. // > openssl errstr 0xA000126
  14393. // error:0A000126:SSL routines::unexpected eof while reading
  14394. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14395. res.ssl_backend_error() == 0xA000126);
  14396. #endif
  14397. }
  14398. TEST(SSLClientTest, ServerCertificateVerification4) {
  14399. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14400. ASSERT_TRUE(svr.is_valid());
  14401. svr.Get("/test", [&](const Request &, Response &res) {
  14402. res.set_content("test", "text/plain");
  14403. svr.stop();
  14404. ASSERT_TRUE(true);
  14405. });
  14406. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14407. auto se = detail::scope_exit([&] {
  14408. t.join();
  14409. ASSERT_FALSE(svr.is_running());
  14410. });
  14411. svr.wait_until_ready();
  14412. SSLClient cli("127.0.0.1", PORT);
  14413. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14414. cli.enable_server_certificate_verification(true);
  14415. cli.set_connection_timeout(30);
  14416. auto res = cli.Get("/test");
  14417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14418. ASSERT_EQ(StatusCode::OK_200, res->status);
  14419. }
  14420. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14421. std::string cert;
  14422. read_file(CA_CERT_FILE, cert);
  14423. SSLClient cli("google.com");
  14424. cli.load_ca_cert_store(cert.data(), cert.size());
  14425. const auto res = cli.Get("/");
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14428. }
  14429. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14430. // clang-format off
  14431. static constexpr char cert[] =
  14432. "GlobalSign Root CA\n"
  14433. "==================\n"
  14434. "-----BEGIN CERTIFICATE-----\n"
  14435. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14436. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14437. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14438. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14439. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14440. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14441. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14442. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14443. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14444. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14445. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14446. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14447. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14448. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14449. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14450. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14451. "-----END CERTIFICATE-----\n";
  14452. // clang-format on
  14453. SSLClient cli("google.com");
  14454. cli.load_ca_cert_store(cert, sizeof(cert));
  14455. const auto res = cli.Get("/");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14458. }
  14459. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14460. SSLClient cli("www.youtube.com");
  14461. cli.set_ca_cert_path(CA_CERT_FILE);
  14462. cli.enable_server_certificate_verification(true);
  14463. cli.set_follow_location(true);
  14464. auto res = cli.Get("/");
  14465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14466. ASSERT_EQ(StatusCode::OK_200, res->status);
  14467. }
  14468. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14469. SSLClient cli("wWw.YouTube.Com");
  14470. cli.set_ca_cert_path(CA_CERT_FILE);
  14471. cli.enable_server_certificate_verification(true);
  14472. cli.enable_server_hostname_verification(true);
  14473. cli.set_follow_location(true);
  14474. auto res = cli.Get("/");
  14475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14476. ASSERT_EQ(StatusCode::OK_200, res->status);
  14477. }
  14478. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14479. SSLClient cli("gOoGlE.COm");
  14480. cli.enable_server_certificate_verification(true);
  14481. cli.enable_server_hostname_verification(true);
  14482. cli.set_follow_location(true);
  14483. auto res = cli.Get("/");
  14484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14485. ASSERT_EQ(StatusCode::OK_200, res->status);
  14486. }
  14487. TEST(SSLClientTest, Issue2004_Online) {
  14488. Client client("https://google.com");
  14489. client.set_follow_location(true);
  14490. auto res = client.Get("/");
  14491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14492. ASSERT_EQ(StatusCode::OK_200, res->status);
  14493. auto body = res->body;
  14494. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14495. }
  14496. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14497. // Create SSLClient with invalid cert/key to make is_valid() return false
  14498. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14499. "nonexistent_key.pem");
  14500. // is_valid() should be false due to cert loading failure
  14501. ASSERT_FALSE(cli.is_valid());
  14502. auto res = cli.Get("/");
  14503. ASSERT_FALSE(res);
  14504. EXPECT_EQ(Error::SSLConnection, res.error());
  14505. }
  14506. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14507. // Test for Issue #2251: SSL error not properly reported when client cert
  14508. // and key paths are swapped or mismatched
  14509. // This simulates the scenario where user accidentally swaps the cert and key
  14510. // files
  14511. // Using client cert file as private key and vice versa (completely wrong)
  14512. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14513. // Should fail validation due to cert/key mismatch
  14514. ASSERT_FALSE(cli.is_valid());
  14515. // Attempt to make a request should fail with proper error
  14516. auto res = cli.Get("/");
  14517. ASSERT_FALSE(res);
  14518. EXPECT_EQ(Error::SSLConnection, res.error());
  14519. // SSL error should be recorded in the Result object (this is the key fix for
  14520. // Issue #2251)
  14521. auto backend_error = res.ssl_backend_error();
  14522. EXPECT_NE(0u, backend_error);
  14523. }
  14524. // Tests cert/key mismatch detection at the TLS context level
  14525. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14526. // Test that using mismatched cert/key causes connection failure.
  14527. // We verify this at the SSLClient level rather than through internal
  14528. // TLS API functions.
  14529. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14530. cli.enable_server_certificate_verification(false);
  14531. cli.set_connection_timeout(2);
  14532. // The mismatch should cause a connection or handshake error
  14533. auto res = cli.Get("/test");
  14534. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14535. // Either way, the request should fail
  14536. EXPECT_FALSE(res);
  14537. }
  14538. #endif
  14539. #if 0
  14540. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14541. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14542. ASSERT_TRUE(cli != nullptr);
  14543. cli->set_address_family(AF_INET6);
  14544. cli->set_interface("en0");
  14545. auto res = cli->Get("/get");
  14546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14547. ASSERT_EQ(StatusCode::OK_200, res->status);
  14548. }
  14549. #endif
  14550. // Client certificate tests - work with all TLS backends
  14551. #ifdef CPPHTTPLIB_SSL_ENABLED
  14552. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14553. void ClientCertPresent(
  14554. const std::string &client_cert_file,
  14555. const std::string &client_private_key_file,
  14556. const std::string &client_encrypted_private_key_pass = std::string(),
  14557. const ClientCertServerSetup &setup = nullptr) {
  14558. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14559. ASSERT_TRUE(svr.is_valid());
  14560. if (setup) { setup(svr); }
  14561. svr.Get("/test", [&](const Request &req, Response &res) {
  14562. res.set_content("test", "text/plain");
  14563. auto cert = req.peer_cert();
  14564. ASSERT_TRUE(static_cast<bool>(cert));
  14565. std::string common_name = cert.subject_cn();
  14566. EXPECT_EQ("Common Name", common_name);
  14567. });
  14568. auto port = svr.bind_to_any_port(HOST);
  14569. ASSERT_LT(0, port);
  14570. thread t = thread([&]() { svr.listen_after_bind(); });
  14571. auto se = detail::scope_exit([&] {
  14572. svr.stop();
  14573. t.join();
  14574. ASSERT_FALSE(svr.is_running());
  14575. });
  14576. svr.wait_until_ready();
  14577. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14578. client_encrypted_private_key_pass);
  14579. cli.enable_server_certificate_verification(false);
  14580. cli.set_connection_timeout(30);
  14581. auto res = cli.Get("/test");
  14582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14583. ASSERT_EQ(StatusCode::OK_200, res->status);
  14584. }
  14585. TEST(SSLClientServerTest, ClientCertPresent) {
  14586. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14587. }
  14588. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14589. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14590. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14591. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14592. }
  14593. // Expects svr, which must require client certificates, to reject a client
  14594. // that has none
  14595. void RejectsClientWithoutCert(SSLServer &svr) {
  14596. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14597. auto port = svr.bind_to_any_port(HOST);
  14598. ASSERT_LT(0, port);
  14599. thread t = thread([&]() { svr.listen_after_bind(); });
  14600. auto se = detail::scope_exit([&] {
  14601. svr.stop();
  14602. t.join();
  14603. ASSERT_FALSE(svr.is_running());
  14604. });
  14605. svr.wait_until_ready();
  14606. SSLClient cli(HOST, port);
  14607. cli.set_connection_timeout(30);
  14608. // Skip the server certificate check, so that the request fails because the
  14609. // client certificate is missing rather than because cert.pem is not trusted
  14610. cli.enable_server_certificate_verification(false);
  14611. auto res = cli.Get("/test");
  14612. ASSERT_FALSE(res);
  14613. // The server rejects the client during the handshake, or on TLS 1.3 right
  14614. // after it, which the client notices on its first write or read
  14615. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14616. res.error() == Error::Write || res.error() == Error::Read)
  14617. << to_string(res.error());
  14618. if (res.error() == Error::SSLConnection) {
  14619. EXPECT_NE(0UL, res.ssl_backend_error());
  14620. }
  14621. // A rejection noticed on the write keeps the TLS error the write hit
  14622. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14623. }
  14624. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14626. ASSERT_TRUE(svr.is_valid());
  14627. if (setup) { setup(svr); }
  14628. RejectsClientWithoutCert(svr);
  14629. }
  14630. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14631. // A server that requires client certificates must keep requiring them after
  14632. // setup changes it, and keep accepting a client that has one
  14633. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14634. ClientCertMissing(setup);
  14635. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14636. setup);
  14637. }
  14638. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14639. ClientCertStillRequired([](SSLServer &svr) {
  14640. ASSERT_TRUE(tls::set_verify_callback(
  14641. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14642. });
  14643. }
  14644. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14645. ClientCertStillRequired([](SSLServer &svr) {
  14646. ASSERT_TRUE(tls::set_verify_callback(
  14647. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14648. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14649. });
  14650. }
  14651. // The client verifies the server certificate during the handshake, so a
  14652. // server that fails the check never gets the client certificate, even when a
  14653. // verifier of the client's own accepts it
  14654. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14655. struct Case {
  14656. const char *trusted_ca;
  14657. const char *host;
  14658. Error error;
  14659. };
  14660. // cert2.pem names localhost: the first client does not trust it, and the
  14661. // second trusts it but asks for another name
  14662. for (const auto &c :
  14663. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14664. Case{SERVER_CERT2_FILE, "example.com",
  14665. Error::SSLServerHostnameVerification}}) {
  14666. for (auto with_verifier : {false, true}) {
  14667. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14668. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14669. CLIENT_CA_CERT_FILE);
  14670. ASSERT_TRUE(svr.is_valid());
  14671. std::atomic<bool> got_client_cert{false};
  14672. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14673. [&](const tls::VerifyContext &) {
  14674. got_client_cert = true;
  14675. return true;
  14676. }));
  14677. auto port = svr.bind_to_any_port("127.0.0.1");
  14678. ASSERT_LT(0, port);
  14679. thread t = thread([&] { svr.listen_after_bind(); });
  14680. svr.wait_until_ready();
  14681. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14682. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14683. cli.set_ca_cert_path(c.trusted_ca);
  14684. if (with_verifier) {
  14685. cli.set_server_certificate_verifier(
  14686. [](const tls::VerifyContext &) { return true; });
  14687. }
  14688. auto res = cli.Get("/");
  14689. EXPECT_FALSE(res);
  14690. EXPECT_EQ(c.error, res.error());
  14691. svr.stop();
  14692. t.join();
  14693. EXPECT_FALSE(got_client_cert);
  14694. }
  14695. }
  14696. }
  14697. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14698. std::string cert_pem, key_pem, ca_pem;
  14699. read_file(SERVER_CERT_FILE, cert_pem);
  14700. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14701. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14702. ASSERT_TRUE(
  14703. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14704. }
  14705. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14707. ASSERT_TRUE(svr.is_valid());
  14708. UpdateCertsPemWithClientCA(svr);
  14709. RejectsClientWithoutCert(svr);
  14710. }
  14711. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14712. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14713. }
  14714. // A TLS error from one request must not show up in a later request's Result
  14715. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14717. ASSERT_TRUE(svr.is_valid());
  14718. svr.Get("/test", [](const Request &, Response &res) {
  14719. res.set_content("test", "text/plain");
  14720. });
  14721. auto port = svr.bind_to_any_port(HOST);
  14722. ASSERT_LT(0, port);
  14723. thread t = thread([&]() { svr.listen_after_bind(); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. ASSERT_FALSE(svr.is_running());
  14728. });
  14729. svr.wait_until_ready();
  14730. SSLClient cli(HOST, port);
  14731. cli.set_connection_timeout(30);
  14732. cli.enable_server_hostname_verification(false);
  14733. // cert.pem is not trusted, so the handshake fails
  14734. ASSERT_FALSE(cli.Get("/test"));
  14735. cli.enable_server_certificate_verification(false);
  14736. auto res = cli.Get("/test");
  14737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14738. EXPECT_EQ(0, res.ssl_error());
  14739. EXPECT_EQ(0UL, res.ssl_backend_error());
  14740. }
  14741. // PEM memory-based constructor tests (works with all TLS backends).
  14742. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14743. // terminator after it.
  14744. void PemMemoryClientCertPresent(
  14745. const std::string &client_cert_file,
  14746. const std::string &client_private_key_file,
  14747. const std::string &client_encrypted_private_key_pass = std::string(),
  14748. bool exact_size = false) {
  14749. // Read PEM files into memory
  14750. std::string server_cert_pem, server_key_pem;
  14751. std::string client_ca_pem;
  14752. std::string client_cert_pem, client_key_pem;
  14753. read_file(SERVER_CERT_FILE, server_cert_pem);
  14754. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14755. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14756. read_file(client_cert_file, client_cert_pem);
  14757. read_file(client_private_key_file, client_key_pem);
  14758. std::list<std::vector<char>> exact_copies;
  14759. auto data = [&](const std::string &pem) -> const char * {
  14760. if (!exact_size) { return pem.c_str(); }
  14761. exact_copies.emplace_back(pem.begin(), pem.end());
  14762. return exact_copies.back().data();
  14763. };
  14764. // Create server with PEM memory
  14765. SSLServer::PemMemory server_pem = {
  14766. data(server_cert_pem),
  14767. server_cert_pem.size(),
  14768. data(server_key_pem),
  14769. server_key_pem.size(),
  14770. data(client_ca_pem),
  14771. client_ca_pem.size(),
  14772. nullptr // no password for server key
  14773. };
  14774. SSLServer svr(server_pem);
  14775. ASSERT_TRUE(svr.is_valid());
  14776. svr.Get("/test", [&](const Request &req, Response &res) {
  14777. res.set_content("test", "text/plain");
  14778. auto cert = req.peer_cert();
  14779. ASSERT_TRUE(static_cast<bool>(cert));
  14780. EXPECT_EQ("Common Name", cert.subject_cn());
  14781. });
  14782. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14783. auto se = detail::scope_exit([&] {
  14784. svr.stop();
  14785. t.join();
  14786. ASSERT_FALSE(svr.is_running());
  14787. });
  14788. svr.wait_until_ready();
  14789. // Create client with PEM memory
  14790. const char *password = client_encrypted_private_key_pass.empty()
  14791. ? nullptr
  14792. : client_encrypted_private_key_pass.c_str();
  14793. SSLClient::PemMemory client_pem = {
  14794. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14795. client_key_pem.size(), password};
  14796. SSLClient cli(HOST, PORT, client_pem);
  14797. cli.enable_server_certificate_verification(false);
  14798. cli.set_connection_timeout(30);
  14799. auto res = cli.Get("/test");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. ASSERT_EQ(StatusCode::OK_200, res->status);
  14802. }
  14803. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14804. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14805. }
  14806. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14807. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14808. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14809. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14810. }
  14811. // A server built from PEM memory with a client CA requires client certificates,
  14812. // also when the CA is a NUL-terminated string passed with a length of 0
  14813. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14814. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14815. read_file(SERVER_CERT_FILE, server_cert_pem);
  14816. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14817. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14818. SSLServer::PemMemory server_pem = {
  14819. server_cert_pem.c_str(),
  14820. server_cert_pem.size(),
  14821. server_key_pem.c_str(),
  14822. server_key_pem.size(),
  14823. client_ca_pem.c_str(),
  14824. client_ca_pem.size(),
  14825. nullptr // no password for server key
  14826. };
  14827. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14828. SCOPED_TRACE(client_ca_pem_len);
  14829. server_pem.client_ca_pem_len = client_ca_pem_len;
  14830. SSLServer svr(server_pem);
  14831. ASSERT_TRUE(svr.is_valid());
  14832. RejectsClientWithoutCert(svr);
  14833. }
  14834. // An empty CA fails to load instead of turning the check off
  14835. server_pem.client_ca_pem = "";
  14836. server_pem.client_ca_pem_len = 0;
  14837. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14838. }
  14839. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14840. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14841. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14842. true);
  14843. }
  14844. // A length shorter than the PEM cuts it short, so it no longer loads
  14845. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14846. std::string cert, key;
  14847. read_file(SERVER_CERT_FILE, cert);
  14848. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14849. for (auto cut_cert : {true, false}) {
  14850. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14851. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14852. SSLServer::PemMemory server_pem = {
  14853. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14854. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14855. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14856. key_len, nullptr};
  14857. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14858. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14859. key.c_str(), key_len, nullptr};
  14860. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14861. }
  14862. }
  14863. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14864. class NoListenSSLServer : public SSLServer {
  14865. public:
  14866. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14867. const char *client_ca_cert_file_path,
  14868. const char *client_ca_cert_dir_path = nullptr)
  14869. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14870. client_ca_cert_dir_path),
  14871. stop_(false) {}
  14872. std::atomic_bool stop_;
  14873. private:
  14874. bool process_and_close_socket(socket_t /*sock*/) override {
  14875. // Don't create SSL context
  14876. while (!stop_.load()) {
  14877. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14878. }
  14879. return true;
  14880. }
  14881. };
  14882. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14883. CLIENT_CA_CERT_FILE);
  14884. ASSERT_TRUE(svr.is_valid());
  14885. // Keep-alive parking would bypass the override.
  14886. svr.set_keep_alive_parking(false);
  14887. svr.Get("/test", [&](const Request &, Response &res) {
  14888. res.set_content("test", "text/plain");
  14889. });
  14890. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14891. auto se = detail::scope_exit([&] {
  14892. svr.stop_ = true;
  14893. svr.stop();
  14894. t.join();
  14895. ASSERT_FALSE(svr.is_running());
  14896. });
  14897. svr.wait_until_ready();
  14898. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14899. cli.enable_server_certificate_verification(false);
  14900. cli.set_connection_timeout(1);
  14901. auto res = cli.Get("/test");
  14902. ASSERT_TRUE(!res);
  14903. EXPECT_EQ(Error::SSLConnection, res.error());
  14904. // Timeout results in WantRead error code (maps to backend-specific value)
  14905. EXPECT_NE(0, res.ssl_error());
  14906. }
  14907. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14908. // Test SSLServer with client certificate verification using the standard
  14909. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14911. CLIENT_CA_CERT_DIR);
  14912. ASSERT_TRUE(svr.is_valid());
  14913. svr.Get("/test", [&](const Request &req, Response &res) {
  14914. res.set_content("test", "text/plain");
  14915. auto cert = req.peer_cert();
  14916. ASSERT_TRUE(static_cast<bool>(cert));
  14917. auto common_name = cert.subject_cn();
  14918. EXPECT_EQ("Common Name", common_name);
  14919. });
  14920. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14921. auto se = detail::scope_exit([&] {
  14922. svr.stop();
  14923. t.join();
  14924. ASSERT_FALSE(svr.is_running());
  14925. });
  14926. svr.wait_until_ready();
  14927. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14928. cli.enable_server_certificate_verification(false);
  14929. cli.set_connection_timeout(30);
  14930. auto res = cli.Get("/test");
  14931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14932. ASSERT_EQ(StatusCode::OK_200, res->status);
  14933. }
  14934. // Test verify_hostname on every backend: a host is named by a SAN only
  14935. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14936. using namespace httplib::tls;
  14937. // We need a running server to test against
  14938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14939. ASSERT_TRUE(svr.is_valid());
  14940. svr.Get("/test", [](const Request &, Response &res) {
  14941. res.set_content("ok", "text/plain");
  14942. });
  14943. thread t([&]() { svr.listen(HOST, PORT); });
  14944. auto se = detail::scope_exit([&] {
  14945. svr.stop();
  14946. t.join();
  14947. });
  14948. svr.wait_until_ready();
  14949. bool verify_callback_called = false;
  14950. bool verify_result_wrong = false;
  14951. SSLClient cli(HOST, PORT);
  14952. cli.enable_server_certificate_verification(true);
  14953. cli.set_ca_cert_path(CA_CERT_FILE);
  14954. cli.set_connection_timeout(5);
  14955. // Note: Test certificate has CN="Common Name", not "localhost"
  14956. bool verify_result_cn = false;
  14957. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14958. verify_callback_called = true;
  14959. if (!ctx.cert) return false;
  14960. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14961. verify_result_cn = ctx.check_hostname("Common Name");
  14962. // Test 2: wrong hostname should not match
  14963. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14964. return true; // Accept for the purpose of this test
  14965. });
  14966. auto res = cli.Get("/test");
  14967. // The request may succeed or fail depending on cert configuration
  14968. // but the callback should have been called
  14969. ASSERT_TRUE(verify_callback_called)
  14970. << "Verify callback should have been called";
  14971. EXPECT_FALSE(verify_result_cn)
  14972. << "verify_hostname must not match the certificate CN (no SAN)";
  14973. // Wrong hostname should not match
  14974. EXPECT_FALSE(verify_result_wrong)
  14975. << "verify_hostname should not match 'wronghost.example.com'";
  14976. }
  14977. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14978. // backend verifies it.
  14979. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14980. // Certificate CN is "localhost" and it carries no SAN.
  14981. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14982. ASSERT_TRUE(svr.is_valid());
  14983. svr.Get("/test", [](const Request &, Response &res) {
  14984. res.set_content("ok", "text/plain");
  14985. });
  14986. auto port = svr.bind_to_any_port(HOST);
  14987. thread t([&]() { svr.listen_after_bind(); });
  14988. auto se = detail::scope_exit([&] {
  14989. svr.stop();
  14990. t.join();
  14991. });
  14992. svr.wait_until_ready();
  14993. SSLClient cli("localhost", port);
  14994. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14995. cli.enable_server_certificate_verification(true);
  14996. cli.set_connection_timeout(5);
  14997. auto res = cli.Get("/test");
  14998. ASSERT_FALSE(res);
  14999. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15000. // The same certificate is accepted once host name verification is off, so the
  15001. // failure above is the host name and not the chain.
  15002. cli.enable_server_hostname_verification(false);
  15003. res = cli.Get("/test");
  15004. ASSERT_TRUE(res) << to_string(res.error());
  15005. EXPECT_EQ(StatusCode::OK_200, res->status);
  15006. }
  15007. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15008. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15009. // X509_check_ip behavior and must hold for every backend.
  15010. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15011. using namespace httplib::tls;
  15012. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15013. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15014. ASSERT_TRUE(svr.is_valid());
  15015. svr.Get("/test", [](const Request &, Response &res) {
  15016. res.set_content("ok", "text/plain");
  15017. });
  15018. thread t([&]() { svr.listen(HOST, PORT); });
  15019. auto se = detail::scope_exit([&] {
  15020. svr.stop();
  15021. t.join();
  15022. });
  15023. svr.wait_until_ready();
  15024. bool verify_callback_called = false;
  15025. bool ip_matched_via_cn = true;
  15026. SSLClient cli(HOST, PORT);
  15027. cli.enable_server_certificate_verification(true);
  15028. cli.set_ca_cert_path(CA_CERT_FILE);
  15029. cli.set_connection_timeout(5);
  15030. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15031. verify_callback_called = true;
  15032. if (!ctx.cert) return false;
  15033. // The IP appears only in the CN, so it must NOT be accepted.
  15034. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15035. return true; // Accept for the purpose of this test
  15036. });
  15037. cli.Get("/test");
  15038. ASSERT_TRUE(verify_callback_called)
  15039. << "Verify callback should have been called";
  15040. EXPECT_FALSE(ip_matched_via_cn)
  15041. << "An IP host must not be authenticated via the certificate CN";
  15042. }
  15043. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15044. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15045. using namespace httplib::tls;
  15046. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15047. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15048. ASSERT_TRUE(svr.is_valid());
  15049. svr.Get("/test", [](const Request &, Response &res) {
  15050. res.set_content("ok", "text/plain");
  15051. });
  15052. thread t([&]() { svr.listen(HOST, PORT); });
  15053. auto se = detail::scope_exit([&] {
  15054. svr.stop();
  15055. t.join();
  15056. });
  15057. svr.wait_until_ready();
  15058. bool verify_callback_called = false;
  15059. bool san_matched = false;
  15060. bool wrong_ipv6_matched = true;
  15061. bool cn_ipv6_matched = true;
  15062. SSLClient cli(HOST, PORT);
  15063. cli.enable_server_certificate_verification(true);
  15064. cli.set_ca_cert_path(CA_CERT_FILE);
  15065. cli.set_connection_timeout(5);
  15066. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15067. verify_callback_called = true;
  15068. if (!ctx.cert) return false;
  15069. // Matches the IPv6 iPAddress SAN.
  15070. san_matched = ctx.check_hostname("2001:db8::1");
  15071. // A different IPv6 address must not match.
  15072. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15073. // "::1" lives only in the CN, so it must not be accepted.
  15074. cn_ipv6_matched = ctx.check_hostname("::1");
  15075. return true; // Accept for the purpose of this test
  15076. });
  15077. cli.Get("/test");
  15078. ASSERT_TRUE(verify_callback_called)
  15079. << "Verify callback should have been called";
  15080. EXPECT_TRUE(san_matched)
  15081. << "verify_hostname should match an IPv6 iPAddress SAN";
  15082. EXPECT_FALSE(wrong_ipv6_matched)
  15083. << "verify_hostname should not match a non-matching IPv6 address";
  15084. EXPECT_FALSE(cn_ipv6_matched)
  15085. << "An IPv6 host must not be authenticated via the certificate CN";
  15086. }
  15087. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15088. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15089. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15090. using namespace httplib::tls;
  15091. // SANs: DNS:a.zz, IP:42.46.122.122
  15092. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15093. ASSERT_TRUE(svr.is_valid());
  15094. svr.Get("/test", [](const Request &, Response &res) {
  15095. res.set_content("ok", "text/plain");
  15096. });
  15097. auto port = svr.bind_to_any_port(HOST);
  15098. thread t([&]() { svr.listen_after_bind(); });
  15099. auto se = detail::scope_exit([&] {
  15100. svr.stop();
  15101. t.join();
  15102. });
  15103. svr.wait_until_ready();
  15104. bool verify_callback_called = false;
  15105. bool dns_san_matched = false;
  15106. bool ip_san_matched = false;
  15107. bool ip_matched_via_dns_san = true;
  15108. bool dns_matched_via_ip_san = true;
  15109. bool cn_matched_next_to_dns_san = true;
  15110. SSLClient cli(HOST, port);
  15111. cli.enable_server_certificate_verification(true);
  15112. cli.set_ca_cert_path(CA_CERT_FILE);
  15113. cli.set_connection_timeout(5);
  15114. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15115. verify_callback_called = true;
  15116. if (!ctx.cert) return false;
  15117. dns_san_matched = ctx.check_hostname("a.zz");
  15118. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15119. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15120. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15121. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15122. return true; // Accept for the purpose of this test
  15123. });
  15124. cli.Get("/test");
  15125. ASSERT_TRUE(verify_callback_called)
  15126. << "Verify callback should have been called";
  15127. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15128. EXPECT_TRUE(ip_san_matched)
  15129. << "verify_hostname should match an iPAddress SAN";
  15130. EXPECT_FALSE(ip_matched_via_dns_san)
  15131. << "An IP host must not be authenticated via a dNSName SAN";
  15132. EXPECT_FALSE(dns_matched_via_ip_san)
  15133. << "A DNS host must not be authenticated via an iPAddress SAN";
  15134. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15135. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15136. }
  15137. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15138. // "www.*.example.test" names one host and not every host under example.test.
  15139. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15140. using namespace httplib::tls;
  15141. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15142. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15143. ASSERT_TRUE(svr.is_valid());
  15144. svr.Get("/test", [](const Request &, Response &res) {
  15145. res.set_content("ok", "text/plain");
  15146. });
  15147. auto port = svr.bind_to_any_port(HOST);
  15148. thread t([&]() { svr.listen_after_bind(); });
  15149. auto se = detail::scope_exit([&] {
  15150. svr.stop();
  15151. t.join();
  15152. });
  15153. svr.wait_until_ready();
  15154. bool verify_callback_called = false;
  15155. bool leftmost_wildcard_matched = false;
  15156. bool wildcard_spanned_labels = true;
  15157. bool inner_wildcard_matched = true;
  15158. SSLClient cli(HOST, port);
  15159. cli.enable_server_certificate_verification(true);
  15160. cli.set_ca_cert_path(CA_CERT_FILE);
  15161. cli.set_connection_timeout(5);
  15162. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15163. verify_callback_called = true;
  15164. if (!ctx.cert) return false;
  15165. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15166. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15167. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15168. return true; // Accept for the purpose of this test
  15169. });
  15170. cli.Get("/test");
  15171. ASSERT_TRUE(verify_callback_called)
  15172. << "Verify callback should have been called";
  15173. EXPECT_TRUE(leftmost_wildcard_matched)
  15174. << "A leftmost wildcard should match a single label";
  15175. EXPECT_FALSE(wildcard_spanned_labels)
  15176. << "A wildcard label must not match more than one label";
  15177. EXPECT_FALSE(inner_wildcard_matched)
  15178. << "A wildcard outside the leftmost label must not be honoured";
  15179. }
  15180. // sans() must report each SAN entry under its own type.
  15181. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15182. using namespace httplib::tls;
  15183. // SANs: DNS:a.zz, IP:42.46.122.122
  15184. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15185. ASSERT_TRUE(svr.is_valid());
  15186. svr.Get("/test", [](const Request &, Response &res) {
  15187. res.set_content("ok", "text/plain");
  15188. });
  15189. auto port = svr.bind_to_any_port(HOST);
  15190. thread t([&]() { svr.listen_after_bind(); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. });
  15195. svr.wait_until_ready();
  15196. bool verify_callback_called = false;
  15197. std::vector<SanEntry> sans;
  15198. SSLClient cli(HOST, port);
  15199. cli.enable_server_certificate_verification(true);
  15200. cli.set_ca_cert_path(CA_CERT_FILE);
  15201. cli.set_connection_timeout(5);
  15202. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15203. verify_callback_called = true;
  15204. if (!ctx.cert) return false;
  15205. sans = ctx.sans();
  15206. return true; // Accept for the purpose of this test
  15207. });
  15208. cli.Get("/test");
  15209. ASSERT_TRUE(verify_callback_called)
  15210. << "Verify callback should have been called";
  15211. auto has_san = [&](SanType type, const std::string &value) {
  15212. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15213. return san.type == type && san.value == value;
  15214. });
  15215. };
  15216. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15217. << "sans() should report the dNSName SAN";
  15218. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15219. << "sans() should report the iPAddress SAN";
  15220. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15221. << "sans() must not report the dNSName SAN as an address";
  15222. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15223. << "sans() must not report the iPAddress SAN as a DNS name";
  15224. }
  15225. #endif
  15226. // mbedTLS-specific callback constructor test
  15227. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15228. #ifdef CPPHTTPLIB_SSL_ENABLED
  15229. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15230. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15231. ASSERT_TRUE(svr.is_valid());
  15232. // Set up a handler to verify client certificate is present
  15233. bool client_cert_verified = false;
  15234. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15235. // Verify that client certificate was provided
  15236. client_cert_verified = true;
  15237. res.set_content("success", "text/plain");
  15238. });
  15239. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15240. auto se = detail::scope_exit([&] {
  15241. svr.stop();
  15242. t.join();
  15243. ASSERT_FALSE(svr.is_running());
  15244. });
  15245. svr.wait_until_ready();
  15246. // Client with certificate
  15247. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15248. cli.enable_server_certificate_verification(false);
  15249. cli.set_connection_timeout(30);
  15250. auto res = cli.Get("/test");
  15251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15252. ASSERT_EQ(StatusCode::OK_200, res->status);
  15253. ASSERT_TRUE(client_cert_verified);
  15254. EXPECT_EQ("success", res->body);
  15255. }
  15256. #endif
  15257. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15258. // backends
  15259. #ifdef CPPHTTPLIB_SSL_ENABLED
  15260. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15261. using namespace httplib::tls;
  15262. // Test that when client CA cert file is provided,
  15263. // the server properly requests and validates client certificates
  15264. // Create a server with client authentication
  15265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15266. ASSERT_TRUE(svr.is_valid());
  15267. bool handler_called = false;
  15268. svr.Get("/test", [&](const Request &req, Response &res) {
  15269. handler_called = true;
  15270. // Verify that a client certificate was provided
  15271. auto cert = req.peer_cert();
  15272. ASSERT_TRUE(static_cast<bool>(cert));
  15273. // Get the issuer name
  15274. std::string issuer_str = cert.issuer_name();
  15275. ASSERT_FALSE(issuer_str.empty());
  15276. // The client certificate should be issued by our test CA
  15277. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15278. res.set_content("authenticated", "text/plain");
  15279. });
  15280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15281. auto se = detail::scope_exit([&] {
  15282. svr.stop();
  15283. t.join();
  15284. ASSERT_FALSE(svr.is_running());
  15285. });
  15286. svr.wait_until_ready();
  15287. // Connect with a client certificate issued by the CA
  15288. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15289. cli.enable_server_certificate_verification(false);
  15290. cli.set_connection_timeout(30);
  15291. auto res = cli.Get("/test");
  15292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15293. ASSERT_EQ(StatusCode::OK_200, res->status);
  15294. ASSERT_TRUE(handler_called);
  15295. EXPECT_EQ("authenticated", res->body);
  15296. }
  15297. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15298. using namespace httplib::tls;
  15299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15300. ASSERT_TRUE(svr.is_valid());
  15301. svr.Get("/test", [](const Request &, Response &res) {
  15302. res.set_content("ok", "text/plain");
  15303. });
  15304. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15305. auto se = detail::scope_exit([&] {
  15306. svr.stop();
  15307. t.join();
  15308. });
  15309. svr.wait_until_ready();
  15310. SSLClient cli(HOST, PORT);
  15311. cli.enable_server_certificate_verification(false);
  15312. cli.set_connection_timeout(30);
  15313. bool cert_checked = false;
  15314. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15315. if (ctx.cert) {
  15316. auto sans = ctx.sans();
  15317. // Test certificate may or may not have SANs - just verify the API
  15318. // works If SANs exist, verify the types are valid
  15319. for (const auto &san : sans) {
  15320. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15321. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15322. san.type == SanType::OTHER);
  15323. EXPECT_FALSE(san.value.empty());
  15324. }
  15325. cert_checked = true;
  15326. }
  15327. return true;
  15328. });
  15329. auto res = cli.Get("/test");
  15330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15331. EXPECT_TRUE(cert_checked);
  15332. }
  15333. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15334. using namespace httplib::tls;
  15335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15336. ASSERT_TRUE(svr.is_valid());
  15337. svr.Get("/test", [](const Request &, Response &res) {
  15338. res.set_content("ok", "text/plain");
  15339. });
  15340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15341. auto se = detail::scope_exit([&] {
  15342. svr.stop();
  15343. t.join();
  15344. });
  15345. svr.wait_until_ready();
  15346. SSLClient cli(HOST, PORT);
  15347. cli.enable_server_certificate_verification(false);
  15348. cli.set_connection_timeout(30);
  15349. bool validity_checked = false;
  15350. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15351. if (ctx.cert) {
  15352. time_t not_before = 0, not_after = 0;
  15353. bool result = ctx.validity(not_before, not_after);
  15354. EXPECT_TRUE(result);
  15355. // Verify that not_before < now < not_after for a valid cert
  15356. time_t now = time(nullptr);
  15357. EXPECT_LT(not_before, now);
  15358. EXPECT_GT(not_after, now);
  15359. validity_checked = true;
  15360. }
  15361. return true;
  15362. });
  15363. auto res = cli.Get("/test");
  15364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15365. EXPECT_TRUE(validity_checked);
  15366. }
  15367. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15368. using namespace httplib::tls;
  15369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15370. ASSERT_TRUE(svr.is_valid());
  15371. svr.Get("/test", [](const Request &, Response &res) {
  15372. res.set_content("ok", "text/plain");
  15373. });
  15374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15375. auto se = detail::scope_exit([&] {
  15376. svr.stop();
  15377. t.join();
  15378. });
  15379. svr.wait_until_ready();
  15380. SSLClient cli(HOST, PORT);
  15381. cli.enable_server_certificate_verification(false);
  15382. cli.set_connection_timeout(30);
  15383. bool serial_checked = false;
  15384. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15385. if (ctx.cert) {
  15386. std::string serial = ctx.serial();
  15387. EXPECT_FALSE(serial.empty());
  15388. // Serial should be a hex string
  15389. for (char c : serial) {
  15390. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15391. (c >= 'a' && c <= 'f'));
  15392. }
  15393. serial_checked = true;
  15394. }
  15395. return true;
  15396. });
  15397. auto res = cli.Get("/test");
  15398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15399. EXPECT_TRUE(serial_checked);
  15400. }
  15401. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15402. // Test 1: Valid CA file - no error should be recorded
  15403. {
  15404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15405. CLIENT_CA_CERT_FILE);
  15406. ASSERT_TRUE(svr.is_valid());
  15407. // With valid setup, last_ssl_error should be 0
  15408. EXPECT_EQ(0, svr.ssl_last_error());
  15409. }
  15410. // Test 2: Invalid CA file content
  15411. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15412. {
  15413. // Create a temporary file with completely invalid content
  15414. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15415. {
  15416. std::ofstream ofs(temp_invalid_ca);
  15417. ofs << "This is not a certificate file at all\n";
  15418. ofs << "Just plain text content\n";
  15419. }
  15420. // Create server with invalid CA file
  15421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15422. // Clean up temporary file
  15423. std::remove(temp_invalid_ca);
  15424. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15425. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15426. // Note: SSL_CTX_load_verify_locations typically fails first,
  15427. // but our error handling code path is still exercised
  15428. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15429. }
  15430. }
  15431. TEST(VerifyCallbackTest, VerifyContextFields) {
  15432. using namespace httplib::tls;
  15433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15434. ASSERT_TRUE(svr.is_valid());
  15435. svr.Get("/test", [](const Request &, Response &res) {
  15436. res.set_content("ok", "text/plain");
  15437. });
  15438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. });
  15443. svr.wait_until_ready();
  15444. SSLClient cli(HOST, PORT);
  15445. cli.enable_server_certificate_verification(false);
  15446. cli.set_connection_timeout(30);
  15447. int callback_count = 0;
  15448. bool saw_leaf_cert = false;
  15449. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15450. if (ctx.cert) {
  15451. callback_count++;
  15452. // We should see at least one certificate (the leaf)
  15453. std::string cn = ctx.subject_cn();
  15454. if (!cn.empty()) { saw_leaf_cert = true; }
  15455. // Verify context fields are populated
  15456. EXPECT_NE(ctx.session, nullptr);
  15457. EXPECT_GE(ctx.depth, 0);
  15458. }
  15459. return true;
  15460. });
  15461. auto res = cli.Get("/test");
  15462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15463. EXPECT_GT(callback_count, 0);
  15464. EXPECT_TRUE(saw_leaf_cert);
  15465. }
  15466. // A verifier that accepts runs alongside the built-in verification, and is the
  15467. // only check once that is turned off.
  15468. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15469. using namespace httplib::tls;
  15470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15471. ASSERT_TRUE(svr.is_valid());
  15472. svr.Get("/test", [](const Request &, Response &res) {
  15473. res.set_content("ok", "text/plain");
  15474. });
  15475. auto port = svr.bind_to_any_port(HOST);
  15476. thread t([&]() { svr.listen_after_bind(); });
  15477. auto se = detail::scope_exit([&] {
  15478. svr.stop();
  15479. t.join();
  15480. });
  15481. svr.wait_until_ready();
  15482. SSLClient cli(HOST, port);
  15483. cli.enable_server_hostname_verification(false);
  15484. auto calls = 0;
  15485. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15486. calls++;
  15487. return true;
  15488. });
  15489. // cert.pem is not trusted
  15490. auto res = cli.Get("/test");
  15491. ASSERT_FALSE(res);
  15492. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15493. EXPECT_GT(calls, 0);
  15494. cli.enable_server_certificate_verification(false);
  15495. res = cli.Get("/test");
  15496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15497. EXPECT_EQ("ok", res->body);
  15498. }
  15499. // A verifier belongs to the client that set it, not to the thread that set it.
  15500. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15501. using namespace httplib::tls;
  15502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15503. ASSERT_TRUE(svr.is_valid());
  15504. svr.Get("/test", [](const Request &, Response &res) {
  15505. res.set_content("ok", "text/plain");
  15506. });
  15507. auto port = svr.bind_to_any_port(HOST);
  15508. thread t([&]() { svr.listen_after_bind(); });
  15509. auto se = detail::scope_exit([&] {
  15510. svr.stop();
  15511. t.join();
  15512. });
  15513. svr.wait_until_ready();
  15514. auto rejecting_calls = 0;
  15515. SSLClient rejecting(HOST, port);
  15516. rejecting.enable_server_certificate_verification(false);
  15517. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15518. rejecting_calls++;
  15519. return false;
  15520. });
  15521. auto accepting_calls = 0;
  15522. SSLClient accepting(HOST, port);
  15523. accepting.enable_server_certificate_verification(false);
  15524. // Set on another thread than the requests below.
  15525. thread([&]() {
  15526. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15527. accepting_calls++;
  15528. return true;
  15529. });
  15530. }).join();
  15531. // Requested on another thread than the verifier was set on.
  15532. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15533. EXPECT_GT(rejecting_calls, 0);
  15534. auto res = accepting.Get("/test");
  15535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15536. EXPECT_GT(accepting_calls, 0);
  15537. }
  15538. // A verifier replaced while a handshake runs it lives until it returns.
  15539. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15540. using namespace httplib::tls;
  15541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15542. ASSERT_TRUE(svr.is_valid());
  15543. svr.Get("/test", [](const Request &, Response &res) {
  15544. res.set_content("ok", "text/plain");
  15545. });
  15546. auto port = svr.bind_to_any_port(HOST);
  15547. thread t([&]() { svr.listen_after_bind(); });
  15548. auto se = detail::scope_exit([&] {
  15549. svr.stop();
  15550. t.join();
  15551. });
  15552. svr.wait_until_ready();
  15553. SSLClient cli(HOST, port);
  15554. cli.enable_server_certificate_verification(false);
  15555. std::promise<void> entered;
  15556. std::promise<void> replaced;
  15557. auto replaced_future = replaced.get_future();
  15558. auto first_call = true;
  15559. // Long enough to live on the heap
  15560. std::string expected(64, 'v');
  15561. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15562. if (first_call) {
  15563. first_call = false;
  15564. entered.set_value();
  15565. replaced_future.wait();
  15566. }
  15567. return expected == std::string(64, 'v');
  15568. });
  15569. thread request([&]() {
  15570. auto res = cli.Get("/test");
  15571. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15572. });
  15573. entered.get_future().wait();
  15574. cli.set_server_certificate_verifier(
  15575. [](const VerifyContext &) { return true; });
  15576. replaced.set_value();
  15577. request.join();
  15578. }
  15579. // VerifyContext::session is the same handle the other tls:: functions take.
  15580. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15581. using namespace httplib::tls;
  15582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15583. ASSERT_TRUE(svr.is_valid());
  15584. svr.Get("/test", [](const Request &, Response &res) {
  15585. res.set_content("ok", "text/plain");
  15586. });
  15587. auto port = svr.bind_to_any_port(HOST);
  15588. thread t([&]() { svr.listen_after_bind(); });
  15589. auto se = detail::scope_exit([&] {
  15590. svr.stop();
  15591. t.join();
  15592. });
  15593. svr.wait_until_ready();
  15594. SSLClient cli(HOST, port);
  15595. cli.enable_server_certificate_verification(false);
  15596. session_t verifier_session = nullptr;
  15597. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15598. verifier_session = ctx.session;
  15599. return true;
  15600. });
  15601. session_t session_verifier_session = nullptr;
  15602. cli.set_session_verifier([&](session_t session) {
  15603. session_verifier_session = session;
  15604. return SSLVerifierResponse::NoDecisionMade;
  15605. });
  15606. auto res = cli.Get("/test");
  15607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15608. EXPECT_NE(nullptr, verifier_session);
  15609. EXPECT_EQ(session_verifier_session, verifier_session);
  15610. }
  15611. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15612. using httplib::tls::TlsError;
  15613. // Test that verify_error_to_string returns empty for success
  15614. std::string success_str = TlsError::verify_error_to_string(0);
  15615. EXPECT_TRUE(success_str.empty());
  15616. // Test that verify_error_to_string returns non-empty for error codes
  15617. // Using a common error code (certificate expired)
  15618. std::string error_str =
  15619. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15620. EXPECT_FALSE(error_str.empty());
  15621. }
  15622. TEST(SessionVerifierTest, CertificateAccepted) {
  15623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15624. ASSERT_TRUE(svr.is_valid());
  15625. svr.Get("/test", [](const Request &, Response &res) {
  15626. res.set_content("ok", "text/plain");
  15627. });
  15628. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15629. auto se = detail::scope_exit([&] {
  15630. svr.stop();
  15631. t.join();
  15632. });
  15633. svr.wait_until_ready();
  15634. SSLClient cli(HOST, PORT);
  15635. cli.enable_server_certificate_verification(false);
  15636. cli.set_connection_timeout(30);
  15637. bool callback_called = false;
  15638. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15639. EXPECT_NE(session, nullptr);
  15640. callback_called = true;
  15641. return SSLVerifierResponse::CertificateAccepted;
  15642. });
  15643. auto res = cli.Get("/test");
  15644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15645. EXPECT_EQ(200, res->status);
  15646. EXPECT_TRUE(callback_called);
  15647. }
  15648. TEST(SessionVerifierTest, CertificateRejected) {
  15649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15650. ASSERT_TRUE(svr.is_valid());
  15651. svr.Get("/test", [](const Request &, Response &res) {
  15652. res.set_content("ok", "text/plain");
  15653. });
  15654. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15655. auto se = detail::scope_exit([&] {
  15656. svr.stop();
  15657. t.join();
  15658. });
  15659. svr.wait_until_ready();
  15660. SSLClient cli(HOST, PORT);
  15661. cli.enable_server_certificate_verification(false);
  15662. cli.set_connection_timeout(30);
  15663. bool callback_called = false;
  15664. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15665. EXPECT_NE(session, nullptr);
  15666. callback_called = true;
  15667. return SSLVerifierResponse::CertificateRejected;
  15668. });
  15669. auto res = cli.Get("/test");
  15670. EXPECT_FALSE(res);
  15671. EXPECT_TRUE(callback_called);
  15672. }
  15673. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15675. ASSERT_TRUE(svr.is_valid());
  15676. svr.Get("/test", [](const Request &, Response &res) {
  15677. res.set_content("ok", "text/plain");
  15678. });
  15679. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15680. auto se = detail::scope_exit([&] {
  15681. svr.stop();
  15682. t.join();
  15683. });
  15684. svr.wait_until_ready();
  15685. // NoDecisionMade with verification disabled should succeed (no default check)
  15686. SSLClient cli(HOST, PORT);
  15687. cli.enable_server_certificate_verification(false);
  15688. cli.set_connection_timeout(30);
  15689. bool callback_called = false;
  15690. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15691. EXPECT_NE(session, nullptr);
  15692. callback_called = true;
  15693. return SSLVerifierResponse::NoDecisionMade;
  15694. });
  15695. auto res = cli.Get("/test");
  15696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15697. EXPECT_EQ(200, res->status);
  15698. EXPECT_TRUE(callback_called);
  15699. }
  15700. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15702. ASSERT_TRUE(svr.is_valid());
  15703. svr.Get("/test", [](const Request &, Response &res) {
  15704. res.set_content("ok", "text/plain");
  15705. });
  15706. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15707. auto se = detail::scope_exit([&] {
  15708. svr.stop();
  15709. t.join();
  15710. });
  15711. svr.wait_until_ready();
  15712. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15713. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15714. // so we only check that the request fails, not whether the callback was
  15715. // called.
  15716. SSLClient cli(HOST, PORT);
  15717. cli.enable_server_certificate_verification(true);
  15718. cli.set_connection_timeout(30);
  15719. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15720. EXPECT_NE(session, nullptr);
  15721. return SSLVerifierResponse::NoDecisionMade;
  15722. });
  15723. auto res = cli.Get("/test");
  15724. EXPECT_FALSE(res);
  15725. }
  15726. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15727. // Test SSL server using PemMemory constructor with client CA certificates
  15728. // Read PEM files
  15729. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15730. read_file(SERVER_CERT_FILE, server_cert_pem);
  15731. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15732. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15733. // Create SSLServer with PemMemory constructor including client CA
  15734. SSLServer::PemMemory server_pem = {
  15735. server_cert_pem.c_str(),
  15736. server_cert_pem.size(),
  15737. server_key_pem.c_str(),
  15738. server_key_pem.size(),
  15739. client_ca_pem.c_str(),
  15740. client_ca_pem.size(),
  15741. nullptr // no password for server key
  15742. };
  15743. SSLServer svr(server_pem);
  15744. ASSERT_TRUE(svr.is_valid());
  15745. // No SSL error should be recorded for valid setup
  15746. EXPECT_EQ(0, svr.ssl_last_error());
  15747. // Set up server endpoints
  15748. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15749. res.set_content("ok", "text/plain");
  15750. });
  15751. // Start server in a thread
  15752. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15753. svr.wait_until_ready();
  15754. // Connect with client certificate (using constructor with paths)
  15755. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15756. cli.enable_server_certificate_verification(false);
  15757. auto res = cli.Get("/test-pem-ca");
  15758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15759. EXPECT_EQ(200, res->status);
  15760. EXPECT_EQ("ok", res->body);
  15761. svr.stop();
  15762. server_thread.join();
  15763. }
  15764. #endif
  15765. #ifdef _WIN32
  15766. TEST(CleanupTest, WSACleanup) {
  15767. int ret = WSACleanup();
  15768. ASSERT_EQ(0, ret);
  15769. }
  15770. #endif
  15771. #ifndef CPPHTTPLIB_SSL_ENABLED
  15772. TEST(NoSSLSupport, SimpleInterface) {
  15773. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15774. }
  15775. #endif
  15776. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15777. TEST(InvalidScheme, SimpleInterface) {
  15778. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15779. }
  15780. #endif
  15781. TEST(NoScheme, SimpleInterface) {
  15782. Client cli("yahoo.com:80");
  15783. ASSERT_TRUE(cli.is_valid());
  15784. }
  15785. TEST(SendAPI, SimpleInterface_Online) {
  15786. Client cli("http://yahoo.com");
  15787. Request req;
  15788. req.method = "GET";
  15789. req.path = "/";
  15790. auto res = cli.send(req);
  15791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15792. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15793. }
  15794. TEST(SendAPI, WithParamsInRequest) {
  15795. Server svr;
  15796. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15797. EXPECT_TRUE(req.has_param("test"));
  15798. EXPECT_EQ("test_value", req.get_param_value("test"));
  15799. });
  15800. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. });
  15806. svr.wait_until_ready();
  15807. Client cli(HOST, PORT);
  15808. {
  15809. Request req;
  15810. req.method = "GET";
  15811. req.path = "/";
  15812. req.params.emplace("test", "test_value");
  15813. auto res = cli.send(req);
  15814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15815. }
  15816. {
  15817. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15819. }
  15820. }
  15821. TEST(ClientImplMethods, GetSocketTest) {
  15822. httplib::Server svr;
  15823. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15824. res.status = StatusCode::OK_200;
  15825. });
  15826. auto port = svr.bind_to_any_port("127.0.0.1");
  15827. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15828. auto se = detail::scope_exit([&] {
  15829. svr.stop();
  15830. thread.join();
  15831. ASSERT_FALSE(svr.is_running());
  15832. });
  15833. svr.wait_until_ready();
  15834. {
  15835. httplib::Client cli("127.0.0.1", port);
  15836. cli.set_keep_alive(true);
  15837. // Use the behavior of cpp-httplib of opening the connection
  15838. // only when the first request happens. If that changes,
  15839. // this test would be obsolete.
  15840. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15841. // This also implicitly tests the server. But other tests would fail much
  15842. // earlier than this one to be considered.
  15843. auto res = cli.Get("/");
  15844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15845. EXPECT_EQ(StatusCode::OK_200, res->status);
  15846. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15847. }
  15848. }
  15849. #ifdef CPPHTTPLIB_SSL_ENABLED
  15850. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15851. Client cli("http://yahoo.com");
  15852. auto res = cli.Get("/");
  15853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15854. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15855. cli.set_follow_location(true);
  15856. res = cli.Get("/");
  15857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15858. EXPECT_EQ(StatusCode::OK_200, res->status);
  15859. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15860. }
  15861. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15862. Client cli("https://yahoo.com");
  15863. auto res = cli.Get("/");
  15864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15865. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15866. cli.set_follow_location(true);
  15867. res = cli.Get("/");
  15868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15869. EXPECT_EQ(StatusCode::OK_200, res->status);
  15870. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15871. }
  15872. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15873. Client cli("https://yahoo.com");
  15874. auto res = cli.Get("/");
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. ASSERT_FALSE(!res);
  15877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15878. ASSERT_FALSE(res == nullptr);
  15879. ASSERT_TRUE(res != nullptr);
  15880. EXPECT_EQ(Error::Success, res.error());
  15881. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15882. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15883. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15884. cli.set_follow_location(true);
  15885. res = cli.Get("/");
  15886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15887. EXPECT_EQ(Error::Success, res.error());
  15888. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15889. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15890. EXPECT_EQ(StatusCode::OK_200, res->status);
  15891. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15892. }
  15893. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15894. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15895. Client cli("https://cdnjs.cloudflare.com");
  15896. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15897. Headers{{"Accept-Encoding", "br"}});
  15898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15899. EXPECT_EQ(StatusCode::OK_200, res->status);
  15900. EXPECT_EQ(287630U, res->body.size());
  15901. EXPECT_EQ("application/javascript; charset=utf-8",
  15902. res->get_header_value("Content-Type"));
  15903. }
  15904. #endif
  15905. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15906. #undef REDIR_HOST // Silence compiler warning
  15907. #define REDIR_HOST "https://httpbingo.org"
  15908. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15909. Client cli(REDIR_HOST);
  15910. cli.set_follow_location(true);
  15911. auto res = retry_gateway_errors([&] {
  15912. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15913. });
  15914. SKIP_ON_GATEWAY_ERROR(res);
  15915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15916. EXPECT_EQ(StatusCode::OK_200, res->status);
  15917. }
  15918. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15919. Client cli(REDIR_HOST);
  15920. cli.set_follow_location(true);
  15921. Params params;
  15922. params.emplace("url", "http://example.com");
  15923. params.emplace("status_code", "302");
  15924. auto res = retry_gateway_errors(
  15925. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15926. SKIP_ON_GATEWAY_ERROR(res);
  15927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15928. EXPECT_EQ(StatusCode::OK_200, res->status);
  15929. }
  15930. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15931. Client cli(REDIR_HOST);
  15932. cli.set_follow_location(true);
  15933. Params params;
  15934. params.emplace("url", "http://example.com");
  15935. auto res = retry_gateway_errors([&] {
  15936. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15937. });
  15938. SKIP_ON_GATEWAY_ERROR(res);
  15939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15940. EXPECT_EQ(StatusCode::OK_200, res->status);
  15941. }
  15942. TEST(HttpToHttpsRedirectTest, CertFile) {
  15943. auto ssl_port = PORT + 1;
  15944. Server svr;
  15945. ASSERT_TRUE(svr.is_valid());
  15946. svr.Get("/index", [&](const Request &, Response &res) {
  15947. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15948. "/index");
  15949. svr.stop();
  15950. });
  15951. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15952. ASSERT_TRUE(ssl_svr.is_valid());
  15953. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15954. res.set_content("test", "text/plain");
  15955. ssl_svr.stop();
  15956. });
  15957. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15958. thread t2 =
  15959. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15960. auto se = detail::scope_exit([&] {
  15961. t2.join();
  15962. t.join();
  15963. ASSERT_FALSE(svr.is_running());
  15964. });
  15965. svr.wait_until_ready();
  15966. ssl_svr.wait_until_ready();
  15967. Client cli("127.0.0.1", PORT);
  15968. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15969. cli.enable_server_certificate_verification(true);
  15970. cli.set_follow_location(true);
  15971. cli.set_connection_timeout(30);
  15972. auto res = cli.Get("/index");
  15973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15974. ASSERT_EQ(StatusCode::OK_200, res->status);
  15975. }
  15976. TEST(UppercaseSchemeTest, UsesTLS) {
  15977. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15978. ASSERT_TRUE(ssl_svr.is_valid());
  15979. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15980. res.set_content("test", "text/plain");
  15981. });
  15982. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15983. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15984. Server svr;
  15985. svr.Get("/index", [&](const Request &, Response &res) {
  15986. res.set_redirect(https_url + "/index");
  15987. });
  15988. auto port = svr.bind_to_any_port("127.0.0.1");
  15989. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15990. auto t2 = thread([&] { svr.listen_after_bind(); });
  15991. auto se = detail::scope_exit([&] {
  15992. svr.stop();
  15993. ssl_svr.stop();
  15994. t2.join();
  15995. t.join();
  15996. });
  15997. ssl_svr.wait_until_ready();
  15998. svr.wait_until_ready();
  15999. {
  16000. Client cli(https_url);
  16001. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16002. auto res = cli.Get("/index");
  16003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16004. EXPECT_EQ("test", res->body);
  16005. }
  16006. {
  16007. Client cli("127.0.0.1", port);
  16008. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16009. cli.set_follow_location(true);
  16010. auto res = cli.Get("/index");
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. EXPECT_EQ("test", res->body);
  16013. }
  16014. }
  16015. TEST(SSLClientRedirectTest, CertFile) {
  16016. auto ssl_port = PORT + 1;
  16017. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16018. ASSERT_TRUE(ssl_svr1.is_valid());
  16019. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16020. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16021. "/index");
  16022. ssl_svr1.stop();
  16023. });
  16024. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16025. ASSERT_TRUE(ssl_svr2.is_valid());
  16026. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16027. res.set_content("test", "text/plain");
  16028. ssl_svr2.stop();
  16029. });
  16030. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16031. thread t2 =
  16032. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16033. auto se = detail::scope_exit([&] {
  16034. t2.join();
  16035. t.join();
  16036. ASSERT_FALSE(ssl_svr1.is_running());
  16037. });
  16038. ssl_svr1.wait_until_ready();
  16039. ssl_svr2.wait_until_ready();
  16040. SSLClient cli("127.0.0.1", PORT);
  16041. std::string cert;
  16042. read_file(SERVER_CERT2_FILE, cert);
  16043. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16044. cli.enable_server_certificate_verification(true);
  16045. cli.set_follow_location(true);
  16046. cli.set_connection_timeout(30);
  16047. auto res = cli.Get("/index");
  16048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16049. ASSERT_EQ(StatusCode::OK_200, res->status);
  16050. }
  16051. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16052. // another port, so the client follows it with a new client.
  16053. static Result GetThroughTlsRedirectToDifferentPort(
  16054. const std::function<void(SSLClient &)> &setup,
  16055. const char *target_cert = SERVER_CERT2_FILE,
  16056. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16057. auto ssl_port = PORT + 1;
  16058. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16059. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16060. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16061. "/index");
  16062. });
  16063. SSLServer ssl_svr2(target_cert, target_key);
  16064. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16065. res.set_content("test", "text/plain");
  16066. });
  16067. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16068. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16069. auto se = detail::scope_exit([&] {
  16070. ssl_svr2.stop();
  16071. ssl_svr1.stop();
  16072. t2.join();
  16073. t.join();
  16074. });
  16075. ssl_svr1.wait_until_ready();
  16076. ssl_svr2.wait_until_ready();
  16077. SSLClient cli("127.0.0.1", PORT);
  16078. cli.set_follow_location(true);
  16079. cli.set_connection_timeout(30);
  16080. setup(cli);
  16081. return cli.Get("/index");
  16082. }
  16083. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16084. auto calls = 0;
  16085. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16086. cli.enable_server_certificate_verification(false);
  16087. // Accept the first server only.
  16088. cli.set_session_verifier([&](tls::session_t) {
  16089. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16090. : SSLVerifierResponse::CertificateRejected;
  16091. });
  16092. });
  16093. ASSERT_FALSE(res);
  16094. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16095. EXPECT_EQ(2, calls);
  16096. }
  16097. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16098. std::string pinned;
  16099. auto res = GetThroughTlsRedirectToDifferentPort(
  16100. [&](SSLClient &cli) {
  16101. cli.enable_server_certificate_verification(false);
  16102. // Pin the first certificate seen.
  16103. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16104. if (pinned.empty()) { pinned = ctx.serial(); }
  16105. return ctx.serial() == pinned;
  16106. });
  16107. },
  16108. // A certificate other than the first server's.
  16109. SERVER_CERT_FILE);
  16110. EXPECT_FALSE(res);
  16111. EXPECT_FALSE(pinned.empty());
  16112. }
  16113. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16114. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16115. std::string cert;
  16116. read_file(SERVER_CERT2_FILE, cert);
  16117. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16118. });
  16119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16120. EXPECT_EQ(StatusCode::OK_200, res->status);
  16121. }
  16122. // The target's certificate is signed by the root CA, which the first server's
  16123. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16124. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16125. auto res = GetThroughTlsRedirectToDifferentPort(
  16126. [](SSLClient &cli) {
  16127. std::string root_ca, cert;
  16128. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16129. read_file(SERVER_CERT2_FILE, cert);
  16130. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16131. cli.load_ca_cert_store(cert.data(), cert.size());
  16132. cli.enable_server_hostname_verification(false);
  16133. },
  16134. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16136. EXPECT_EQ(StatusCode::OK_200, res->status);
  16137. }
  16138. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16139. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16140. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16141. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16142. auto res = GetThroughTlsRedirectToDifferentPort(
  16143. [](SSLClient &cli) {
  16144. std::string root_ca, cert;
  16145. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16146. read_file(SERVER_CERT2_FILE, cert);
  16147. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16148. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16149. cli.enable_server_hostname_verification(false);
  16150. },
  16151. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16152. ASSERT_FALSE(res);
  16153. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16154. }
  16155. #endif
  16156. #endif
  16157. #ifdef CPPHTTPLIB_SSL_ENABLED
  16158. // Test that set_ca_cert_store() skips system certs (consistent with
  16159. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16160. // should be trusted - system certs should NOT be loaded.
  16161. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16162. // Load a specific cert that is NOT a system CA cert
  16163. std::string cert;
  16164. read_file(SERVER_CERT2_FILE, cert);
  16165. SSLClient cli("google.com");
  16166. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16167. cli.enable_server_certificate_verification(true);
  16168. // This should FAIL because:
  16169. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16170. // 2. System certs should NOT be loaded when custom store is set
  16171. // If system certs WERE loaded, this would succeed
  16172. auto res = cli.Get("/");
  16173. ASSERT_FALSE(res);
  16174. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16175. }
  16176. // Same as above, but through the native store handle path. Regression test:
  16177. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16178. // merged system certs into the user-provided store.
  16179. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16180. std::string cert;
  16181. read_file(SERVER_CERT2_FILE, cert);
  16182. SSLClient cli("google.com");
  16183. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16184. cli.enable_server_certificate_verification(true);
  16185. auto res = cli.Get("/");
  16186. ASSERT_FALSE(res);
  16187. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16188. }
  16189. // A custom store set via the native handle must still verify a server whose
  16190. // cert it does contain.
  16191. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16192. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16193. ASSERT_TRUE(svr.is_valid());
  16194. svr.Get("/test", [&](const Request &, Response &res) {
  16195. res.set_content("test", "text/plain");
  16196. });
  16197. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16198. auto se = detail::scope_exit([&] {
  16199. svr.stop();
  16200. t.join();
  16201. ASSERT_FALSE(svr.is_running());
  16202. });
  16203. svr.wait_until_ready();
  16204. SSLClient cli("127.0.0.1", PORT);
  16205. std::string cert;
  16206. read_file(SERVER_CERT2_FILE, cert);
  16207. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16208. cli.enable_server_certificate_verification(true);
  16209. cli.set_connection_timeout(30);
  16210. auto res = cli.Get("/test");
  16211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16212. ASSERT_EQ(StatusCode::OK_200, res->status);
  16213. }
  16214. // CA certs loaded through the universal Client must be transferred to the
  16215. // client created internally for following an HTTPS redirect. Regression test:
  16216. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16217. // the CA data for redirect transfer.
  16218. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16219. auto ssl_port = PORT + 1;
  16220. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16221. ASSERT_TRUE(ssl_svr1.is_valid());
  16222. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16223. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16224. "/index");
  16225. });
  16226. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16227. ASSERT_TRUE(ssl_svr2.is_valid());
  16228. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16229. res.set_content("test", "text/plain");
  16230. });
  16231. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16232. thread t2 =
  16233. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16234. auto se = detail::scope_exit([&] {
  16235. ssl_svr2.stop();
  16236. ssl_svr1.stop();
  16237. t2.join();
  16238. t.join();
  16239. ASSERT_FALSE(ssl_svr1.is_running());
  16240. });
  16241. ssl_svr1.wait_until_ready();
  16242. ssl_svr2.wait_until_ready();
  16243. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16244. std::string cert;
  16245. read_file(SERVER_CERT2_FILE, cert);
  16246. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16247. cli.enable_server_certificate_verification(true);
  16248. cli.set_follow_location(true);
  16249. cli.set_connection_timeout(30);
  16250. auto res = cli.Get("/index");
  16251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16252. ASSERT_EQ(StatusCode::OK_200, res->status);
  16253. }
  16254. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16255. // so a host signed by a system CA verifies even though a custom CA is set
  16256. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16257. std::string cert;
  16258. read_file(SERVER_CERT2_FILE, cert);
  16259. SSLClient cli("google.com");
  16260. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16261. cli.enable_system_ca(true);
  16262. cli.enable_server_certificate_verification(true);
  16263. auto res = cli.Get("/");
  16264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16265. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16266. }
  16267. // The custom CA remains effective when combined with the system CA
  16268. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16269. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16270. ASSERT_TRUE(svr.is_valid());
  16271. svr.Get("/test", [&](const Request &, Response &res) {
  16272. res.set_content("test", "text/plain");
  16273. });
  16274. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16275. auto se = detail::scope_exit([&] {
  16276. svr.stop();
  16277. t.join();
  16278. ASSERT_FALSE(svr.is_running());
  16279. });
  16280. svr.wait_until_ready();
  16281. SSLClient cli("127.0.0.1", PORT);
  16282. std::string cert;
  16283. read_file(SERVER_CERT2_FILE, cert);
  16284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16285. cli.enable_system_ca(true);
  16286. cli.enable_server_certificate_verification(true);
  16287. cli.set_connection_timeout(30);
  16288. auto res = cli.Get("/test");
  16289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16290. ASSERT_EQ(StatusCode::OK_200, res->status);
  16291. }
  16292. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16293. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16294. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16295. static CFDictionaryRef
  16296. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16297. const SecTrustSettingsResult *result) {
  16298. auto constraint =
  16299. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16300. &kCFTypeDictionaryValueCallBacks);
  16301. if (policy) {
  16302. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16303. }
  16304. if (policy_string) {
  16305. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16306. kCFStringEncodingUTF8);
  16307. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16308. CFRelease(str);
  16309. }
  16310. if (result) {
  16311. auto number_value = static_cast<SInt32>(*result);
  16312. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16313. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16314. CFRelease(number);
  16315. }
  16316. return constraint;
  16317. }
  16318. static SecTrustSettingsResult
  16319. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16320. auto trust_settings =
  16321. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16322. for (auto constraint : constraints) {
  16323. CFArrayAppendValue(trust_settings, constraint);
  16324. CFRelease(constraint);
  16325. }
  16326. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16327. CFRelease(trust_settings);
  16328. return result;
  16329. }
  16330. // The system CA loader takes a Keychain certificate as a trusted root only
  16331. // when its Trust Settings say so for SSL, not merely because it has some.
  16332. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16333. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16334. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16335. const auto deny = kSecTrustSettingsResultDeny;
  16336. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16337. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16338. auto x509_policy = SecPolicyCreateBasicX509();
  16339. // "Always Trust", which stores no constraint at all
  16340. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16341. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16342. ssl_trust_settings_result(
  16343. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16344. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16345. ssl_trust_settings_result(
  16346. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16347. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16348. ssl_trust_settings_result(
  16349. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16350. // "Never Trust", for everything or for SSL
  16351. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16352. ssl_trust_settings_result(
  16353. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16354. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16355. ssl_trust_settings_result(
  16356. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16357. // Trusted for another policy, for one host, or not at all
  16358. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16359. ssl_trust_settings_result(
  16360. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16361. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16362. ssl_trust_settings_result({make_usage_constraint(
  16363. ssl_policy, "www.example.com", &trust_root)}));
  16364. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16365. ssl_trust_settings_result(
  16366. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16367. // The first constraint that applies to SSL decides
  16368. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16369. ssl_trust_settings_result(
  16370. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16371. make_usage_constraint(nullptr, nullptr, &deny)}));
  16372. CFRelease(x509_policy);
  16373. CFRelease(ssl_policy);
  16374. }
  16375. #endif
  16376. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16377. // skip chain verification entirely (only the certificate identity was
  16378. // checked), so a server presenting an untrusted certificate with a matching
  16379. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16380. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16382. ASSERT_TRUE(svr.is_valid());
  16383. svr.Get("/test", [&](const Request &, Response &res) {
  16384. res.set_content("test", "text/plain");
  16385. });
  16386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16387. auto se = detail::scope_exit([&] {
  16388. svr.stop();
  16389. t.join();
  16390. ASSERT_FALSE(svr.is_running());
  16391. });
  16392. svr.wait_until_ready();
  16393. SSLClient cli("127.0.0.1", PORT);
  16394. std::string cert;
  16395. // A trusted CA that did not sign the server certificate. The server cert
  16396. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16397. // this connection.
  16398. read_file(CLIENT_CA_CERT_FILE, cert);
  16399. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16400. cli.enable_server_certificate_verification(true);
  16401. cli.set_connection_timeout(30);
  16402. auto res = cli.Get("/test");
  16403. ASSERT_FALSE(res);
  16404. }
  16405. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16406. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16407. // CA that failed to come through fails verification instead of trusting them.
  16408. // (wolfSSL does not list the system CAs it loaded.)
  16409. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16410. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16411. ASSERT_TRUE(svr.is_valid());
  16412. auto port = svr.bind_to_any_port("127.0.0.1");
  16413. ASSERT_LT(0, port);
  16414. thread t = thread([&] { svr.listen_after_bind(); });
  16415. auto se = detail::scope_exit([&] {
  16416. svr.stop();
  16417. t.join();
  16418. ASSERT_FALSE(svr.is_running());
  16419. });
  16420. svr.wait_until_ready();
  16421. // The CAs a client trusts once its first request has loaded them
  16422. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16423. Client cli("https://127.0.0.1:" + std::to_string(port));
  16424. setup(cli);
  16425. cli.Get("/");
  16426. return tls::get_ca_names(cli.tls_context()).size();
  16427. };
  16428. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16429. EXPECT_EQ(0u,
  16430. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16431. }
  16432. #endif
  16433. // A TLS setting changed between requests applies to the next one, not just to
  16434. // the next connection
  16435. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16436. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16437. ASSERT_TRUE(svr.is_valid());
  16438. svr.Get("/", [](const Request &req, Response &res) {
  16439. res.set_content(std::to_string(req.remote_port), "text/plain");
  16440. });
  16441. auto port = svr.bind_to_any_port("127.0.0.1");
  16442. ASSERT_LT(0, port);
  16443. thread t = thread([&] { svr.listen_after_bind(); });
  16444. auto se = detail::scope_exit([&] {
  16445. svr.stop();
  16446. t.join();
  16447. ASSERT_FALSE(svr.is_running());
  16448. });
  16449. svr.wait_until_ready();
  16450. SSLClient cli("127.0.0.1", port);
  16451. cli.set_keep_alive(true);
  16452. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16453. cli.enable_server_certificate_verification(false);
  16454. // The port the request went out from, so a new one means a new connection
  16455. auto client_port = [&] {
  16456. auto res = cli.Get("/");
  16457. return res ? res->body : std::string();
  16458. };
  16459. auto last = client_port();
  16460. ASSERT_FALSE(last.empty());
  16461. // Setting a value it already has keeps the connection
  16462. cli.enable_server_certificate_verification(false);
  16463. cli.enable_server_hostname_verification(true);
  16464. EXPECT_EQ(last, client_port());
  16465. cli.enable_server_certificate_verification(true);
  16466. auto res = cli.Get("/");
  16467. EXPECT_FALSE(res);
  16468. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16469. std::string ca;
  16470. read_file(SERVER_CERT2_FILE, ca);
  16471. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16472. last = client_port();
  16473. ASSERT_FALSE(last.empty());
  16474. std::vector<std::function<void()>> setters = {
  16475. [&] { cli.enable_server_hostname_verification(false); },
  16476. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16477. [&] {
  16478. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16479. },
  16480. [&] {
  16481. cli.set_server_certificate_verifier(
  16482. [](const tls::VerifyContext &) { return true; });
  16483. },
  16484. [&] {
  16485. cli.set_session_verifier(
  16486. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16487. },
  16488. };
  16489. for (const auto &setter : setters) {
  16490. setter();
  16491. auto next = client_port();
  16492. ASSERT_FALSE(next.empty());
  16493. EXPECT_NE(last, next);
  16494. last = next;
  16495. }
  16496. cli.set_session_verifier(
  16497. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16498. auto handle = cli.open_stream("GET", "/");
  16499. EXPECT_FALSE(handle.is_valid());
  16500. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16501. }
  16502. // A PEM given to create_ca_store() needs no NUL after it
  16503. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16504. std::string pem;
  16505. read_file(SERVER_CERT2_FILE, pem);
  16506. auto buf = pem + "X";
  16507. auto store = tls::create_ca_store(buf.data(), pem.size());
  16508. EXPECT_TRUE(store != nullptr);
  16509. SSLClient cli("localhost");
  16510. cli.set_ca_cert_store(store);
  16511. }
  16512. // enable_system_ca(false) prevents system CA loading entirely
  16513. TEST(SSLClientTest, DisableSystemCa_Online) {
  16514. SSLClient cli("google.com");
  16515. cli.enable_system_ca(false);
  16516. cli.enable_server_certificate_verification(true);
  16517. auto res = cli.Get("/");
  16518. ASSERT_FALSE(res);
  16519. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16520. // itself when the CA chain is empty
  16521. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16522. res.error() == Error::SSLConnection);
  16523. }
  16524. // The universal Client forwards enable_system_ca()
  16525. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16526. std::string cert;
  16527. read_file(SERVER_CERT2_FILE, cert);
  16528. Client cli("https://google.com");
  16529. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16530. cli.enable_system_ca(true);
  16531. cli.enable_server_certificate_verification(true);
  16532. auto res = cli.Get("/");
  16533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16534. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16535. }
  16536. // The system CA policy must carry over to the client created internally for
  16537. // following a cross-host HTTPS redirect
  16538. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16539. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16540. ASSERT_TRUE(svr.is_valid());
  16541. svr.Get("/index", [&](const Request &, Response &res) {
  16542. res.set_redirect("https://www.google.com/");
  16543. });
  16544. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16545. auto se = detail::scope_exit([&] {
  16546. svr.stop();
  16547. t.join();
  16548. ASSERT_FALSE(svr.is_running());
  16549. });
  16550. svr.wait_until_ready();
  16551. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16552. std::string cert;
  16553. read_file(SERVER_CERT2_FILE, cert);
  16554. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16555. cli.enable_system_ca(true);
  16556. cli.enable_server_certificate_verification(true);
  16557. cli.set_follow_location(true);
  16558. cli.set_connection_timeout(30);
  16559. // Receiving any response proves the redirect client completed the TLS
  16560. // handshake with a system-CA-signed host
  16561. auto res = cli.Get("/index");
  16562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16563. }
  16564. TEST(MultipartFormDataTest, LargeData) {
  16565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16566. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16567. const ContentReader &content_reader) {
  16568. if (req.is_multipart_form_data()) {
  16569. std::vector<FormData> items;
  16570. content_reader(
  16571. [&](const FormData &file) {
  16572. items.push_back(file);
  16573. return true;
  16574. },
  16575. [&](const char *data, size_t data_length) {
  16576. items.back().content.append(data, data_length);
  16577. return true;
  16578. });
  16579. EXPECT_TRUE(std::string(items[0].name) == "document");
  16580. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16581. EXPECT_TRUE(items[0].filename == "2MB_data");
  16582. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16583. EXPECT_TRUE(items[1].name == "hello");
  16584. EXPECT_TRUE(items[1].content == "world");
  16585. EXPECT_TRUE(items[1].filename == "");
  16586. EXPECT_TRUE(items[1].content_type == "");
  16587. } else {
  16588. std::string body;
  16589. content_reader([&](const char *data, size_t data_length) {
  16590. body.append(data, data_length);
  16591. return true;
  16592. });
  16593. }
  16594. });
  16595. auto port = svr.bind_to_any_port(HOST);
  16596. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16597. auto se = detail::scope_exit([&] {
  16598. svr.stop();
  16599. t.join();
  16600. ASSERT_FALSE(svr.is_running());
  16601. });
  16602. svr.wait_until_ready();
  16603. {
  16604. std::string data(1024 * 1024 * 2, '.');
  16605. std::stringstream buffer;
  16606. buffer << data;
  16607. SSLClient cli(HOST, port);
  16608. cli.enable_server_certificate_verification(false);
  16609. UploadFormDataItems items{
  16610. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16611. {"hello", "world", "", ""},
  16612. };
  16613. auto res = cli.Post("/post", items);
  16614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16615. ASSERT_EQ(StatusCode::OK_200, res->status);
  16616. }
  16617. }
  16618. TEST(MultipartFormDataTest, DataProviderItems) {
  16619. std::random_device seed_gen;
  16620. std::mt19937 random(seed_gen());
  16621. std::string rand1;
  16622. rand1.resize(1000);
  16623. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16624. std::string rand2;
  16625. rand2.resize(3000);
  16626. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16628. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16629. const ContentReader &content_reader) {
  16630. ASSERT_FALSE(req.is_multipart_form_data());
  16631. std::string body;
  16632. content_reader([&](const char *data, size_t data_length) {
  16633. body.append(data, data_length);
  16634. return true;
  16635. });
  16636. EXPECT_EQ(body, "");
  16637. });
  16638. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16639. const ContentReader &content_reader) {
  16640. ASSERT_TRUE(req.is_multipart_form_data());
  16641. std::vector<FormData> items;
  16642. content_reader(
  16643. [&](const FormData &file) {
  16644. items.push_back(file);
  16645. return true;
  16646. },
  16647. [&](const char *data, size_t data_length) {
  16648. items.back().content.append(data, data_length);
  16649. return true;
  16650. });
  16651. ASSERT_TRUE(items.size() == 2);
  16652. EXPECT_EQ(std::string(items[0].name), "name1");
  16653. EXPECT_EQ(items[0].content, "Testing123");
  16654. EXPECT_EQ(items[0].filename, "filename1");
  16655. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16656. EXPECT_EQ(items[1].name, "name2");
  16657. EXPECT_EQ(items[1].content, "Testing456");
  16658. EXPECT_EQ(items[1].filename, "");
  16659. EXPECT_EQ(items[1].content_type, "");
  16660. });
  16661. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16662. const ContentReader &content_reader) {
  16663. ASSERT_TRUE(req.is_multipart_form_data());
  16664. std::vector<FormData> items;
  16665. content_reader(
  16666. [&](const FormData &file) {
  16667. items.push_back(file);
  16668. return true;
  16669. },
  16670. [&](const char *data, size_t data_length) {
  16671. items.back().content.append(data, data_length);
  16672. return true;
  16673. });
  16674. ASSERT_TRUE(items.size() == 2);
  16675. EXPECT_EQ(items[0].name, "name3");
  16676. EXPECT_EQ(items[0].content, rand1);
  16677. EXPECT_EQ(items[0].filename, "filename3");
  16678. EXPECT_EQ(items[0].content_type, "");
  16679. EXPECT_EQ(items[1].name, "name4");
  16680. EXPECT_EQ(items[1].content, rand2);
  16681. EXPECT_EQ(items[1].filename, "filename4");
  16682. EXPECT_EQ(items[1].content_type, "");
  16683. });
  16684. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16685. const ContentReader &content_reader) {
  16686. ASSERT_TRUE(req.is_multipart_form_data());
  16687. std::vector<FormData> items;
  16688. content_reader(
  16689. [&](const FormData &file) {
  16690. items.push_back(file);
  16691. return true;
  16692. },
  16693. [&](const char *data, size_t data_length) {
  16694. items.back().content.append(data, data_length);
  16695. return true;
  16696. });
  16697. ASSERT_TRUE(items.size() == 4);
  16698. EXPECT_EQ(std::string(items[0].name), "name1");
  16699. EXPECT_EQ(items[0].content, "Testing123");
  16700. EXPECT_EQ(items[0].filename, "filename1");
  16701. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16702. EXPECT_EQ(items[1].name, "name2");
  16703. EXPECT_EQ(items[1].content, "Testing456");
  16704. EXPECT_EQ(items[1].filename, "");
  16705. EXPECT_EQ(items[1].content_type, "");
  16706. EXPECT_EQ(items[2].name, "name3");
  16707. EXPECT_EQ(items[2].content, rand1);
  16708. EXPECT_EQ(items[2].filename, "filename3");
  16709. EXPECT_EQ(items[2].content_type, "");
  16710. EXPECT_EQ(items[3].name, "name4");
  16711. EXPECT_EQ(items[3].content, rand2);
  16712. EXPECT_EQ(items[3].filename, "filename4");
  16713. EXPECT_EQ(items[3].content_type, "");
  16714. });
  16715. auto port = svr.bind_to_any_port("localhost");
  16716. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. t.join();
  16720. ASSERT_FALSE(svr.is_running());
  16721. });
  16722. svr.wait_until_ready();
  16723. {
  16724. SSLClient cli("localhost", port);
  16725. cli.enable_server_certificate_verification(false);
  16726. UploadFormDataItems items{
  16727. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16728. {"name2", "Testing456", "", ""}, // not a file
  16729. };
  16730. {
  16731. auto res = cli.Post("/post-none", {}, {}, {});
  16732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16733. ASSERT_EQ(StatusCode::OK_200, res->status);
  16734. }
  16735. FormDataProviderItems providers;
  16736. {
  16737. auto res =
  16738. cli.Post("/post-items", {}, items, providers); // empty providers
  16739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16740. ASSERT_EQ(StatusCode::OK_200, res->status);
  16741. }
  16742. providers.push_back({"name3",
  16743. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16744. // test the offset is given correctly at each step
  16745. if (!offset)
  16746. sink.os.write(rand1.data(), 30);
  16747. else if (offset == 30)
  16748. sink.os.write(rand1.data() + 30, 300);
  16749. else if (offset == 330)
  16750. sink.os.write(rand1.data() + 330, 670);
  16751. else if (offset == rand1.size())
  16752. sink.done();
  16753. return true;
  16754. },
  16755. "filename3",
  16756. {}});
  16757. providers.push_back({"name4",
  16758. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16759. // test the offset is given correctly at each step
  16760. if (!offset)
  16761. sink.os.write(rand2.data(), 2000);
  16762. else if (offset == 2000)
  16763. sink.os.write(rand2.data() + 2000, 1);
  16764. else if (offset == 2001)
  16765. sink.os.write(rand2.data() + 2001, 999);
  16766. else if (offset == rand2.size())
  16767. sink.done();
  16768. return true;
  16769. },
  16770. "filename4",
  16771. {}});
  16772. {
  16773. auto res = cli.Post("/post-providers", {}, {}, providers);
  16774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16775. ASSERT_EQ(StatusCode::OK_200, res->status);
  16776. }
  16777. {
  16778. auto res = cli.Post("/post-both", {}, items, providers);
  16779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16780. ASSERT_EQ(StatusCode::OK_200, res->status);
  16781. }
  16782. }
  16783. }
  16784. TEST(MultipartFormDataTest, BadHeader) {
  16785. Server svr;
  16786. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16787. res.set_content("ok", "text/plain");
  16788. });
  16789. thread t = thread([&] { svr.listen(HOST, PORT); });
  16790. auto se = detail::scope_exit([&] {
  16791. svr.stop();
  16792. t.join();
  16793. ASSERT_FALSE(svr.is_running());
  16794. });
  16795. svr.wait_until_ready();
  16796. const std::string body =
  16797. "This is the preamble. It is to be ignored, though it\r\n"
  16798. "is a handy place for composition agents to include an\r\n"
  16799. "explanatory note to non-MIME conformant readers.\r\n"
  16800. "\r\n"
  16801. "\r\n"
  16802. "--simple boundary\r\n"
  16803. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16804. ": BAD...\r\n"
  16805. "\r\n"
  16806. "value1\r\n"
  16807. "--simple boundary\r\n"
  16808. "Content-Disposition: form-data; name=\"field2\"; "
  16809. "filename=\"example.txt\"\r\n"
  16810. "\r\n"
  16811. "value2\r\n"
  16812. "--simple boundary--\r\n"
  16813. "This is the epilogue. It is also to be ignored.\r\n";
  16814. std::string content_type =
  16815. R"(multipart/form-data; boundary="simple boundary")";
  16816. Client cli(HOST, PORT);
  16817. auto res = cli.Post("/post", body, content_type.c_str());
  16818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16819. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16820. }
  16821. TEST(MultipartFormDataTest, WithPreamble) {
  16822. Server svr;
  16823. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16824. res.set_content("ok", "text/plain");
  16825. });
  16826. thread t = thread([&] { svr.listen(HOST, PORT); });
  16827. auto se = detail::scope_exit([&] {
  16828. svr.stop();
  16829. t.join();
  16830. ASSERT_FALSE(svr.is_running());
  16831. });
  16832. svr.wait_until_ready();
  16833. const std::string body =
  16834. "This is the preamble. It is to be ignored, though it\r\n"
  16835. "is a handy place for composition agents to include an\r\n"
  16836. "explanatory note to non-MIME conformant readers.\r\n"
  16837. "\r\n"
  16838. "\r\n"
  16839. "--simple boundary\r\n"
  16840. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16841. "\r\n"
  16842. "value1\r\n"
  16843. "--simple boundary\r\n"
  16844. "Content-Disposition: form-data; name=\"field2\"; "
  16845. "filename=\"example.txt\"\r\n"
  16846. "\r\n"
  16847. "value2\r\n"
  16848. "--simple boundary--\r\n"
  16849. "This is the epilogue. It is also to be ignored.\r\n";
  16850. std::string content_type =
  16851. R"(multipart/form-data; boundary="simple boundary")";
  16852. Client cli(HOST, PORT);
  16853. auto res = cli.Post("/post", body, content_type.c_str());
  16854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16855. EXPECT_EQ(StatusCode::OK_200, res->status);
  16856. }
  16857. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16859. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16860. const ContentReader &content_reader) {
  16861. if (req.is_multipart_form_data()) {
  16862. std::vector<FormData> items;
  16863. content_reader(
  16864. [&](const FormData &file) {
  16865. items.push_back(file);
  16866. return true;
  16867. },
  16868. [&](const char *data, size_t data_length) {
  16869. items.back().content.append(data, data_length);
  16870. return true;
  16871. });
  16872. EXPECT_TRUE(std::string(items[0].name) == "document");
  16873. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16874. EXPECT_TRUE(items[0].filename == "2MB_data");
  16875. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16876. EXPECT_TRUE(items[1].name == "hello");
  16877. EXPECT_TRUE(items[1].content == "world");
  16878. EXPECT_TRUE(items[1].filename == "");
  16879. EXPECT_TRUE(items[1].content_type == "");
  16880. } else {
  16881. std::string body;
  16882. content_reader([&](const char *data, size_t data_length) {
  16883. body.append(data, data_length);
  16884. return true;
  16885. });
  16886. }
  16887. });
  16888. auto port = svr.bind_to_any_port("localhost");
  16889. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16890. auto se = detail::scope_exit([&] {
  16891. svr.stop();
  16892. t.join();
  16893. ASSERT_FALSE(svr.is_running());
  16894. });
  16895. svr.wait_until_ready();
  16896. {
  16897. std::string data(1024 * 1024 * 2, '.');
  16898. std::stringstream buffer;
  16899. buffer << data;
  16900. SSLClient cli("localhost", port);
  16901. cli.enable_server_certificate_verification(false);
  16902. UploadFormDataItems items{
  16903. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16904. {"hello", "world", "", ""},
  16905. };
  16906. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16908. ASSERT_EQ(StatusCode::OK_200, res->status);
  16909. }
  16910. }
  16911. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16912. std::string data(1024 * 1024 * 2, '&');
  16913. std::stringstream buffer;
  16914. buffer << data;
  16915. Client cli("https://localhost:8080");
  16916. UploadFormDataItems items{
  16917. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16918. {"hello", "world", "", ""},
  16919. };
  16920. for (const char &c : " \t\r\n") {
  16921. auto res =
  16922. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16923. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16924. ASSERT_FALSE(res);
  16925. }
  16926. }
  16927. TEST(MultipartFormDataTest, PutFormData) {
  16928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16929. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16930. const ContentReader &content_reader) {
  16931. if (req.is_multipart_form_data()) {
  16932. std::vector<FormData> items;
  16933. content_reader(
  16934. [&](const FormData &file) {
  16935. items.push_back(file);
  16936. return true;
  16937. },
  16938. [&](const char *data, size_t data_length) {
  16939. items.back().content.append(data, data_length);
  16940. return true;
  16941. });
  16942. EXPECT_TRUE(std::string(items[0].name) == "document");
  16943. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16944. EXPECT_TRUE(items[0].filename == "2MB_data");
  16945. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16946. EXPECT_TRUE(items[1].name == "hello");
  16947. EXPECT_TRUE(items[1].content == "world");
  16948. EXPECT_TRUE(items[1].filename == "");
  16949. EXPECT_TRUE(items[1].content_type == "");
  16950. } else {
  16951. std::string body;
  16952. content_reader([&](const char *data, size_t data_length) {
  16953. body.append(data, data_length);
  16954. return true;
  16955. });
  16956. }
  16957. });
  16958. auto port = svr.bind_to_any_port("localhost");
  16959. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16960. auto se = detail::scope_exit([&] {
  16961. svr.stop();
  16962. t.join();
  16963. ASSERT_FALSE(svr.is_running());
  16964. });
  16965. svr.wait_until_ready();
  16966. {
  16967. std::string data(1024 * 1024 * 2, '&');
  16968. std::stringstream buffer;
  16969. buffer << data;
  16970. SSLClient cli("localhost", port);
  16971. cli.enable_server_certificate_verification(false);
  16972. UploadFormDataItems items{
  16973. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16974. {"hello", "world", "", ""},
  16975. };
  16976. auto res = cli.Put("/put", items);
  16977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16978. ASSERT_EQ(StatusCode::OK_200, res->status);
  16979. }
  16980. }
  16981. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16983. svr.Put("/put_customboundary",
  16984. [&](const Request &req, const Response & /*res*/,
  16985. const ContentReader &content_reader) {
  16986. if (req.is_multipart_form_data()) {
  16987. std::vector<FormData> items;
  16988. content_reader(
  16989. [&](const FormData &file) {
  16990. items.push_back(file);
  16991. return true;
  16992. },
  16993. [&](const char *data, size_t data_length) {
  16994. items.back().content.append(data, data_length);
  16995. return true;
  16996. });
  16997. EXPECT_TRUE(std::string(items[0].name) == "document");
  16998. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16999. EXPECT_TRUE(items[0].filename == "2MB_data");
  17000. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17001. EXPECT_TRUE(items[1].name == "hello");
  17002. EXPECT_TRUE(items[1].content == "world");
  17003. EXPECT_TRUE(items[1].filename == "");
  17004. EXPECT_TRUE(items[1].content_type == "");
  17005. } else {
  17006. std::string body;
  17007. content_reader([&](const char *data, size_t data_length) {
  17008. body.append(data, data_length);
  17009. return true;
  17010. });
  17011. }
  17012. });
  17013. auto port = svr.bind_to_any_port("localhost");
  17014. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17015. auto se = detail::scope_exit([&] {
  17016. svr.stop();
  17017. t.join();
  17018. ASSERT_FALSE(svr.is_running());
  17019. });
  17020. svr.wait_until_ready();
  17021. {
  17022. std::string data(1024 * 1024 * 2, '&');
  17023. std::stringstream buffer;
  17024. buffer << data;
  17025. SSLClient cli("localhost", port);
  17026. cli.enable_server_certificate_verification(false);
  17027. UploadFormDataItems items{
  17028. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17029. {"hello", "world", "", ""},
  17030. };
  17031. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17033. ASSERT_EQ(StatusCode::OK_200, res->status);
  17034. }
  17035. }
  17036. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17037. std::string data(1024 * 1024 * 2, '&');
  17038. std::stringstream buffer;
  17039. buffer << data;
  17040. Client cli("https://localhost:8080");
  17041. cli.enable_server_certificate_verification(false);
  17042. UploadFormDataItems items{
  17043. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17044. {"hello", "world", "", ""},
  17045. };
  17046. for (const char &c : " \t\r\n") {
  17047. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17048. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17049. ASSERT_FALSE(res);
  17050. }
  17051. }
  17052. TEST(MultipartFormDataTest, AlternateFilename) {
  17053. auto handled = false;
  17054. Server svr;
  17055. svr.Post("/test", [&](const Request &req, Response &res) {
  17056. ASSERT_EQ(2u, req.form.files.size());
  17057. ASSERT_EQ(1u, req.form.fields.size());
  17058. // Test files
  17059. const auto &file1 = req.form.get_file("file1");
  17060. ASSERT_EQ("file1", file1.name);
  17061. ASSERT_EQ("A.txt", file1.filename);
  17062. ASSERT_EQ("text/plain", file1.content_type);
  17063. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17064. const auto &file2 = req.form.get_file("file2");
  17065. ASSERT_EQ("file2", file2.name);
  17066. ASSERT_EQ("a.html", file2.filename);
  17067. ASSERT_EQ("text/html", file2.content_type);
  17068. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17069. file2.content);
  17070. // Test text field
  17071. const auto &text = req.form.get_field("text");
  17072. ASSERT_EQ("text default", text);
  17073. res.set_content("ok", "text/plain");
  17074. handled = true;
  17075. });
  17076. thread t = thread([&] { svr.listen(HOST, PORT); });
  17077. auto se = detail::scope_exit([&] {
  17078. svr.stop();
  17079. t.join();
  17080. ASSERT_FALSE(svr.is_running());
  17081. ASSERT_TRUE(handled);
  17082. });
  17083. svr.wait_until_ready();
  17084. auto req = "POST /test HTTP/1.1\r\n"
  17085. "Host: localhost\r\n"
  17086. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17087. "Content-Length: 399\r\n"
  17088. "\r\n"
  17089. "----------\r\n"
  17090. "Content-Disposition: form-data; name=\"text\"\r\n"
  17091. "\r\n"
  17092. "text default\r\n"
  17093. "----------\r\n"
  17094. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17095. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17096. "Content-Type: text/plain\r\n"
  17097. "\r\n"
  17098. "Content of a.txt.\r\n"
  17099. "\r\n"
  17100. "----------\r\n"
  17101. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17102. "\"a.html\"\r\n"
  17103. "Content-Type: text/html\r\n"
  17104. "\r\n"
  17105. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17106. "\r\n"
  17107. "------------\r\n";
  17108. ASSERT_TRUE(send_request(1, req));
  17109. }
  17110. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17111. auto handled = false;
  17112. Server svr;
  17113. svr.Post("/test", [&](const Request &req, Response &res) {
  17114. // Case-insensitive "utf-8''" prefix with a long value
  17115. const auto &file = req.form.get_file("file1");
  17116. ASSERT_EQ("file1", file.name);
  17117. // 8000 chars exercises both the Content-Disposition parser and the
  17118. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17119. // Prior to the fix, std::regex_match on this header would cause O(N)
  17120. // stack recursion in libstdc++, leading to SIGSEGV.
  17121. std::string expected_filename(8000, 'A');
  17122. ASSERT_EQ(expected_filename, file.filename);
  17123. res.set_content("ok", "text/plain");
  17124. handled = true;
  17125. });
  17126. thread t = thread([&] { svr.listen(HOST, PORT); });
  17127. auto se = detail::scope_exit([&] {
  17128. svr.stop();
  17129. t.join();
  17130. ASSERT_FALSE(svr.is_running());
  17131. ASSERT_TRUE(handled);
  17132. });
  17133. svr.wait_until_ready();
  17134. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17135. // Regression test for GHSA-qq6v-r583-3h69
  17136. std::string long_filename(8000, 'A');
  17137. std::string body = "----------\r\n"
  17138. "Content-Disposition: form-data; name=\"file1\"; "
  17139. "filename*=\"Utf-8''" +
  17140. long_filename +
  17141. "\"\r\n"
  17142. "\r\n"
  17143. "hello\r\n"
  17144. "------------\r\n";
  17145. auto req = "POST /test HTTP/1.1\r\n"
  17146. "Host: localhost\r\n"
  17147. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17148. "Content-Length: " +
  17149. std::to_string(body.size()) + "\r\n\r\n" + body;
  17150. ASSERT_TRUE(send_request(1, req));
  17151. }
  17152. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17153. auto handled = false;
  17154. Server svr;
  17155. svr.Post("/test", [&](const Request &req, Response &) {
  17156. ASSERT_EQ(2u, req.form.fields.size());
  17157. const auto &text1 = req.form.get_field("text1");
  17158. ASSERT_EQ("text1", text1);
  17159. const auto &text2 = req.form.get_field("text2");
  17160. ASSERT_EQ("text2", text2);
  17161. handled = true;
  17162. });
  17163. thread t = thread([&] { svr.listen(HOST, PORT); });
  17164. auto se = detail::scope_exit([&] {
  17165. svr.stop();
  17166. t.join();
  17167. ASSERT_FALSE(svr.is_running());
  17168. ASSERT_TRUE(handled);
  17169. });
  17170. svr.wait_until_ready();
  17171. auto req = "POST /test HTTP/1.1\r\n"
  17172. "Host: localhost\r\n"
  17173. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17174. "Content-Length: 146\r\n"
  17175. "\r\n----------\r\n"
  17176. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17177. "\r\n"
  17178. "text1"
  17179. "\r\n----------\r\n"
  17180. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17181. "\r\n"
  17182. "text2"
  17183. "\r\n------------";
  17184. std::string response;
  17185. ASSERT_TRUE(send_request(1, req, &response));
  17186. ASSERT_EQ("200", response.substr(9, 3));
  17187. }
  17188. TEST(MultipartFormDataTest, ContentLength) {
  17189. auto handled = false;
  17190. Server svr;
  17191. svr.Post("/test", [&](const Request &req, Response &) {
  17192. ASSERT_EQ(2u, req.form.fields.size());
  17193. const auto &text1 = req.form.get_field("text1");
  17194. ASSERT_EQ("text1", text1);
  17195. const auto &text2 = req.form.get_field("text2");
  17196. ASSERT_EQ("text2", text2);
  17197. handled = true;
  17198. });
  17199. thread t = thread([&] { svr.listen(HOST, PORT); });
  17200. auto se = detail::scope_exit([&] {
  17201. svr.stop();
  17202. t.join();
  17203. ASSERT_FALSE(svr.is_running());
  17204. ASSERT_TRUE(handled);
  17205. });
  17206. svr.wait_until_ready();
  17207. auto req = "POST /test HTTP/1.1\r\n"
  17208. "Host: localhost\r\n"
  17209. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17210. "Content-Length: 167\r\n"
  17211. "\r\n----------\r\n"
  17212. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17213. "Content-Length: 5\r\n"
  17214. "\r\n"
  17215. "text1"
  17216. "\r\n----------\r\n"
  17217. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17218. "\r\n"
  17219. "text2"
  17220. "\r\n------------\r\n";
  17221. std::string response;
  17222. ASSERT_TRUE(send_request(1, req, &response));
  17223. ASSERT_EQ("200", response.substr(9, 3));
  17224. }
  17225. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17226. auto handled = false;
  17227. Server svr;
  17228. svr.Post("/test", [&](const Request &req, Response &) {
  17229. ASSERT_EQ(2u, req.form.fields.size());
  17230. const auto &text1 = req.form.get_field("text1");
  17231. ASSERT_EQ("text1", text1);
  17232. // TODO: Add header access for text fields if needed
  17233. const auto &text2 = req.form.get_field("text2");
  17234. ASSERT_EQ("text2", text2);
  17235. // TODO: Header access for text fields needs to be implemented
  17236. // auto &headers = it->second.headers;
  17237. // ASSERT_EQ(3U, headers.size());
  17238. // auto custom_header = headers.find("x-whatever");
  17239. // ASSERT_TRUE(custom_header != headers.end());
  17240. // ASSERT_NE("customvalue", custom_header->second);
  17241. // ASSERT_EQ("CustomValue", custom_header->second);
  17242. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17243. handled = true;
  17244. });
  17245. thread t = thread([&] { svr.listen(HOST, PORT); });
  17246. auto se = detail::scope_exit([&] {
  17247. svr.stop();
  17248. t.join();
  17249. ASSERT_FALSE(svr.is_running());
  17250. ASSERT_TRUE(handled);
  17251. });
  17252. svr.wait_until_ready();
  17253. auto req = "POST /test HTTP/1.1\r\n"
  17254. "Host: localhost\r\n"
  17255. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17256. "Content-Length: 232\r\n"
  17257. "\r\n----------\r\n"
  17258. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17259. "Content-Length: 5\r\n"
  17260. "X-Test: 1\r\n"
  17261. "\r\n"
  17262. "text1"
  17263. "\r\n----------\r\n"
  17264. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17265. "Content-Type: text/plain\r\n"
  17266. "X-Whatever: CustomValue\r\n"
  17267. "\r\n"
  17268. "text2"
  17269. "\r\n------------\r\n"
  17270. "That should be disregarded. Not even read";
  17271. std::string response;
  17272. ASSERT_TRUE(send_request(1, req, &response));
  17273. ASSERT_EQ("200", response.substr(9, 3));
  17274. }
  17275. TEST(MultipartFormDataTest, LargeHeader) {
  17276. auto handled = false;
  17277. Server svr;
  17278. svr.Post("/test", [&](const Request &req, Response &) {
  17279. ASSERT_EQ(1u, req.form.fields.size());
  17280. const auto &text = req.form.get_field("name1");
  17281. ASSERT_EQ("text1", text);
  17282. handled = true;
  17283. });
  17284. thread t = thread([&] { svr.listen(HOST, PORT); });
  17285. auto se = detail::scope_exit([&] {
  17286. svr.stop();
  17287. t.join();
  17288. ASSERT_FALSE(svr.is_running());
  17289. ASSERT_TRUE(handled);
  17290. });
  17291. svr.wait_until_ready();
  17292. auto boundary = std::string("cpp-httplib-multipart-data");
  17293. std::string content = "--" + boundary +
  17294. "\r\n"
  17295. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17296. "\r\n"
  17297. "text1\r\n"
  17298. "--" +
  17299. boundary + "--\r\n";
  17300. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17301. "Host: localhost\r\n"
  17302. "Content-Type: multipart/form-data;boundary=" +
  17303. boundary +
  17304. "\r\n"
  17305. "Content-Length: " +
  17306. std::to_string(content.size()) +
  17307. "\r\n"
  17308. "Dummy-Header: ";
  17309. std::string header_suffix = "\r\n"
  17310. "\r\n";
  17311. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17312. size_t header_dummy_size =
  17313. read_buff_size -
  17314. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17315. auto header_dummy = std::string(header_dummy_size, '@');
  17316. auto req = header_prefix + header_dummy + header_suffix + content;
  17317. std::string response;
  17318. ASSERT_TRUE(send_request(1, req, &response));
  17319. ASSERT_EQ("200", response.substr(9, 3));
  17320. }
  17321. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17322. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17323. // (not chunked Transfer-Encoding) after the streaming refactor.
  17324. auto handled = false;
  17325. Server svr;
  17326. svr.Post("/upload", [&](const Request &req, Response &res) {
  17327. auto cl_it = req.headers.find("Content-Length");
  17328. EXPECT_TRUE(cl_it != req.headers.end());
  17329. auto te_it = req.headers.find("Transfer-Encoding");
  17330. EXPECT_TRUE(te_it == req.headers.end());
  17331. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17332. res.set_content("ok", "text/plain");
  17333. handled = true;
  17334. });
  17335. auto port = svr.bind_to_any_port(HOST);
  17336. auto t = thread([&] { svr.listen_after_bind(); });
  17337. auto se = detail::scope_exit([&] {
  17338. svr.stop();
  17339. t.join();
  17340. ASSERT_FALSE(svr.is_running());
  17341. ASSERT_TRUE(handled);
  17342. });
  17343. svr.wait_until_ready();
  17344. UploadFormDataItems items = {
  17345. {"field1", "hello", "", "text/plain"},
  17346. {"file1", "world", "test.txt", "application/octet-stream"},
  17347. };
  17348. Client cli(HOST, port);
  17349. auto res = cli.Post("/upload", {}, items);
  17350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17351. EXPECT_EQ(StatusCode::OK_200, res->status);
  17352. }
  17353. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17354. // Verify that make_multipart_content_provider coalesces many small segments
  17355. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17356. constexpr size_t kItemCount = 1000;
  17357. UploadFormDataItems items;
  17358. items.reserve(kItemCount);
  17359. for (size_t i = 0; i < kItemCount; i++) {
  17360. items.push_back(
  17361. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17362. }
  17363. const std::string boundary = "----test-boundary";
  17364. auto content_length = detail::get_multipart_content_length(items, boundary);
  17365. auto provider = detail::make_multipart_content_provider(items, boundary);
  17366. // Drive the provider the same way write_content_with_progress does
  17367. size_t write_count = 0;
  17368. size_t total_bytes = 0;
  17369. DataSink sink;
  17370. size_t offset = 0;
  17371. sink.write = [&](const char *d, size_t l) -> bool {
  17372. (void)d;
  17373. write_count++;
  17374. total_bytes += l;
  17375. offset += l;
  17376. return true;
  17377. };
  17378. sink.is_writable = []() -> bool { return true; };
  17379. while (offset < content_length) {
  17380. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17381. }
  17382. EXPECT_EQ(content_length, total_bytes);
  17383. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17384. // With buffering into 64KB blocks, write_count should be much smaller.
  17385. auto segment_count = 3 * kItemCount + 1;
  17386. EXPECT_LT(write_count, segment_count / 10);
  17387. }
  17388. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17389. // Integration test: send many UploadFormDataItems and verify the server
  17390. // receives all of them correctly (#2410).
  17391. constexpr size_t kItemCount = 500;
  17392. auto handled = false;
  17393. Server svr;
  17394. svr.Post("/upload", [&](const Request &req, Response &res) {
  17395. EXPECT_EQ(kItemCount, req.form.fields.size());
  17396. for (size_t i = 0; i < kItemCount; i++) {
  17397. auto key = "field" + std::to_string(i);
  17398. auto val = "value" + std::to_string(i);
  17399. auto it = req.form.fields.find(key);
  17400. if (it != req.form.fields.end()) {
  17401. EXPECT_EQ(val, it->second.content);
  17402. } else {
  17403. ADD_FAILURE() << "Missing field: " << key;
  17404. }
  17405. }
  17406. res.set_content("ok", "text/plain");
  17407. handled = true;
  17408. });
  17409. auto port = svr.bind_to_any_port(HOST);
  17410. auto t = thread([&] { svr.listen_after_bind(); });
  17411. auto se = detail::scope_exit([&] {
  17412. svr.stop();
  17413. t.join();
  17414. ASSERT_FALSE(svr.is_running());
  17415. ASSERT_TRUE(handled);
  17416. });
  17417. svr.wait_until_ready();
  17418. UploadFormDataItems items;
  17419. items.reserve(kItemCount);
  17420. for (size_t i = 0; i < kItemCount; i++) {
  17421. items.push_back(
  17422. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17423. }
  17424. Client cli(HOST, port);
  17425. auto res = cli.Post("/upload", items);
  17426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17427. EXPECT_EQ(StatusCode::OK_200, res->status);
  17428. }
  17429. TEST(MultipartFormDataTest, MakeFileProvider) {
  17430. // Verify make_file_provider sends a file's contents correctly.
  17431. const std::string file_content(4096, 'Z');
  17432. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17433. {
  17434. std::ofstream ofs(tmp_path, std::ios::binary);
  17435. ofs.write(file_content.data(),
  17436. static_cast<std::streamsize>(file_content.size()));
  17437. }
  17438. auto handled = false;
  17439. Server svr;
  17440. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17441. const ContentReader &content_reader) {
  17442. ASSERT_TRUE(req.is_multipart_form_data());
  17443. std::vector<FormData> items;
  17444. content_reader(
  17445. [&](const FormData &file) {
  17446. items.push_back(file);
  17447. return true;
  17448. },
  17449. [&](const char *data, size_t data_length) {
  17450. items.back().content.append(data, data_length);
  17451. return true;
  17452. });
  17453. ASSERT_EQ(1u, items.size());
  17454. EXPECT_EQ("myfile", items[0].name);
  17455. EXPECT_EQ("data.bin", items[0].filename);
  17456. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17457. EXPECT_EQ(file_content, items[0].content);
  17458. handled = true;
  17459. });
  17460. auto port = svr.bind_to_any_port(HOST);
  17461. auto t = thread([&] { svr.listen_after_bind(); });
  17462. auto se = detail::scope_exit([&] {
  17463. svr.stop();
  17464. t.join();
  17465. ASSERT_FALSE(svr.is_running());
  17466. ASSERT_TRUE(handled);
  17467. std::remove(tmp_path.c_str());
  17468. });
  17469. svr.wait_until_ready();
  17470. FormDataProviderItems providers;
  17471. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17472. "application/octet-stream"));
  17473. Client cli(HOST, port);
  17474. auto res = cli.Post("/upload", {}, {}, providers);
  17475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17476. EXPECT_EQ(StatusCode::OK_200, res->status);
  17477. }
  17478. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17479. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17480. // (100) headers is rejected with a 400 Bad Request response.
  17481. Server svr;
  17482. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17483. res.set_content("ok", "text/plain");
  17484. });
  17485. thread t = thread([&] { svr.listen(HOST, PORT); });
  17486. auto se = detail::scope_exit([&] {
  17487. svr.stop();
  17488. t.join();
  17489. ASSERT_FALSE(svr.is_running());
  17490. });
  17491. svr.wait_until_ready();
  17492. // Build a multipart part with 101 custom headers (exceeding
  17493. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17494. std::stringstream body;
  17495. body << "--simpleboundary\r\n"
  17496. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17497. for (int i = 0; i < 101; i++) {
  17498. body << "X-Custom-Header-" << i << ": value\r\n";
  17499. }
  17500. body << "\r\n"
  17501. << "value1\r\n"
  17502. << "--simpleboundary--\r\n";
  17503. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17504. Client cli(HOST, PORT);
  17505. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17507. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17508. }
  17509. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17510. // A body that never contains the declared boundary must not be accumulated
  17511. // while the parser waits for it. Buffering it would also make every read
  17512. // rescan everything seen so far, which is quadratic in the body size.
  17513. Server svr;
  17514. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17515. res.set_content("ok", "text/plain");
  17516. });
  17517. auto port = svr.bind_to_any_port(HOST);
  17518. thread t = thread([&] { svr.listen_after_bind(); });
  17519. auto se = detail::scope_exit([&] {
  17520. svr.stop();
  17521. t.join();
  17522. ASSERT_FALSE(svr.is_running());
  17523. });
  17524. svr.wait_until_ready();
  17525. Client cli(HOST, port);
  17526. cli.set_read_timeout(60, 0);
  17527. cli.set_write_timeout(60, 0);
  17528. // '-' is the worst case: it matches the first character of the boundary, so
  17529. // every position has to be checked against it.
  17530. auto post_dashes = [&](size_t size) {
  17531. const std::string body(size, '-');
  17532. auto start = std::chrono::steady_clock::now();
  17533. auto res =
  17534. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17535. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17536. std::chrono::steady_clock::now() - start)
  17537. .count();
  17538. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17539. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17540. return ms;
  17541. };
  17542. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17543. // Windows.
  17544. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17545. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17546. // Comparing the two sizes rather than checking an absolute duration keeps
  17547. // this meaningful across build types and CI load, both of which move the
  17548. // absolute numbers by more than an order of magnitude. Four times the bytes
  17549. // costs about four times the time when parsing is linear, and about sixteen
  17550. // times when the body is buffered and rescanned.
  17551. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17552. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17553. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17554. << "ms, which suggests the body is being buffered and rescanned";
  17555. }
  17556. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17557. // A boundary can only be followed by CRLF or by "--", so anything else is
  17558. // malformed no matter what comes next. The parser must say so right away
  17559. // instead of buffering the rest of the declared body.
  17560. Server svr;
  17561. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17562. res.set_content("ok", "text/plain");
  17563. });
  17564. auto port = svr.bind_to_any_port(HOST);
  17565. thread t = thread([&] { svr.listen_after_bind(); });
  17566. auto se = detail::scope_exit([&] {
  17567. svr.stop();
  17568. t.join();
  17569. ASSERT_FALSE(svr.is_running());
  17570. });
  17571. svr.wait_until_ready();
  17572. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17573. // buffers instead of failing would still be waiting for the remaining bytes.
  17574. const std::string body = "--zzzz\r\n"
  17575. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17576. "\r\n"
  17577. "text1"
  17578. "\r\n--zzzzXX";
  17579. const std::string req = "POST /post HTTP/1.1\r\n"
  17580. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17581. "Content-Length: 1048576\r\n"
  17582. "\r\n" +
  17583. body;
  17584. std::string response;
  17585. ASSERT_TRUE(send_request(3, req, &response, port));
  17586. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17587. EXPECT_EQ("400", response.substr(9, 3));
  17588. }
  17589. // Posts a multipart body split into two writes, so that the server sees the
  17590. // split at whatever offset the caller chose, and expects the single "text1"
  17591. // field to come through.
  17592. static void expect_split_multipart_ok(const std::string &body1,
  17593. const std::string &body2) {
  17594. auto handled = false;
  17595. Server svr;
  17596. svr.Post("/post", [&](const Request &req, Response &) {
  17597. EXPECT_EQ(1u, req.form.fields.size());
  17598. EXPECT_EQ("text1", req.form.get_field("text1"));
  17599. handled = true;
  17600. });
  17601. auto port = svr.bind_to_any_port(HOST);
  17602. thread t = thread([&] { svr.listen_after_bind(); });
  17603. auto se = detail::scope_exit([&] {
  17604. svr.stop();
  17605. t.join();
  17606. ASSERT_FALSE(svr.is_running());
  17607. ASSERT_TRUE(handled);
  17608. });
  17609. svr.wait_until_ready();
  17610. // "Connection: close" makes the server close once it has answered, so the
  17611. // response drain ends immediately instead of idling until the read timeout.
  17612. const std::string head =
  17613. "POST /post HTTP/1.1\r\n"
  17614. "Host: localhost\r\n"
  17615. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17616. "Connection: close\r\n"
  17617. "Content-Length: " +
  17618. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17619. std::string response;
  17620. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17621. ASSERT_GE(response.size(), 12u) << "no response";
  17622. EXPECT_EQ("200", response.substr(9, 3));
  17623. }
  17624. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17625. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17626. // ignored, including when it does not arrive in the same read as the
  17627. // close-delimiter itself.
  17628. expect_split_multipart_ok("--zzzz\r\n"
  17629. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17630. "\r\n"
  17631. "text1"
  17632. "\r\n--zzzz--",
  17633. "\r\nthis epilogue must be ignored\r\n");
  17634. }
  17635. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17636. // The initial boundary may be preceded by a preamble of any length and may
  17637. // straddle a read boundary. Discarding data while waiting for it must not
  17638. // throw away a partial boundary sitting at the end of the buffer.
  17639. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17640. "zz\r\n"
  17641. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17642. "\r\n"
  17643. "text1"
  17644. "\r\n--zzzz--\r\n");
  17645. }
  17646. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17647. // The received boundary was only checked for being non-empty, so it could be
  17648. // as long as a header is allowed to be. The parser scans the body for
  17649. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17650. // costs a nearly full comparison at nearly every position, making the
  17651. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17652. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17653. Server svr;
  17654. svr.Post("/post", [](const Request &req, Response &res) {
  17655. EXPECT_EQ(1u, req.form.fields.size());
  17656. EXPECT_EQ("text1", req.form.get_field("text1"));
  17657. res.set_content("ok", "text/plain");
  17658. });
  17659. auto port = svr.bind_to_any_port(HOST);
  17660. thread t = thread([&] { svr.listen_after_bind(); });
  17661. auto se = detail::scope_exit([&] {
  17662. svr.stop();
  17663. t.join();
  17664. ASSERT_FALSE(svr.is_running());
  17665. });
  17666. svr.wait_until_ready();
  17667. Client cli(HOST, port);
  17668. auto post_with_boundary_of_length = [&](size_t len) {
  17669. const std::string boundary(len, 'a');
  17670. const std::string body =
  17671. "--" + boundary +
  17672. "\r\n"
  17673. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17674. "\r\n"
  17675. "text1"
  17676. "\r\n--" +
  17677. boundary + "--\r\n";
  17678. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17679. };
  17680. auto res = post_with_boundary_of_length(70);
  17681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17682. EXPECT_EQ(StatusCode::OK_200, res->status);
  17683. res = post_with_boundary_of_length(71);
  17684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17685. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17686. }
  17687. TEST(MakeFileBodyTest, Basic) {
  17688. const std::string file_content(4096, 'Z');
  17689. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17690. {
  17691. std::ofstream ofs(tmp_path, std::ios::binary);
  17692. ofs.write(file_content.data(),
  17693. static_cast<std::streamsize>(file_content.size()));
  17694. }
  17695. auto handled = false;
  17696. Server svr;
  17697. svr.Post("/upload", [&](const Request &req, Response &res) {
  17698. EXPECT_EQ(file_content, req.body);
  17699. handled = true;
  17700. res.status = StatusCode::OK_200;
  17701. });
  17702. auto port = svr.bind_to_any_port(HOST);
  17703. auto t = thread([&] { svr.listen_after_bind(); });
  17704. auto se = detail::scope_exit([&] {
  17705. svr.stop();
  17706. t.join();
  17707. ASSERT_FALSE(svr.is_running());
  17708. ASSERT_TRUE(handled);
  17709. std::remove(tmp_path.c_str());
  17710. });
  17711. svr.wait_until_ready();
  17712. auto fb = make_file_body(tmp_path);
  17713. ASSERT_GT(fb.first, 0u);
  17714. Client cli(HOST, port);
  17715. auto res =
  17716. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17718. EXPECT_EQ(StatusCode::OK_200, res->status);
  17719. }
  17720. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17721. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17722. {
  17723. std::ofstream ofs(path, std::ios::binary);
  17724. const std::string content(100, 'A');
  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(100u, body.first);
  17730. ASSERT_TRUE(static_cast<bool>(body.second));
  17731. // Rewritten shorter after its length was measured - and, on a server, after
  17732. // that length has already gone out as Content-Length.
  17733. {
  17734. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17735. const std::string content(10, 'A');
  17736. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17737. }
  17738. std::string written;
  17739. DataSink sink;
  17740. sink.write = [&](const char *d, size_t l) {
  17741. written.append(d, l);
  17742. return true;
  17743. };
  17744. // The provider has to report failure. write_content_with_progress() advances
  17745. // its offset only by what was written, so a provider that returns true
  17746. // without completing the length it promised is called again straight away,
  17747. // and again.
  17748. EXPECT_FALSE(body.second(0, body.first, sink));
  17749. EXPECT_EQ(std::string(10, 'A'), written);
  17750. }
  17751. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17752. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17753. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17754. {
  17755. std::ofstream ofs(path, std::ios::binary);
  17756. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17757. }
  17758. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17759. auto body = make_file_body(path);
  17760. ASSERT_EQ(content.size(), body.first);
  17761. ASSERT_TRUE(static_cast<bool>(body.second));
  17762. std::string written;
  17763. DataSink sink;
  17764. sink.write = [&](const char *d, size_t l) {
  17765. written.append(d, l);
  17766. return true;
  17767. };
  17768. EXPECT_TRUE(body.second(0, body.first, sink));
  17769. EXPECT_EQ(content, written);
  17770. }
  17771. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17772. static constexpr unsigned int number_of_tasks{1000000};
  17773. std::atomic_uint count{0};
  17774. std::unique_ptr<TaskQueue> task_queue{
  17775. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17776. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17777. auto queued = task_queue->enqueue(
  17778. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17779. EXPECT_TRUE(queued);
  17780. }
  17781. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17782. task_queue->shutdown();
  17783. #else
  17784. EXPECT_NO_THROW(task_queue->shutdown());
  17785. #endif
  17786. EXPECT_EQ(number_of_tasks, count.load());
  17787. }
  17788. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17789. static constexpr unsigned int number_of_tasks{1000000};
  17790. static constexpr unsigned int qlimit{2};
  17791. unsigned int queued_count{0};
  17792. std::atomic_uint count{0};
  17793. std::unique_ptr<TaskQueue> task_queue{
  17794. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17795. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17796. if (task_queue->enqueue(
  17797. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17798. queued_count++;
  17799. }
  17800. }
  17801. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17802. task_queue->shutdown();
  17803. #else
  17804. EXPECT_NO_THROW(task_queue->shutdown());
  17805. #endif
  17806. EXPECT_EQ(queued_count, count.load());
  17807. EXPECT_TRUE(queued_count <= number_of_tasks);
  17808. EXPECT_TRUE(queued_count >= qlimit);
  17809. }
  17810. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17811. // Use a short idle timeout so a dynamic thread spawns, times out and
  17812. // exits during the test, and the pool keeps working afterwards.
  17813. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17814. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17815. /*idle_timeout_sec=*/1}};
  17816. std::atomic_uint count{0};
  17817. std::condition_variable cv;
  17818. std::mutex mtx;
  17819. bool release = false;
  17820. // Block the base thread so the second task spawns a dynamic thread.
  17821. EXPECT_TRUE(task_queue->enqueue([&] {
  17822. std::unique_lock<std::mutex> lock(mtx);
  17823. while (!release) {
  17824. cv.wait(lock);
  17825. }
  17826. count++;
  17827. }));
  17828. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17829. // Let the dynamic thread finish its task and exceed the idle timeout.
  17830. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17831. {
  17832. std::unique_lock<std::mutex> lock(mtx);
  17833. release = true;
  17834. }
  17835. cv.notify_all();
  17836. // The pool must still accept and run tasks after the dynamic thread exited.
  17837. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17838. task_queue->shutdown();
  17839. EXPECT_EQ(3u, count.load());
  17840. }
  17841. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17842. static constexpr size_t number_of_tasks{32};
  17843. std::unique_ptr<TaskQueue> task_queue{
  17844. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17845. // Let the base threads go idle so the burst below finds them waiting.
  17846. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17847. std::mutex mtx;
  17848. std::condition_variable cv;
  17849. size_t running = 0;
  17850. bool release = false;
  17851. for (size_t i = 0; i < number_of_tasks; i++) {
  17852. EXPECT_TRUE(task_queue->enqueue([&] {
  17853. std::unique_lock<std::mutex> lock(mtx);
  17854. running++;
  17855. cv.notify_all();
  17856. cv.wait(lock, [&] { return release; });
  17857. }));
  17858. }
  17859. {
  17860. std::unique_lock<std::mutex> lock(mtx);
  17861. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17862. [&] { return running == number_of_tasks; }));
  17863. release = true;
  17864. }
  17865. cv.notify_all();
  17866. task_queue->shutdown();
  17867. }
  17868. TEST(TaskQueueTest, MaxQueuedRequests) {
  17869. static constexpr unsigned int qlimit{3};
  17870. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17871. std::condition_variable sem_cv;
  17872. std::mutex sem_mtx;
  17873. int credits = 0;
  17874. bool queued;
  17875. /* Fill up the queue with tasks that will block until we give them credits to
  17876. * complete. */
  17877. for (unsigned int n = 0; n <= qlimit;) {
  17878. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17879. std::unique_lock<std::mutex> lock(sem_mtx);
  17880. while (credits <= 0) {
  17881. sem_cv.wait(lock);
  17882. }
  17883. /* Consume the credit and signal the test code if they are all gone. */
  17884. if (--credits == 0) { sem_cv.notify_one(); }
  17885. });
  17886. if (n < qlimit) {
  17887. /* The first qlimit enqueues must succeed. */
  17888. EXPECT_TRUE(queued);
  17889. } else {
  17890. /* The last one will succeed only when the worker thread
  17891. * starts and dequeues the first blocking task. Although
  17892. * not necessary for the correctness of this test, we sleep for
  17893. * a short while to avoid busy waiting. */
  17894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17895. }
  17896. if (queued) { n++; }
  17897. }
  17898. /* Further enqueues must fail since the queue is full. */
  17899. for (auto i = 0; i < 4; i++) {
  17900. queued = task_queue->enqueue([] {});
  17901. EXPECT_FALSE(queued);
  17902. }
  17903. /* Give the credits to allow the previous tasks to complete. */
  17904. {
  17905. std::unique_lock<std::mutex> lock(sem_mtx);
  17906. credits += qlimit + 1;
  17907. }
  17908. sem_cv.notify_all();
  17909. /* Wait for all the credits to be consumed. */
  17910. {
  17911. std::unique_lock<std::mutex> lock(sem_mtx);
  17912. while (credits > 0) {
  17913. sem_cv.wait(lock);
  17914. }
  17915. }
  17916. /* Check that we are able again to enqueue at least qlimit tasks. */
  17917. for (unsigned int i = 0; i < qlimit; i++) {
  17918. queued = task_queue->enqueue([] {});
  17919. EXPECT_TRUE(queued);
  17920. }
  17921. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17922. task_queue->shutdown();
  17923. #else
  17924. EXPECT_NO_THROW(task_queue->shutdown());
  17925. #endif
  17926. }
  17927. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17928. Server svr;
  17929. std::string method;
  17930. std::string body;
  17931. auto has_content_length = false;
  17932. auto has_transfer_encoding = false;
  17933. std::atomic<int> bad_requests{0};
  17934. // Leftover body bytes get parsed as a malformed request and answered with
  17935. // 400
  17936. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17937. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17938. });
  17939. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17940. res.set_redirect("/down", StatusCode::SeeOther_303);
  17941. });
  17942. svr.Get("/down", [&](const Request &req, Response &res) {
  17943. method = req.method;
  17944. body = req.body;
  17945. has_content_length = req.has_header("Content-Length");
  17946. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17947. res.set_content("ok", "text/plain");
  17948. });
  17949. auto port = svr.bind_to_any_port(HOST);
  17950. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17951. auto se = detail::scope_exit([&] {
  17952. svr.stop();
  17953. thread.join();
  17954. ASSERT_FALSE(svr.is_running());
  17955. });
  17956. svr.wait_until_ready();
  17957. const std::string payload = "SECRET-BODY";
  17958. auto check = [&](Client &cli, const Result &res) {
  17959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17960. EXPECT_EQ(StatusCode::OK_200, res->status);
  17961. EXPECT_EQ("ok", res->body);
  17962. EXPECT_EQ("GET", method);
  17963. EXPECT_TRUE(body.empty());
  17964. EXPECT_FALSE(has_content_length);
  17965. EXPECT_FALSE(has_transfer_encoding);
  17966. // Nothing of the original body may be left on the connection
  17967. auto res2 = cli.Get("/down");
  17968. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17969. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17970. EXPECT_EQ("ok", res2->body);
  17971. EXPECT_EQ(0, bad_requests);
  17972. };
  17973. // With content length
  17974. {
  17975. Client cli(HOST, port);
  17976. cli.set_keep_alive(true);
  17977. cli.set_follow_location(true);
  17978. auto res = cli.Post(
  17979. "/up", payload.size(),
  17980. [&](size_t offset, size_t length, DataSink &sink) {
  17981. return sink.write(payload.data() + offset, length);
  17982. },
  17983. "text/plain");
  17984. check(cli, res);
  17985. }
  17986. // Without content length (chunked)
  17987. {
  17988. Client cli(HOST, port);
  17989. cli.set_keep_alive(true);
  17990. cli.set_follow_location(true);
  17991. auto res = cli.Post(
  17992. "/up",
  17993. [&](size_t /*offset*/, DataSink &sink) {
  17994. sink.write(payload.data(), payload.size());
  17995. sink.done();
  17996. return true;
  17997. },
  17998. "text/plain");
  17999. check(cli, res);
  18000. }
  18001. }
  18002. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18003. Server svr;
  18004. std::string target;
  18005. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18006. // Echo the still-encoded name back in the Location
  18007. const std::string prefix = "/start/";
  18008. res.status = StatusCode::Found_302;
  18009. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18010. });
  18011. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18012. target = req.target;
  18013. res.set_content("ok", "text/plain");
  18014. });
  18015. auto port = svr.bind_to_any_port(HOST);
  18016. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18017. auto se = detail::scope_exit([&] {
  18018. svr.stop();
  18019. thread.join();
  18020. ASSERT_FALSE(svr.is_running());
  18021. });
  18022. svr.wait_until_ready();
  18023. // Decoding the Location path would turn the first four into a path
  18024. // separator, a query delimiter, a fragment delimiter and a different
  18025. // percent-encoded octet. The rest must keep reaching the server as they are.
  18026. const std::vector<std::string> names = {
  18027. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18028. };
  18029. for (auto path_encode : {true, false}) {
  18030. Client cli(HOST, port);
  18031. cli.set_follow_location(true);
  18032. cli.set_path_encode(path_encode);
  18033. for (const auto &name : names) {
  18034. target.clear();
  18035. auto res = cli.Get("/start/" + name);
  18036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18037. EXPECT_EQ(StatusCode::OK_200, res->status);
  18038. EXPECT_EQ("/dest/" + name, target);
  18039. }
  18040. }
  18041. }
  18042. TEST(RedirectTest, NotModifiedIsReturned) {
  18043. Server svr;
  18044. svr.Get("/cached", [](const Request &, Response &res) {
  18045. res.status = StatusCode::NotModified_304;
  18046. });
  18047. auto port = svr.bind_to_any_port(HOST);
  18048. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18049. auto se = detail::scope_exit([&] {
  18050. svr.stop();
  18051. thread.join();
  18052. ASSERT_FALSE(svr.is_running());
  18053. });
  18054. svr.wait_until_ready();
  18055. Client cli(HOST, port);
  18056. cli.set_follow_location(true);
  18057. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18059. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18060. }
  18061. TEST(RedirectTest, NoLocationIsReturned) {
  18062. Server svr;
  18063. svr.Get("/no-location", [](const Request &, Response &res) {
  18064. res.status = StatusCode::Found_302;
  18065. res.set_content("no location", "text/plain");
  18066. });
  18067. auto port = svr.bind_to_any_port(HOST);
  18068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18069. auto se = detail::scope_exit([&] {
  18070. svr.stop();
  18071. thread.join();
  18072. ASSERT_FALSE(svr.is_running());
  18073. });
  18074. svr.wait_until_ready();
  18075. Client cli(HOST, port);
  18076. cli.set_follow_location(true);
  18077. auto res = cli.Get("/no-location");
  18078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18079. EXPECT_EQ(StatusCode::Found_302, res->status);
  18080. EXPECT_EQ("no location", res->body);
  18081. // The callbacks see the body of the response that is returned
  18082. auto handler_called = false;
  18083. auto progress_called = false;
  18084. std::string body;
  18085. auto res2 = cli.Get(
  18086. "/no-location",
  18087. [&](const Response &) {
  18088. handler_called = true;
  18089. return true;
  18090. },
  18091. [&](const char *data, size_t data_length) {
  18092. body.append(data, data_length);
  18093. return true;
  18094. },
  18095. [&](size_t, size_t) {
  18096. progress_called = true;
  18097. return true;
  18098. });
  18099. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18100. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18101. EXPECT_TRUE(handler_called);
  18102. EXPECT_TRUE(progress_called);
  18103. EXPECT_EQ("no location", body);
  18104. }
  18105. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18106. Server svr;
  18107. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18108. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18109. });
  18110. svr.Get("/hello", [](const Request &req, Response &res) {
  18111. res.set_content(req.get_param_value("key"), "text/plain");
  18112. });
  18113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18114. auto se = detail::scope_exit([&] {
  18115. svr.stop();
  18116. thread.join();
  18117. ASSERT_FALSE(svr.is_running());
  18118. });
  18119. svr.wait_until_ready();
  18120. {
  18121. Client cli(HOST, PORT);
  18122. cli.set_follow_location(true);
  18123. auto res = cli.Get("/");
  18124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18125. EXPECT_EQ(StatusCode::OK_200, res->status);
  18126. EXPECT_EQ("val&key2=val2", res->body);
  18127. }
  18128. }
  18129. #endif
  18130. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18131. Server svr;
  18132. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18133. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18134. });
  18135. svr.Get("/hello", [](const Request &req, Response &res) {
  18136. res.set_content(req.get_param_value("key"), "text/plain");
  18137. });
  18138. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18139. auto se = detail::scope_exit([&] {
  18140. svr.stop();
  18141. thread.join();
  18142. ASSERT_FALSE(svr.is_running());
  18143. });
  18144. svr.wait_until_ready();
  18145. {
  18146. Client cli(HOST, PORT);
  18147. cli.set_follow_location(true);
  18148. auto res = cli.Get("/");
  18149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18150. EXPECT_EQ(StatusCode::OK_200, res->status);
  18151. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18152. }
  18153. }
  18154. TEST(RedirectTest, RedirectWithPlusInPath) {
  18155. Server svr;
  18156. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18157. res.set_redirect("/a+b");
  18158. });
  18159. // Route pattern uses regex; escape + as \\+
  18160. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18161. res.set_content(req.path, "text/plain");
  18162. });
  18163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18164. auto se = detail::scope_exit([&] {
  18165. svr.stop();
  18166. thread.join();
  18167. ASSERT_FALSE(svr.is_running());
  18168. });
  18169. svr.wait_until_ready();
  18170. {
  18171. Client cli(HOST, PORT);
  18172. cli.set_follow_location(true);
  18173. auto res = cli.Get("/");
  18174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18175. EXPECT_EQ(StatusCode::OK_200, res->status);
  18176. EXPECT_EQ("/a+b", res->body);
  18177. }
  18178. }
  18179. TEST(RedirectTest, ResolveRelativeLocation) {
  18180. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18181. const std::vector<std::pair<std::string, std::string>> cases = {
  18182. {"g", "/b/c/g"},
  18183. {"./g", "/b/c/g"},
  18184. {"g/", "/b/c/g/"},
  18185. {"?y", "/b/c/d;p?y"},
  18186. {"g?y", "/b/c/g?y"},
  18187. {"#s", "/b/c/d;p?q#s"},
  18188. {"g#s", "/b/c/g#s"},
  18189. {"g?y#s", "/b/c/g?y#s"},
  18190. {";x", "/b/c/;x"},
  18191. {"g;x", "/b/c/g;x"},
  18192. {".", "/b/c/"},
  18193. {"./", "/b/c/"},
  18194. {"..", "/b/"},
  18195. {"../", "/b/"},
  18196. {"../g", "/b/g"},
  18197. {"../..", "/"},
  18198. {"../../", "/"},
  18199. {"../../g", "/g"},
  18200. {"../../../g", "/g"},
  18201. {"g.", "/b/c/g."},
  18202. {".g", "/b/c/.g"},
  18203. {"g..", "/b/c/g.."},
  18204. {"..g", "/b/c/..g"},
  18205. {"./../g", "/b/g"},
  18206. {"./g/.", "/b/c/g/"},
  18207. {"g/./h", "/b/c/g/h"},
  18208. {"g/../h", "/b/c/h"},
  18209. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18210. {"g;x=1/../y", "/b/c/y"},
  18211. {"g?y/./x", "/b/c/g?y/./x"},
  18212. {"g#s/../x", "/b/c/g#s/../x"},
  18213. // Not relative-path references, so left for parse_url.
  18214. {"/g", "/g"},
  18215. {"//g", "//g"},
  18216. {"http://g/x", "http://g/x"},
  18217. {"g:h", "g:h"},
  18218. };
  18219. for (const auto &c : cases) {
  18220. EXPECT_EQ(c.second,
  18221. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18222. << c.first;
  18223. }
  18224. // A result starting with "//" is still a path, not a network-path reference
  18225. EXPECT_EQ("/.//g",
  18226. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18227. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18228. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18229. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18230. }
  18231. TEST(RedirectTest, RemoveDotSegments) {
  18232. // RFC 3986 section 5.2.4
  18233. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18234. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18235. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18236. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18237. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18238. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18239. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18240. }
  18241. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18242. Server svr;
  18243. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18244. res.set_redirect("/dir/../target?x=1");
  18245. });
  18246. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18247. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18248. "/dir/./../target");
  18249. });
  18250. svr.Get("/target", [](const Request &req, Response &res) {
  18251. res.set_content(req.path, "text/plain");
  18252. });
  18253. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18254. auto se = detail::scope_exit([&] {
  18255. svr.stop();
  18256. th.join();
  18257. ASSERT_FALSE(svr.is_running());
  18258. });
  18259. svr.wait_until_ready();
  18260. Client cli("localhost", PORT);
  18261. cli.set_follow_location(true);
  18262. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18263. auto res = cli.Get(path);
  18264. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18265. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18266. EXPECT_EQ("/target", res->body) << path;
  18267. }
  18268. }
  18269. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18270. Server svr;
  18271. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18272. res.set_redirect(req.get_param_value("to"));
  18273. });
  18274. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18275. res.set_content(req.target, "text/plain");
  18276. });
  18277. svr.Get("/other", [](const Request &req, Response &res) {
  18278. res.set_content(req.target, "text/plain");
  18279. });
  18280. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18281. auto se = detail::scope_exit([&] {
  18282. svr.stop();
  18283. thread.join();
  18284. ASSERT_FALSE(svr.is_running());
  18285. });
  18286. svr.wait_until_ready();
  18287. const std::vector<std::pair<std::string, std::string>> cases = {
  18288. {"next", "/dir/next"},
  18289. {"./next?x=1", "/dir/next?x=1"},
  18290. {"../other", "/other"},
  18291. };
  18292. for (const auto &c : cases) {
  18293. Client cli(HOST, PORT);
  18294. cli.set_follow_location(true);
  18295. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18296. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18297. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18298. EXPECT_EQ(c.second, res->body) << c.first;
  18299. }
  18300. }
  18301. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18302. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18303. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18304. Server other;
  18305. std::atomic<int> other_hits{0};
  18306. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18307. other_hits++;
  18308. res.set_content("other", "text/plain");
  18309. });
  18310. auto other_port = other.bind_to_any_port("127.0.0.1");
  18311. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18312. Server svr;
  18313. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18314. res.set_redirect(req.get_param_value("to"));
  18315. });
  18316. svr.Get(".*", [](const Request &req, Response &res) {
  18317. res.set_content(req.path, "text/plain");
  18318. });
  18319. auto port = svr.bind_to_any_port(HOST);
  18320. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18321. auto se = detail::scope_exit([&] {
  18322. svr.stop();
  18323. thread.join();
  18324. other.stop();
  18325. other_thread.join();
  18326. ASSERT_FALSE(svr.is_running());
  18327. ASSERT_FALSE(other.is_running());
  18328. });
  18329. svr.wait_until_ready();
  18330. other.wait_until_ready();
  18331. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18332. for (const auto &to :
  18333. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18334. Client cli(HOST, port);
  18335. cli.set_follow_location(true);
  18336. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18337. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18338. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18339. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18340. }
  18341. EXPECT_EQ(0, other_hits.load());
  18342. }
  18343. #ifdef CPPHTTPLIB_SSL_ENABLED
  18344. TEST(RedirectTest, Issue2185_Online) {
  18345. SSLClient client("github.com");
  18346. client.set_follow_location(true);
  18347. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18348. "Coollab-Windows.zip");
  18349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18350. EXPECT_EQ(StatusCode::OK_200, res->status);
  18351. EXPECT_EQ(9920427U, res->body.size());
  18352. }
  18353. #endif
  18354. TEST(VulnerabilityTest, CRLFInjection) {
  18355. Server svr;
  18356. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18357. res.set_content("Hello 1", "text/plain");
  18358. });
  18359. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18360. res.set_content("Hello 2", "text/plain");
  18361. });
  18362. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18363. res.set_content("Hello 3", "text/plain");
  18364. });
  18365. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18366. res.set_content("Hello 4", "text/plain");
  18367. });
  18368. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18369. for (const auto &x : req.headers) {
  18370. auto key = x.first;
  18371. EXPECT_STRNE("evil", key.c_str());
  18372. }
  18373. });
  18374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18375. auto se = detail::scope_exit([&] {
  18376. svr.stop();
  18377. thread.join();
  18378. ASSERT_FALSE(svr.is_running());
  18379. });
  18380. svr.wait_until_ready();
  18381. {
  18382. Client cli(HOST, PORT);
  18383. cli.Post("/test1", "A=B",
  18384. "application/x-www-form-urlencoded\r\nevil: hello1");
  18385. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18386. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18387. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18388. }
  18389. }
  18390. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18391. auto server_thread = std::thread([] {
  18392. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18393. default_socket_options(srv);
  18394. sockaddr_in addr{};
  18395. addr.sin_family = AF_INET;
  18396. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18398. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18399. ::listen(srv, 1);
  18400. sockaddr_in cli_addr{};
  18401. socklen_t cli_len = sizeof(cli_addr);
  18402. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18403. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18404. std::string buf_all;
  18405. char buf[2048];
  18406. ssize_t n;
  18407. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18408. buf_all.append(buf, static_cast<size_t>(n));
  18409. size_t pos;
  18410. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18411. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18412. auto e = request_block.find("\r\n");
  18413. if (e != std::string::npos) {
  18414. auto request_line = request_block.substr(0, e);
  18415. std::string msg =
  18416. "CRLF injection detected in request line: '" + request_line + "'";
  18417. EXPECT_FALSE(true) << msg;
  18418. }
  18419. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18420. ::send(cli,
  18421. #ifdef _WIN32
  18422. static_cast<const char *>(resp.c_str()),
  18423. static_cast<int>(resp.size()),
  18424. #else
  18425. resp.c_str(), resp.size(),
  18426. #endif
  18427. 0);
  18428. buf_all.erase(0, pos + 4);
  18429. }
  18430. }
  18431. detail::close_socket(cli);
  18432. detail::close_socket(srv);
  18433. });
  18434. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18435. auto cli = Client("127.0.0.1", PORT + 1);
  18436. auto headers = Headers{
  18437. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18438. {"Connection", "keep-alive"}};
  18439. auto res = cli.Get("/hi", headers);
  18440. EXPECT_FALSE(res);
  18441. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18442. server_thread.join();
  18443. }
  18444. // A request rejected before any byte reaches the socket must fail right away
  18445. // instead of waiting for a response the server will never send.
  18446. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18447. // The kernel completes the TCP handshake from the listen backlog, so the
  18448. // client connects, but nothing ever reads, responds or closes.
  18449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18450. default_socket_options(srv);
  18451. sockaddr_in addr{};
  18452. addr.sin_family = AF_INET;
  18453. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18454. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18455. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18456. ASSERT_EQ(0, ::listen(srv, 8));
  18457. auto cli = Client("127.0.0.1", PORT + 1);
  18458. cli.set_read_timeout(10, 0);
  18459. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18460. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18461. std::chrono::steady_clock::now() - start)
  18462. .count();
  18463. };
  18464. {
  18465. Request req;
  18466. req.method = "GE T";
  18467. req.path = "/";
  18468. auto start = std::chrono::steady_clock::now();
  18469. auto res = cli.send(req);
  18470. EXPECT_FALSE(res);
  18471. EXPECT_EQ(Error::Write, res.error());
  18472. EXPECT_LT(elapsed_ms(start), 1000);
  18473. }
  18474. {
  18475. auto start = std::chrono::steady_clock::now();
  18476. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18477. EXPECT_FALSE(res);
  18478. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18479. EXPECT_LT(elapsed_ms(start), 1000);
  18480. }
  18481. EXPECT_FALSE(cli.is_socket_open());
  18482. detail::close_socket(srv);
  18483. }
  18484. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18485. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18486. default_socket_options(srv);
  18487. sockaddr_in addr{};
  18488. addr.sin_family = AF_INET;
  18489. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18491. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18492. ASSERT_EQ(0, ::listen(srv, 1));
  18493. std::string received;
  18494. auto server_thread = std::thread([&] {
  18495. auto sock = ::accept(srv, nullptr, nullptr);
  18496. if (sock == INVALID_SOCKET) { return; }
  18497. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18498. char buf[2048];
  18499. ssize_t n;
  18500. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18501. received.append(buf, static_cast<size_t>(n));
  18502. }
  18503. detail::close_socket(sock);
  18504. });
  18505. {
  18506. auto cli = Client("127.0.0.1", PORT + 1);
  18507. // "Z" sorts after the default headers, so writing straight to the socket
  18508. // would have sent the request line and those headers before the rejection.
  18509. auto handle =
  18510. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18511. EXPECT_FALSE(handle.is_valid());
  18512. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18513. }
  18514. server_thread.join();
  18515. detail::close_socket(srv);
  18516. EXPECT_TRUE(received.empty()) << received;
  18517. }
  18518. TEST(PathParamsTest, StaticMatch) {
  18519. const auto pattern = "/users/all";
  18520. detail::PathParamsMatcher matcher(pattern);
  18521. Request request;
  18522. request.path = "/users/all";
  18523. ASSERT_TRUE(matcher.match(request));
  18524. std::unordered_map<std::string, std::string> expected_params = {};
  18525. EXPECT_EQ(request.path_params, expected_params);
  18526. }
  18527. TEST(PathParamsTest, StaticMismatch) {
  18528. const auto pattern = "/users/all";
  18529. detail::PathParamsMatcher matcher(pattern);
  18530. Request request;
  18531. request.path = "/users/1";
  18532. ASSERT_FALSE(matcher.match(request));
  18533. }
  18534. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18535. const auto pattern = "/users/:id/subscriptions";
  18536. detail::PathParamsMatcher matcher(pattern);
  18537. Request request;
  18538. request.path = "/users/42/subscriptions";
  18539. ASSERT_TRUE(matcher.match(request));
  18540. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18541. EXPECT_EQ(request.path_params, expected_params);
  18542. }
  18543. TEST(PathParamsTest, SingleParamInTheEnd) {
  18544. const auto pattern = "/users/:id";
  18545. detail::PathParamsMatcher matcher(pattern);
  18546. Request request;
  18547. request.path = "/users/24";
  18548. ASSERT_TRUE(matcher.match(request));
  18549. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18550. EXPECT_EQ(request.path_params, expected_params);
  18551. }
  18552. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18553. const auto pattern = "/users/:id/";
  18554. detail::PathParamsMatcher matcher(pattern);
  18555. Request request;
  18556. request.path = "/users/42/";
  18557. ASSERT_TRUE(matcher.match(request));
  18558. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18559. EXPECT_EQ(request.path_params, expected_params);
  18560. }
  18561. TEST(PathParamsTest, EmptyParam) {
  18562. const auto pattern = "/users/:id/";
  18563. detail::PathParamsMatcher matcher(pattern);
  18564. Request request;
  18565. request.path = "/users//";
  18566. ASSERT_TRUE(matcher.match(request));
  18567. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18568. EXPECT_EQ(request.path_params, expected_params);
  18569. }
  18570. TEST(PathParamsTest, FragmentMismatch) {
  18571. const auto pattern = "/users/:id/";
  18572. detail::PathParamsMatcher matcher(pattern);
  18573. Request request;
  18574. request.path = "/admins/24/";
  18575. ASSERT_FALSE(matcher.match(request));
  18576. }
  18577. TEST(PathParamsTest, ExtraFragments) {
  18578. const auto pattern = "/users/:id";
  18579. detail::PathParamsMatcher matcher(pattern);
  18580. Request request;
  18581. request.path = "/users/42/subscriptions";
  18582. ASSERT_FALSE(matcher.match(request));
  18583. }
  18584. TEST(PathParamsTest, MissingTrailingParam) {
  18585. const auto pattern = "/users/:id";
  18586. detail::PathParamsMatcher matcher(pattern);
  18587. Request request;
  18588. request.path = "/users";
  18589. ASSERT_FALSE(matcher.match(request));
  18590. }
  18591. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18592. const auto pattern = "/users/:id/subscriptions";
  18593. detail::PathParamsMatcher matcher(pattern);
  18594. Request request;
  18595. request.path = "/users/subscriptions";
  18596. ASSERT_FALSE(matcher.match(request));
  18597. }
  18598. TEST(PathParamsTest, MultipleParams) {
  18599. const auto pattern = "/users/:userid/subscriptions/:subid";
  18600. detail::PathParamsMatcher matcher(pattern);
  18601. Request request;
  18602. request.path = "/users/42/subscriptions/2";
  18603. ASSERT_TRUE(matcher.match(request));
  18604. std::unordered_map<std::string, std::string> expected_params = {
  18605. {"userid", "42"}, {"subid", "2"}};
  18606. EXPECT_EQ(request.path_params, expected_params);
  18607. }
  18608. TEST(PathParamsTest, SequenceOfParams) {
  18609. const auto pattern = "/values/:x/:y/:z";
  18610. detail::PathParamsMatcher matcher(pattern);
  18611. Request request;
  18612. request.path = "/values/1/2/3";
  18613. ASSERT_TRUE(matcher.match(request));
  18614. std::unordered_map<std::string, std::string> expected_params = {
  18615. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18616. EXPECT_EQ(request.path_params, expected_params);
  18617. }
  18618. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18619. const auto pattern = "/prefix:suffix";
  18620. detail::PathParamsMatcher matcher(pattern);
  18621. Request request;
  18622. request.path = "/prefix:suffix";
  18623. ASSERT_TRUE(matcher.match(request));
  18624. const std::unordered_map<std::string, std::string> expected_params = {};
  18625. EXPECT_EQ(request.path_params, expected_params);
  18626. }
  18627. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18628. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18629. // calling thread's stack on a long enough path for a quantified pattern;
  18630. // RegexMatcher must refuse to run regex matching on paths beyond
  18631. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18632. detail::RegexMatcher matcher("/files/(.*)");
  18633. Request within_limit;
  18634. within_limit.path = "/files/" + std::string(10, 'A');
  18635. EXPECT_TRUE(matcher.match(within_limit));
  18636. Request over_limit;
  18637. over_limit.path =
  18638. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18639. EXPECT_FALSE(matcher.match(over_limit));
  18640. }
  18641. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18642. Server svr;
  18643. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18644. res.set_content("ok", "text/plain");
  18645. });
  18646. auto port = svr.bind_to_any_port(HOST);
  18647. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18648. auto se = detail::scope_exit([&] {
  18649. svr.stop();
  18650. thread.join();
  18651. ASSERT_FALSE(svr.is_running());
  18652. });
  18653. svr.wait_until_ready();
  18654. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18655. // request URI limit; this used to be able to crash the process.
  18656. std::string path =
  18657. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18658. std::string req = "GET " + path +
  18659. " HTTP/1.1\r\n"
  18660. "Host: " +
  18661. std::string(HOST) + ":" + std::to_string(port) +
  18662. "\r\n"
  18663. "Connection: close\r\n"
  18664. "\r\n";
  18665. std::string response;
  18666. ASSERT_TRUE(send_request(5, req, &response, port));
  18667. EXPECT_NE(std::string::npos, response.find("404"));
  18668. }
  18669. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18670. Server svr;
  18671. auto handler = [](const Request & /*req*/, Response &res) {
  18672. res.set_content("hit", "text/plain");
  18673. };
  18674. // No regex metacharacter, so this one is compared literally
  18675. svr.Get("/literal/route", handler);
  18676. // '.' is a regex metacharacter, so this one must keep regex semantics
  18677. svr.Get("/a.c", handler);
  18678. auto port = svr.bind_to_any_port(HOST);
  18679. std::thread t([&]() { svr.listen_after_bind(); });
  18680. auto se = detail::scope_exit([&] {
  18681. svr.stop();
  18682. t.join();
  18683. ASSERT_FALSE(svr.is_running());
  18684. });
  18685. svr.wait_until_ready();
  18686. Client cli(HOST, port);
  18687. struct {
  18688. const char *path;
  18689. int status;
  18690. } cases[] = {
  18691. {"/literal/route", StatusCode::OK_200},
  18692. {"/literal/routes", StatusCode::NotFound_404},
  18693. {"/literal/rout", StatusCode::NotFound_404},
  18694. {"/abc", StatusCode::OK_200},
  18695. {"/a.c", StatusCode::OK_200},
  18696. };
  18697. for (const auto &x : cases) {
  18698. auto res = cli.Get(x.path);
  18699. ASSERT_TRUE(res) << x.path;
  18700. EXPECT_EQ(x.status, res->status) << x.path;
  18701. }
  18702. }
  18703. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18704. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18705. // from exhausting the stack, so it must only constrain routes that actually
  18706. // run a regular expression. A literal route is matched by comparison and
  18707. // stays usable at any length.
  18708. Server svr;
  18709. const std::string pattern =
  18710. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18711. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18712. res.set_content("hit", "text/plain");
  18713. });
  18714. auto port = svr.bind_to_any_port(HOST);
  18715. std::thread t([&]() { svr.listen_after_bind(); });
  18716. auto se = detail::scope_exit([&] {
  18717. svr.stop();
  18718. t.join();
  18719. ASSERT_FALSE(svr.is_running());
  18720. });
  18721. svr.wait_until_ready();
  18722. Client cli(HOST, port);
  18723. auto res = cli.Get(pattern);
  18724. ASSERT_TRUE(res);
  18725. EXPECT_EQ(StatusCode::OK_200, res->status);
  18726. }
  18727. TEST(ParseUrlTest, VariousPatterns) {
  18728. {
  18729. detail::UrlComponents uc;
  18730. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18731. EXPECT_EQ("http", uc.scheme);
  18732. EXPECT_EQ("example.com", uc.host);
  18733. EXPECT_EQ("8080", uc.port);
  18734. EXPECT_EQ("/path", uc.path);
  18735. EXPECT_EQ("?q=1", uc.query);
  18736. }
  18737. {
  18738. detail::UrlComponents uc;
  18739. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18740. EXPECT_EQ("https", uc.scheme);
  18741. EXPECT_EQ("example.com", uc.host);
  18742. EXPECT_TRUE(uc.port.empty());
  18743. EXPECT_EQ("/path", uc.path);
  18744. }
  18745. {
  18746. detail::UrlComponents uc;
  18747. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18748. EXPECT_EQ("::1", uc.host);
  18749. EXPECT_EQ("8080", uc.port);
  18750. EXPECT_EQ("/path", uc.path);
  18751. }
  18752. {
  18753. detail::UrlComponents uc;
  18754. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18755. }
  18756. {
  18757. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18758. // the path while the connection still targets the bracketed host.
  18759. detail::UrlComponents uc;
  18760. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18761. }
  18762. {
  18763. detail::UrlComponents uc;
  18764. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18765. }
  18766. {
  18767. detail::UrlComponents uc;
  18768. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18769. EXPECT_EQ("::1", uc.host);
  18770. EXPECT_TRUE(uc.port.empty());
  18771. EXPECT_EQ("/path", uc.path);
  18772. }
  18773. {
  18774. detail::UrlComponents uc;
  18775. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18776. EXPECT_TRUE(uc.scheme.empty());
  18777. EXPECT_EQ("example.com", uc.host);
  18778. EXPECT_EQ("/path", uc.path);
  18779. EXPECT_EQ("?q=1", uc.query);
  18780. }
  18781. {
  18782. detail::UrlComponents uc;
  18783. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18784. EXPECT_TRUE(uc.host.empty());
  18785. EXPECT_EQ("/path", uc.path);
  18786. EXPECT_EQ("?q=1", uc.query);
  18787. }
  18788. {
  18789. detail::UrlComponents uc;
  18790. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18791. EXPECT_EQ("example.com", uc.host);
  18792. EXPECT_EQ("8080", uc.port);
  18793. }
  18794. {
  18795. // Unix socket path — must not be parsed as host
  18796. detail::UrlComponents uc;
  18797. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18798. EXPECT_TRUE(uc.host.empty());
  18799. }
  18800. {
  18801. detail::UrlComponents uc;
  18802. ASSERT_TRUE(detail::parse_url("", uc));
  18803. EXPECT_TRUE(uc.host.empty());
  18804. EXPECT_TRUE(uc.path.empty());
  18805. }
  18806. {
  18807. detail::UrlComponents uc;
  18808. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18809. EXPECT_EQ("http", uc.scheme);
  18810. }
  18811. {
  18812. detail::UrlComponents uc;
  18813. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18814. }
  18815. {
  18816. // Accepted by parse_url; callers restrict to http/https
  18817. detail::UrlComponents uc;
  18818. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18819. EXPECT_EQ("ftp", uc.scheme);
  18820. }
  18821. {
  18822. detail::UrlComponents uc;
  18823. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18824. }
  18825. {
  18826. detail::UrlComponents uc;
  18827. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18828. }
  18829. }
  18830. TEST(ParseUrlTest, FragmentHandling) {
  18831. {
  18832. detail::UrlComponents uc;
  18833. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18834. EXPECT_EQ("/path", uc.path);
  18835. EXPECT_TRUE(uc.query.empty());
  18836. }
  18837. {
  18838. detail::UrlComponents uc;
  18839. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18840. EXPECT_TRUE(uc.path.empty());
  18841. EXPECT_TRUE(uc.query.empty());
  18842. }
  18843. }
  18844. TEST(ParseUrlTest, UserinfoHandling) {
  18845. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18846. // parsers would see evil.com as the host.
  18847. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18848. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18849. for (auto url : urls) {
  18850. detail::UrlComponents uc;
  18851. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18852. }
  18853. }
  18854. TEST(ParseUrlTest, IPv6EdgeCases) {
  18855. {
  18856. detail::UrlComponents uc;
  18857. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18858. EXPECT_TRUE(uc.scheme.empty());
  18859. EXPECT_EQ("::1", uc.host);
  18860. EXPECT_EQ("8080", uc.port);
  18861. }
  18862. {
  18863. // Zone ID '%25' is not in [a-fA-F0-9:]
  18864. detail::UrlComponents uc;
  18865. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18866. }
  18867. }
  18868. TEST(ParseUrlTest, SchemeEdgeCases) {
  18869. {
  18870. detail::UrlComponents uc;
  18871. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18872. }
  18873. {
  18874. detail::UrlComponents uc;
  18875. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18876. }
  18877. {
  18878. detail::UrlComponents uc;
  18879. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18880. }
  18881. {
  18882. detail::UrlComponents uc;
  18883. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18884. EXPECT_EQ("https", uc.scheme);
  18885. }
  18886. }
  18887. TEST(ParseUrlTest, PortEdgeCases) {
  18888. {
  18889. detail::UrlComponents uc;
  18890. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18891. EXPECT_TRUE(uc.port.empty());
  18892. EXPECT_EQ("/path", uc.path);
  18893. }
  18894. {
  18895. // parse_url accepts any port string; validation is done by parse_port
  18896. detail::UrlComponents uc;
  18897. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18898. EXPECT_EQ("abc", uc.port);
  18899. }
  18900. }
  18901. TEST(ParseUrlTest, WebSocketPatterns) {
  18902. {
  18903. detail::UrlComponents uc;
  18904. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18905. EXPECT_EQ("ws", uc.scheme);
  18906. EXPECT_EQ("echo.example.com", uc.host);
  18907. EXPECT_EQ("8080", uc.port);
  18908. EXPECT_EQ("/ws", uc.path);
  18909. }
  18910. {
  18911. detail::UrlComponents uc;
  18912. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18913. EXPECT_EQ("wss", uc.scheme);
  18914. EXPECT_EQ("echo.example.com", uc.host);
  18915. EXPECT_TRUE(uc.port.empty());
  18916. EXPECT_EQ("/ws", uc.path);
  18917. }
  18918. }
  18919. TEST(ParseUrlTest, QueryOnly) {
  18920. detail::UrlComponents uc;
  18921. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18922. EXPECT_TRUE(uc.host.empty());
  18923. EXPECT_TRUE(uc.path.empty());
  18924. EXPECT_EQ("?q=1&r=2", uc.query);
  18925. }
  18926. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18927. detail::UrlComponents uc;
  18928. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18929. EXPECT_TRUE(uc.scheme.empty());
  18930. EXPECT_EQ("example.com", uc.host);
  18931. EXPECT_EQ("443", uc.port);
  18932. EXPECT_EQ("/path", uc.path);
  18933. }
  18934. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18935. // If ipv6 regex working, regex match codepath is taken.
  18936. // else port will default to 80 in Client impl
  18937. int clientImplMagicPort = 80;
  18938. int port = 4321;
  18939. // above ports must be different to avoid false negative
  18940. EXPECT_NE(clientImplMagicPort, port);
  18941. std::string ipV6TestURL = "http://[ff06::c3]";
  18942. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18943. CLIENT_PRIVATE_KEY_FILE);
  18944. EXPECT_EQ(cli.port(), port);
  18945. }
  18946. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18947. auto file_path = "./www/dir/index.html";
  18948. auto dir_path = "./www/dir";
  18949. detail::FileStat stat_file(file_path);
  18950. EXPECT_TRUE(stat_file.is_file());
  18951. EXPECT_FALSE(stat_file.is_dir());
  18952. detail::FileStat stat_dir(dir_path);
  18953. EXPECT_FALSE(stat_dir.is_file());
  18954. EXPECT_TRUE(stat_dir.is_dir());
  18955. }
  18956. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18957. // IPv4 with default HTTP port (80)
  18958. EXPECT_EQ("example.com",
  18959. detail::make_host_and_port_string("example.com", 80, false));
  18960. // IPv4 with default HTTPS port (443)
  18961. EXPECT_EQ("example.com",
  18962. detail::make_host_and_port_string("example.com", 443, true));
  18963. // IPv4 with non-default HTTP port
  18964. EXPECT_EQ("example.com:8080",
  18965. detail::make_host_and_port_string("example.com", 8080, false));
  18966. // IPv4 with non-default HTTPS port
  18967. EXPECT_EQ("example.com:8443",
  18968. detail::make_host_and_port_string("example.com", 8443, true));
  18969. // IPv6 with default HTTP port (80)
  18970. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18971. // IPv6 with default HTTPS port (443)
  18972. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18973. // IPv6 with non-default HTTP port
  18974. EXPECT_EQ("[::1]:8080",
  18975. detail::make_host_and_port_string("::1", 8080, false));
  18976. // IPv6 with non-default HTTPS port
  18977. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18978. // IPv6 full address with default port
  18979. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18980. detail::make_host_and_port_string(
  18981. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18982. // IPv6 full address with non-default port
  18983. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18984. detail::make_host_and_port_string(
  18985. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18986. // IPv6 localhost with non-default port
  18987. EXPECT_EQ("[::1]:3000",
  18988. detail::make_host_and_port_string("::1", 3000, false));
  18989. // IPv6 with zone ID (link-local address) with default port
  18990. EXPECT_EQ("[fe80::1%eth0]",
  18991. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18992. // IPv6 with zone ID (link-local address) with non-default port
  18993. EXPECT_EQ("[fe80::1%eth0]:8080",
  18994. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18995. // Edge case: Port 443 with is_ssl=false (should add port)
  18996. EXPECT_EQ("example.com:443",
  18997. detail::make_host_and_port_string("example.com", 443, false));
  18998. // Edge case: Port 80 with is_ssl=true (should add port)
  18999. EXPECT_EQ("example.com:80",
  19000. detail::make_host_and_port_string("example.com", 80, true));
  19001. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19002. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19003. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19004. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19005. // Security fix: Already bracketed IPv6 should not get double brackets
  19006. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19007. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19008. EXPECT_EQ("[::1]:8080",
  19009. detail::make_host_and_port_string("[::1]", 8080, false));
  19010. EXPECT_EQ("[2001:db8::1]:8080",
  19011. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19012. EXPECT_EQ("[fe80::1%eth0]",
  19013. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19014. EXPECT_EQ("[fe80::1%eth0]:8080",
  19015. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19016. // Edge case: Empty host (should return as-is)
  19017. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19018. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19019. // This is a known limitation but shouldn't crash
  19020. EXPECT_EQ("[host:name]",
  19021. detail::make_host_and_port_string("host:name", 80, false));
  19022. // Port number edge cases (no validation, but should not crash)
  19023. EXPECT_EQ("example.com:0",
  19024. detail::make_host_and_port_string("example.com", 0, false));
  19025. EXPECT_EQ("example.com:-1",
  19026. detail::make_host_and_port_string("example.com", -1, false));
  19027. EXPECT_EQ("example.com:65535",
  19028. detail::make_host_and_port_string("example.com", 65535, false));
  19029. EXPECT_EQ("example.com:65536",
  19030. detail::make_host_and_port_string("example.com", 65536, false));
  19031. }
  19032. namespace httplib {
  19033. namespace detail {
  19034. std::string
  19035. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19036. const std::string &host, int port);
  19037. } // namespace detail
  19038. } // namespace httplib
  19039. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19040. std::map<std::string, std::string> addr_map = {
  19041. {"ipv4.example", "192.0.2.10"},
  19042. {"ipv6.example", "2001:db8::1"},
  19043. {"name.example", "internal.example.lan"},
  19044. {"empty.example", ""}};
  19045. EXPECT_EQ("192.0.2.10:443",
  19046. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19047. EXPECT_EQ("[2001:db8::1]:443",
  19048. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19049. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19050. addr_map, "name.example", 8443));
  19051. // An empty or absent mapping keeps the hostname as the target
  19052. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19053. addr_map, "empty.example", 443));
  19054. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19055. addr_map, "other.example", 443));
  19056. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19057. }
  19058. #ifdef CPPHTTPLIB_SSL_ENABLED
  19059. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19060. httplib::SSLClient cli("roblox.com", 443);
  19061. cli.set_follow_location(true);
  19062. auto res = cli.Get("/");
  19063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19064. EXPECT_EQ(StatusCode::OK_200, res->status);
  19065. }
  19066. #endif
  19067. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19068. Server svr;
  19069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19070. EXPECT_EQ(res.status, 400);
  19071. });
  19072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19073. auto se = detail::scope_exit([&] {
  19074. svr.stop();
  19075. thread.join();
  19076. ASSERT_FALSE(svr.is_running());
  19077. });
  19078. svr.wait_until_ready();
  19079. Client cli(HOST, PORT);
  19080. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19081. }
  19082. TEST(InvalidHeaderCharsTest, is_field_name) {
  19083. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19084. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19085. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19086. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19087. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19088. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19089. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19090. EXPECT_FALSE(detail::fields::is_field_name(""));
  19091. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19092. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19093. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19094. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19095. }
  19096. TEST(InvalidHeaderCharsTest, is_field_value) {
  19097. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19098. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19099. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19100. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19101. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19102. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19103. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19104. EXPECT_TRUE(detail::fields::is_field_value(""));
  19105. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19106. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19107. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19108. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19109. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19110. }
  19111. TEST(InvalidHeaderCharsTest, OnServer) {
  19112. Server svr;
  19113. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19114. std::string header = "Not Set";
  19115. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19116. res.set_header(header, "value");
  19117. res.set_content("Page Content Page Content", "text/plain");
  19118. });
  19119. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19120. std::string header = "Not Set";
  19121. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19122. res.set_header("X-Test", header);
  19123. res.set_content("Page Content Page Content", "text/plain");
  19124. });
  19125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19126. auto se = detail::scope_exit([&] {
  19127. svr.stop();
  19128. thread.join();
  19129. ASSERT_FALSE(svr.is_running());
  19130. });
  19131. svr.wait_until_ready();
  19132. Client cli(HOST, PORT);
  19133. {
  19134. auto res = cli.Get(
  19135. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19137. EXPECT_EQ("Page Content Page Content", res->body);
  19138. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19139. }
  19140. {
  19141. auto res = cli.Get(
  19142. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19144. EXPECT_EQ("Page Content Page Content", res->body);
  19145. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19146. }
  19147. }
  19148. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19149. auto handled = false;
  19150. Server svr;
  19151. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19152. thread t = thread([&] { svr.listen(HOST, PORT); });
  19153. auto se = detail::scope_exit([&] {
  19154. svr.stop();
  19155. t.join();
  19156. ASSERT_FALSE(svr.is_running());
  19157. ASSERT_FALSE(handled);
  19158. });
  19159. svr.wait_until_ready();
  19160. auto req = "POST /test HTTP/1.1\r\n"
  19161. "Content-Length: x\r\n"
  19162. "\r\n";
  19163. std::string response;
  19164. ASSERT_TRUE(send_request(1, req, &response));
  19165. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19166. response.substr(0, response.find("\r\n")));
  19167. }
  19168. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19169. // case-insensitive, and a server that receives a 100-continue expectation in
  19170. // an HTTP/1.0 request MUST ignore it.
  19171. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19172. std::string response;
  19173. ASSERT_TRUE(send_request(1, req, &response, port));
  19174. *got_100 = response.find("100 Continue") != std::string::npos;
  19175. }
  19176. class ExpectTokenTest : public ::testing::Test {
  19177. protected:
  19178. void SetUp() override {
  19179. svr_.Post("/p", [](const Request &, Response &res) {
  19180. res.set_content("ok", "text/plain");
  19181. });
  19182. port_ = svr_.bind_to_any_port(HOST);
  19183. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19184. svr_.wait_until_ready();
  19185. }
  19186. void TearDown() override {
  19187. svr_.stop();
  19188. if (thread_.joinable()) { thread_.join(); }
  19189. }
  19190. std::string request(const char *version, const char *expect_value) const {
  19191. return std::string("POST /p ") + version +
  19192. "\r\n"
  19193. "Host: localhost\r\n"
  19194. "Content-Length: 2\r\n"
  19195. "Connection: close\r\n"
  19196. "Expect: " +
  19197. expect_value +
  19198. "\r\n"
  19199. "\r\n"
  19200. "hi";
  19201. }
  19202. Server svr_;
  19203. int port_ = 0;
  19204. thread thread_;
  19205. };
  19206. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19207. bool got_100 = false;
  19208. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19209. EXPECT_TRUE(got_100);
  19210. }
  19211. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19212. bool got_100 = true;
  19213. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19214. EXPECT_FALSE(got_100);
  19215. }
  19216. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19217. bool got_100 = false;
  19218. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19219. EXPECT_TRUE(got_100);
  19220. }
  19221. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19222. bool got_100 = false;
  19223. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19224. EXPECT_TRUE(got_100);
  19225. }
  19226. // `100 Continue` is sent only when the server starts reading the body, so a
  19227. // request rejected before that never invites the client to send it. The
  19228. // requests below carry the expectation but withhold the body, as a client
  19229. // waiting for `100 Continue` would.
  19230. // A POST that expects `100 Continue` and withholds its two-byte body.
  19231. static std::string expect_headers_only(const std::string &path) {
  19232. return "POST " + path +
  19233. " HTTP/1.1\r\n"
  19234. "Host: localhost\r\n"
  19235. "Content-Length: 2\r\n"
  19236. "Expect: 100-continue\r\n"
  19237. "\r\n";
  19238. }
  19239. class ExpectLazyContinueTest : public ::testing::Test {
  19240. protected:
  19241. void SetUp() override {
  19242. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19243. if (req.path == "/pre-routing") {
  19244. res.status = StatusCode::Unauthorized_401;
  19245. return Server::HandlerResponse::Handled;
  19246. }
  19247. return Server::HandlerResponse::Unhandled;
  19248. });
  19249. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19250. if (req.matched_route == "/pre-request") {
  19251. res.status = StatusCode::Forbidden_403;
  19252. return Server::HandlerResponse::Handled;
  19253. }
  19254. return Server::HandlerResponse::Unhandled;
  19255. });
  19256. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19257. res.set_content("ok", "text/plain");
  19258. });
  19259. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19260. res.set_content("ok", "text/plain");
  19261. });
  19262. svr_.Post("/reader-used", [](const Request &, Response &res,
  19263. const ContentReader &content_reader) {
  19264. std::string body;
  19265. content_reader([&](const char *data, size_t len) {
  19266. body.append(data, len);
  19267. return true;
  19268. });
  19269. res.set_content(body, "text/plain");
  19270. });
  19271. svr_.Post("/reader-unused",
  19272. [](const Request &, Response &res, const ContentReader &) {
  19273. res.set_content("ignored", "text/plain");
  19274. });
  19275. port_ = svr_.bind_to_any_port(HOST);
  19276. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19277. svr_.wait_until_ready();
  19278. }
  19279. void TearDown() override {
  19280. svr_.stop();
  19281. if (thread_.joinable()) { thread_.join(); }
  19282. }
  19283. // Sends `req` and reads until the server closes the connection. Returns
  19284. // false if the read had to wait for the client-side timeout instead.
  19285. bool send_until_closed(const std::string &req, std::string *resp) const {
  19286. auto start = std::chrono::steady_clock::now();
  19287. if (!send_request(3, req, resp, port_)) { return false; }
  19288. auto elapsed = std::chrono::steady_clock::now() - start;
  19289. return elapsed < std::chrono::seconds(2);
  19290. }
  19291. // The final response comes without `100 Continue`, and the server closes
  19292. // the connection since the body may or may not follow.
  19293. void expect_final_without_interim(const std::string &path,
  19294. const char *status_line) const {
  19295. std::string resp;
  19296. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19297. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19298. EXPECT_EQ(0u, resp.find(status_line));
  19299. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19300. }
  19301. Server svr_;
  19302. int port_ = 0;
  19303. thread thread_;
  19304. };
  19305. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19306. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19307. }
  19308. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19309. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19310. }
  19311. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19312. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19313. }
  19314. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19315. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19316. }
  19317. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19318. // The body follows once `100 Continue` has had time to arrive.
  19319. auto req = expect_headers_only("/reader-used");
  19320. req.insert(req.size() - 2, "Connection: close\r\n");
  19321. std::string resp;
  19322. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19323. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19324. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19325. EXPECT_NE(std::string::npos, resp.find("hi"));
  19326. }
  19327. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19328. // Large enough for the client to add `Expect: 100-continue` itself.
  19329. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19330. std::atomic<bool> body_sent{false};
  19331. Client cli(HOST, port_);
  19332. auto res = cli.Post(
  19333. "/pre-request", length,
  19334. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19335. body_sent = true;
  19336. std::string chunk(len, 'x');
  19337. sink.write(chunk.data(), chunk.size());
  19338. return true;
  19339. },
  19340. "application/octet-stream");
  19341. ASSERT_TRUE(res);
  19342. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19343. EXPECT_FALSE(body_sent);
  19344. }
  19345. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19346. Server svr;
  19347. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19348. return StatusCode::ExpectationFailed_417;
  19349. });
  19350. svr.Post("/p", [](const Request &, Response &res) {
  19351. res.set_content("ok", "text/plain");
  19352. });
  19353. auto port = svr.bind_to_any_port(HOST);
  19354. thread t = thread([&] { svr.listen_after_bind(); });
  19355. auto se = detail::scope_exit([&] {
  19356. svr.stop();
  19357. t.join();
  19358. });
  19359. svr.wait_until_ready();
  19360. std::string resp;
  19361. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19362. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19363. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19364. // Exactly one response: the route handler must not run after the 417.
  19365. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19366. }
  19367. #ifndef _WIN32
  19368. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19369. static constexpr char reject[] = "Unauthorized";
  19370. static constexpr char accept[] = "Upload accepted";
  19371. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19372. Server svr;
  19373. svr.set_expect_100_continue_handler(
  19374. [](const Request & /*req*/, Response &res) {
  19375. res.status = StatusCode::Unauthorized_401;
  19376. res.set_content(reject, "text/plain");
  19377. return res.status;
  19378. });
  19379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19380. res.set_content(accept, "text/plain");
  19381. });
  19382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19383. auto se = detail::scope_exit([&] {
  19384. svr.stop();
  19385. thread.join();
  19386. ASSERT_FALSE(svr.is_running());
  19387. });
  19388. svr.wait_until_ready();
  19389. {
  19390. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19391. curl_easy_init(), &curl_easy_cleanup};
  19392. ASSERT_NE(curl, nullptr);
  19393. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19394. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19395. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19396. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19397. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19398. &curl_slist_free_all};
  19399. ASSERT_NE(list, nullptr);
  19400. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19401. struct read_data {
  19402. uint64_t read_size;
  19403. uint64_t total_size;
  19404. } data = {0, total_size};
  19405. using read_callback_t =
  19406. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19407. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19408. void *userdata) -> size_t {
  19409. read_data *d = (read_data *)userdata;
  19410. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19411. std::fill_n(ptr, size * nmemb, 'A');
  19412. d->read_size += size * nmemb;
  19413. return size * nmemb;
  19414. };
  19415. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19416. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19417. std::vector<char> buffer;
  19418. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19419. using write_callback_t =
  19420. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19421. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19422. void *userdata) -> size_t {
  19423. std::vector<char> *buf = (std::vector<char> *)userdata;
  19424. buf->reserve(buf->size() + size * nmemb + 1);
  19425. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19426. return size * nmemb;
  19427. };
  19428. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19429. {
  19430. const auto res = curl_easy_perform(curl.get());
  19431. ASSERT_EQ(res, CURLE_OK);
  19432. }
  19433. {
  19434. auto response_code = long{};
  19435. const auto res =
  19436. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19437. ASSERT_EQ(res, CURLE_OK);
  19438. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19439. }
  19440. {
  19441. auto dl = curl_off_t{};
  19442. const auto res =
  19443. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19444. ASSERT_EQ(res, CURLE_OK);
  19445. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19446. }
  19447. {
  19448. buffer.push_back('\0');
  19449. ASSERT_STRCASEEQ(buffer.data(), reject);
  19450. }
  19451. }
  19452. }
  19453. #endif
  19454. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19455. // Regression test for #2458.
  19456. //
  19457. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19458. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19459. // ticket can make the client socket spuriously readable during the
  19460. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19461. // the client withholds the body and then blocks reading a response that never
  19462. // comes, failing with `Failed to read connection`.
  19463. //
  19464. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19465. // within the timeout. This raw OpenSSL server deliberately never sends
  19466. // `100 Continue`; the client must still deliver the body and receive 200.
  19467. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19468. signal(SIGPIPE, SIG_IGN);
  19469. const auto port = PORT + 4;
  19470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19471. ASSERT_NE(srv, INVALID_SOCKET);
  19472. int opt = 1;
  19473. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19474. sockaddr_in addr{};
  19475. addr.sin_family = AF_INET;
  19476. addr.sin_port = htons(static_cast<uint16_t>(port));
  19477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19478. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19479. ASSERT_EQ(0, ::listen(srv, 1));
  19480. std::atomic<size_t> server_body_bytes{0};
  19481. auto server_thread = std::thread([&] {
  19482. sockaddr_in cli_addr{};
  19483. socklen_t cli_len = sizeof(cli_addr);
  19484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19485. if (cli == INVALID_SOCKET) { return; }
  19486. // Bound the lifetime of the server side so a buggy client (which never
  19487. // sends the body) cannot make this thread block forever on join.
  19488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19489. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19490. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19491. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19492. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19493. SSL *ssl = SSL_new(ctx);
  19494. SSL_set_fd(ssl, static_cast<int>(cli));
  19495. if (SSL_accept(ssl) > 0) {
  19496. // Read the request headers. Reading here also flushes the TLS 1.3
  19497. // session tickets to the client. Deliberately do NOT send
  19498. // `100 Continue`.
  19499. std::string buf;
  19500. char tmp[1024];
  19501. while (buf.find("\r\n\r\n") == std::string::npos) {
  19502. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19503. if (n <= 0) { break; }
  19504. buf.append(tmp, static_cast<size_t>(n));
  19505. }
  19506. // A correct client sends the body now; count what arrives.
  19507. auto pos = buf.find("\r\n\r\n");
  19508. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19509. while (body < 4096) {
  19510. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19511. if (n <= 0) { break; }
  19512. body += static_cast<size_t>(n);
  19513. }
  19514. server_body_bytes = body;
  19515. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19516. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19517. SSL_shutdown(ssl);
  19518. }
  19519. SSL_free(ssl);
  19520. detail::close_socket(cli);
  19521. SSL_CTX_free(ctx);
  19522. });
  19523. auto se = detail::scope_exit([&] {
  19524. server_thread.join();
  19525. detail::close_socket(srv);
  19526. });
  19527. SSLClient cli("127.0.0.1", port);
  19528. cli.enable_server_certificate_verification(false);
  19529. cli.set_connection_timeout(5, 0);
  19530. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19531. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19532. std::string body(4096, 'A');
  19533. auto res = cli.Put("/api/test", body, "application/json");
  19534. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19535. EXPECT_EQ(StatusCode::OK_200, res->status);
  19536. EXPECT_EQ(body.size(), server_body_bytes.load());
  19537. }
  19538. #endif
  19539. template <typename S, typename C>
  19540. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19541. svr.Get("/stream", [&](const Request &, Response &res) {
  19542. auto data = new std::string("01234567890123456789");
  19543. res.set_content_provider(
  19544. data->size(), "text/plain",
  19545. [&, data](size_t offset, size_t length, DataSink &sink) {
  19546. const size_t DATA_CHUNK_SIZE = 4;
  19547. const auto &d = *data;
  19548. std::this_thread::sleep_for(std::chrono::seconds(1));
  19549. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19550. return true;
  19551. },
  19552. [data](bool success) {
  19553. EXPECT_FALSE(success);
  19554. delete data;
  19555. });
  19556. });
  19557. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19558. auto i = new size_t(0);
  19559. res.set_content_provider(
  19560. "text/plain",
  19561. [i](size_t, DataSink &sink) {
  19562. if (*i < 5) {
  19563. std::this_thread::sleep_for(std::chrono::seconds(1));
  19564. sink.write("abcd", 4);
  19565. (*i)++;
  19566. } else {
  19567. sink.done();
  19568. }
  19569. return true;
  19570. },
  19571. [i](bool success) {
  19572. EXPECT_FALSE(success);
  19573. delete i;
  19574. });
  19575. });
  19576. svr.Get("/chunked", [&](const Request &, Response &res) {
  19577. auto i = new size_t(0);
  19578. res.set_chunked_content_provider(
  19579. "text/plain",
  19580. [i](size_t, DataSink &sink) {
  19581. if (*i < 5) {
  19582. std::this_thread::sleep_for(std::chrono::seconds(1));
  19583. sink.os << "abcd";
  19584. (*i)++;
  19585. } else {
  19586. sink.done();
  19587. }
  19588. return true;
  19589. },
  19590. [i](bool success) {
  19591. EXPECT_FALSE(success);
  19592. delete i;
  19593. });
  19594. });
  19595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19596. auto se = detail::scope_exit([&] {
  19597. svr.stop();
  19598. listen_thread.join();
  19599. ASSERT_FALSE(svr.is_running());
  19600. });
  19601. svr.wait_until_ready();
  19602. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19603. {
  19604. auto start = std::chrono::steady_clock::now();
  19605. auto res = cli.Get("/stream");
  19606. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19607. std::chrono::steady_clock::now() - start)
  19608. .count();
  19609. ASSERT_FALSE(res);
  19610. EXPECT_EQ(Error::Read, res.error());
  19611. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19612. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19613. }
  19614. {
  19615. auto start = std::chrono::steady_clock::now();
  19616. auto res = cli.Get("/stream_without_length");
  19617. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19618. std::chrono::steady_clock::now() - start)
  19619. .count();
  19620. ASSERT_FALSE(res);
  19621. EXPECT_EQ(Error::Read, res.error());
  19622. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19623. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19624. }
  19625. {
  19626. auto start = std::chrono::steady_clock::now();
  19627. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19628. EXPECT_EQ("abcd", string(data, data_length));
  19629. return true;
  19630. });
  19631. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19632. std::chrono::steady_clock::now() - start)
  19633. .count();
  19634. ASSERT_FALSE(res);
  19635. EXPECT_EQ(Error::Read, res.error());
  19636. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19637. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19638. }
  19639. }
  19640. TEST(MaxTimeoutTest, ContentStream) {
  19641. time_t timeout = 2000;
  19642. time_t threshold = 200;
  19643. Server svr;
  19644. Client cli("localhost", PORT);
  19645. max_timeout_test(svr, cli, timeout, threshold);
  19646. }
  19647. #ifdef CPPHTTPLIB_SSL_ENABLED
  19648. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19649. time_t timeout = 2000;
  19650. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19652. SSLClient cli("localhost", PORT);
  19653. cli.enable_server_certificate_verification(false);
  19654. max_timeout_test(svr, cli, timeout, threshold);
  19655. }
  19656. #endif
  19657. class EventDispatcher {
  19658. public:
  19659. EventDispatcher() {}
  19660. bool wait_event(DataSink *sink) {
  19661. unique_lock<mutex> lk(m_);
  19662. int id = id_;
  19663. // Wait with timeout to prevent hanging if client disconnects
  19664. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19665. [&] { return cid_ == id; })) {
  19666. return false; // Timeout occurred
  19667. }
  19668. sink->write(message_.data(), message_.size());
  19669. return true;
  19670. }
  19671. void send_event(const string &message) {
  19672. lock_guard<mutex> lk(m_);
  19673. cid_ = id_++;
  19674. message_ = message;
  19675. cv_.notify_all();
  19676. }
  19677. private:
  19678. mutex m_;
  19679. condition_variable cv_;
  19680. atomic_int id_{0};
  19681. atomic_int cid_{-1};
  19682. string message_;
  19683. };
  19684. TEST(ClientInThreadTest, Issue2068) {
  19685. EventDispatcher ed;
  19686. Server svr;
  19687. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19688. res.set_chunked_content_provider("text/event-stream",
  19689. [&](size_t /*offset*/, DataSink &sink) {
  19690. return ed.wait_event(&sink);
  19691. });
  19692. });
  19693. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19694. svr.wait_until_ready();
  19695. thread event_thread([&] {
  19696. int id = 0;
  19697. while (svr.is_running()) {
  19698. this_thread::sleep_for(chrono::milliseconds(500));
  19699. std::stringstream ss;
  19700. ss << "data: " << id << "\n\n";
  19701. ed.send_event(ss.str());
  19702. id++;
  19703. }
  19704. });
  19705. auto se = detail::scope_exit([&] {
  19706. svr.stop();
  19707. listen_thread.join();
  19708. event_thread.join();
  19709. ASSERT_FALSE(svr.is_running());
  19710. });
  19711. {
  19712. auto client = detail::make_unique<Client>(HOST, PORT);
  19713. client->set_read_timeout(std::chrono::minutes(10));
  19714. std::atomic<bool> stop{false};
  19715. std::thread t([&] {
  19716. client->Get("/event1",
  19717. [&](const char *, size_t) -> bool { return !stop; });
  19718. });
  19719. std::this_thread::sleep_for(std::chrono::seconds(2));
  19720. stop = true;
  19721. client->stop();
  19722. t.join();
  19723. // Reset client after thread has finished
  19724. client.reset();
  19725. }
  19726. }
  19727. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19728. auto handled = false;
  19729. Server svr;
  19730. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19731. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19732. auto se = detail::scope_exit([&] {
  19733. svr.stop();
  19734. t.join();
  19735. ASSERT_FALSE(svr.is_running());
  19736. ASSERT_FALSE(handled);
  19737. });
  19738. svr.wait_until_ready();
  19739. // Two Content-Length headers with different values — must be rejected
  19740. auto req = "POST /test HTTP/1.1\r\n"
  19741. "Content-Length: 5\r\n"
  19742. "Content-Length: 10\r\n"
  19743. "\r\n"
  19744. "hello";
  19745. std::string response;
  19746. ASSERT_TRUE(send_request(1, req, &response));
  19747. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19748. response.substr(0, response.find("\r\n")));
  19749. }
  19750. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19751. auto handled = false;
  19752. Server svr;
  19753. svr.Post("/test", [&](const Request &, Response &res) {
  19754. handled = true;
  19755. res.set_content("ok", "text/plain");
  19756. });
  19757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19758. auto se = detail::scope_exit([&] {
  19759. svr.stop();
  19760. t.join();
  19761. ASSERT_FALSE(svr.is_running());
  19762. ASSERT_TRUE(handled);
  19763. });
  19764. svr.wait_until_ready();
  19765. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19766. auto req = "POST /test HTTP/1.1\r\n"
  19767. "Host: localhost\r\n"
  19768. "Content-Length: 5\r\n"
  19769. "Content-Length: 5\r\n"
  19770. "\r\n"
  19771. "hello";
  19772. std::string response;
  19773. ASSERT_TRUE(send_request(1, req, &response));
  19774. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19775. }
  19776. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19777. Server svr;
  19778. svr.Get("/test", [](const Request &, Response &res) {
  19779. res.set_content("ok", "text/plain");
  19780. });
  19781. auto port = svr.bind_to_any_port(HOST);
  19782. thread t = thread([&] { svr.listen_after_bind(); });
  19783. auto se = detail::scope_exit([&] {
  19784. svr.stop();
  19785. t.join();
  19786. ASSERT_FALSE(svr.is_running());
  19787. });
  19788. svr.wait_until_ready();
  19789. auto status_line = [&](const std::string &host_lines) {
  19790. std::string res;
  19791. send_request(
  19792. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19793. &res, port);
  19794. return res.substr(0, res.find("\r\n"));
  19795. };
  19796. const char *accepted[] = {
  19797. "Host: localhost\r\n",
  19798. "Host: a.example:8080\r\n",
  19799. "Host: my_service\r\n",
  19800. "Host: [::1]:8080\r\n",
  19801. "Host: [fe80::1%25eth0]\r\n",
  19802. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19803. };
  19804. for (auto host_lines : accepted) {
  19805. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19806. }
  19807. const char *rejected[] = {
  19808. "Host: a.example\r\nHost: b.example\r\n",
  19809. "Host: a.example\r\nHost: a.example\r\n",
  19810. "Host: a@b.example\r\n",
  19811. "Host: a.example/b\r\n",
  19812. "Host: a.example\\b\r\n",
  19813. "Host: a.example?b\r\n",
  19814. "Host: a.example#b\r\n",
  19815. "Host: a.example b.example\r\n",
  19816. };
  19817. for (auto host_lines : rejected) {
  19818. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19819. << host_lines;
  19820. }
  19821. }
  19822. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19823. Server svr;
  19824. svr.Get("/", [](const Request &req, Response &res) {
  19825. EXPECT_EQ(2U, req.trailers.size());
  19826. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19827. // Denied
  19828. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19829. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19830. // Accepted
  19831. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19832. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19833. EXPECT_TRUE(req.has_trailer("X-World"));
  19834. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19835. res.set_content("ok", "text/plain");
  19836. });
  19837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19838. auto se = detail::scope_exit([&] {
  19839. svr.stop();
  19840. t.join();
  19841. ASSERT_FALSE(svr.is_running());
  19842. });
  19843. svr.wait_until_ready();
  19844. const std::string req = "GET / HTTP/1.1\r\n"
  19845. "Transfer-Encoding: chunked\r\n"
  19846. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19847. "\r\n"
  19848. "0\r\n"
  19849. "Content-Length: 10\r\n"
  19850. "Host: internal.local\r\n"
  19851. "Content-Type: malicious/content\r\n"
  19852. "Cookie: any\r\n"
  19853. "Set-Cookie: any\r\n"
  19854. "X-Forwarded-For: attacker.com\r\n"
  19855. "X-Real-Ip: 1.1.1.1\r\n"
  19856. "X-Hello: hello\r\n"
  19857. "X-World: world\r\n"
  19858. "\r\n";
  19859. std::string res;
  19860. ASSERT_TRUE(send_request(1, req, &res));
  19861. }
  19862. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19863. // several field lines, and the combined value is what has to be parsed. A
  19864. // Trailer field split across lines therefore declares every name it lists;
  19865. // reading only the first line silently drops the trailers the later lines
  19866. // declare. The prohibited-trailer filter still applies to every line.
  19867. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19868. Server svr;
  19869. size_t observed_trailer_count = 0;
  19870. std::string observed_hello;
  19871. std::string observed_world;
  19872. bool observed_content_length = true;
  19873. svr.Get("/", [&](const Request &req, Response &res) {
  19874. observed_trailer_count = req.trailers.size();
  19875. observed_hello = req.get_trailer_value("X-Hello");
  19876. observed_world = req.get_trailer_value("X-World");
  19877. observed_content_length = req.has_trailer("Content-Length");
  19878. res.set_content("ok", "text/plain");
  19879. });
  19880. auto port = svr.bind_to_any_port(HOST);
  19881. thread t = thread([&]() { svr.listen_after_bind(); });
  19882. auto se = detail::scope_exit([&] {
  19883. svr.stop();
  19884. t.join();
  19885. ASSERT_FALSE(svr.is_running());
  19886. });
  19887. svr.wait_until_ready();
  19888. const std::string req = "GET / HTTP/1.1\r\n"
  19889. "Host: localhost\r\n"
  19890. "Transfer-Encoding: chunked\r\n"
  19891. "Trailer: X-Hello\r\n"
  19892. "Trailer: X-World, Content-Length\r\n"
  19893. "\r\n"
  19894. "0\r\n"
  19895. "X-Hello: hello\r\n"
  19896. "X-World: world\r\n"
  19897. "Content-Length: 10\r\n"
  19898. "\r\n";
  19899. std::string res;
  19900. ASSERT_TRUE(send_request(1, req, &res, port));
  19901. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19902. // Accepted: both field lines contribute to the declared set
  19903. EXPECT_EQ(2U, observed_trailer_count);
  19904. EXPECT_EQ(observed_hello, "hello");
  19905. EXPECT_EQ(observed_world, "world");
  19906. // Denied: a prohibited name stays prohibited on a later field line
  19907. EXPECT_FALSE(observed_content_length);
  19908. }
  19909. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19910. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19911. // unbounded run of fields that are never declared, because the counter would
  19912. // only advance for declared fields.
  19913. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19914. Server svr;
  19915. bool handler_called = false;
  19916. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19917. handler_called = true;
  19918. res.set_content("ok", "text/plain");
  19919. });
  19920. auto port = svr.bind_to_any_port(HOST);
  19921. thread t = thread([&]() { svr.listen_after_bind(); });
  19922. auto se = detail::scope_exit([&] {
  19923. svr.stop();
  19924. t.join();
  19925. ASSERT_FALSE(svr.is_running());
  19926. });
  19927. svr.wait_until_ready();
  19928. // Declare nothing, then send far more undeclared trailer fields than the
  19929. // header-count limit. Parsing must stop and reject the request rather than
  19930. // read every line.
  19931. std::string req = "GET / HTTP/1.1\r\n"
  19932. "Transfer-Encoding: chunked\r\n"
  19933. "\r\n"
  19934. "0\r\n";
  19935. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19936. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19937. }
  19938. req += "\r\n";
  19939. std::string res;
  19940. ASSERT_TRUE(send_request(1, req, &res, port));
  19941. // The request is rejected before the handler runs.
  19942. EXPECT_FALSE(handler_called);
  19943. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19944. }
  19945. // The set of declared trailer names is capped so a peer cannot grow it without
  19946. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19947. // declared past the cap is not honored, even if the field is actually sent.
  19948. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19949. Server svr;
  19950. // One name inside the cap and one past it, so the test tracks the cap rather
  19951. // than a fixed count.
  19952. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19953. const std::string within_cap_name = "X-T-0";
  19954. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19955. bool observed_within_cap = false;
  19956. bool observed_past_cap = false;
  19957. svr.Get("/", [&](const Request &req, Response &res) {
  19958. observed_within_cap = req.has_trailer(within_cap_name);
  19959. observed_past_cap = req.has_trailer(past_cap_name);
  19960. res.set_content("ok", "text/plain");
  19961. });
  19962. auto port = svr.bind_to_any_port(HOST);
  19963. thread t = thread([&]() { svr.listen_after_bind(); });
  19964. auto se = detail::scope_exit([&] {
  19965. svr.stop();
  19966. t.join();
  19967. ASSERT_FALSE(svr.is_running());
  19968. });
  19969. svr.wait_until_ready();
  19970. // Declare more trailer names than the cap in a single Trailer field, then
  19971. // actually send the first (within the cap) and the last (past it).
  19972. std::string trailer_decl = "Trailer: ";
  19973. for (int i = 0; i < declared_count; i++) {
  19974. if (i != 0) { trailer_decl += ", "; }
  19975. trailer_decl += "X-T-" + std::to_string(i);
  19976. }
  19977. trailer_decl += "\r\n";
  19978. const std::string req = "GET / HTTP/1.1\r\n"
  19979. "Host: localhost\r\n"
  19980. "Transfer-Encoding: chunked\r\n" +
  19981. trailer_decl +
  19982. "\r\n"
  19983. "0\r\n" +
  19984. within_cap_name + ": a\r\n" + past_cap_name +
  19985. ": b\r\n"
  19986. "\r\n";
  19987. std::string res;
  19988. ASSERT_TRUE(send_request(1, req, &res, port));
  19989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19990. // A name within the cap is honored; one declared past the cap is dropped.
  19991. EXPECT_TRUE(observed_within_cap);
  19992. EXPECT_FALSE(observed_past_cap);
  19993. }
  19994. // A direct client that is not listed in trusted_proxies must not be able to
  19995. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19996. // the peer address on the actual TCP connection determines whether the
  19997. // header is honored.
  19998. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19999. Server svr;
  20000. // Deliberately does NOT include the loopback address the test client
  20001. // actually connects from, so the direct connection is not a trusted proxy.
  20002. svr.set_trusted_proxies({"203.0.113.66"});
  20003. std::string observed_remote_addr;
  20004. svr.Get("/ip", [&](const Request &req, Response &res) {
  20005. observed_remote_addr = req.remote_addr;
  20006. res.set_content("ok", "text/plain");
  20007. });
  20008. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20009. auto se = detail::scope_exit([&] {
  20010. svr.stop();
  20011. t.join();
  20012. ASSERT_FALSE(svr.is_running());
  20013. });
  20014. svr.wait_until_ready();
  20015. Client cli(HOST, PORT);
  20016. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20018. EXPECT_EQ(StatusCode::OK_200, res->status);
  20019. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20020. // ignored entirely and the real connection-level address retained.
  20021. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20022. observed_remote_addr == "127.0.0.1");
  20023. }
  20024. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20025. Server svr;
  20026. std::string observed_remote_addr;
  20027. std::string observed_xff;
  20028. svr.Get("/ip", [&](const Request &req, Response &res) {
  20029. observed_remote_addr = req.remote_addr;
  20030. observed_xff = req.get_header_value("X-Forwarded-For");
  20031. res.set_content("ok", "text/plain");
  20032. });
  20033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20034. auto se = detail::scope_exit([&] {
  20035. svr.stop();
  20036. t.join();
  20037. ASSERT_FALSE(svr.is_running());
  20038. });
  20039. svr.wait_until_ready();
  20040. Client cli(HOST, PORT);
  20041. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20043. EXPECT_EQ(StatusCode::OK_200, res->status);
  20044. EXPECT_EQ(observed_xff, "203.0.113.66");
  20045. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20046. observed_remote_addr == "127.0.0.1");
  20047. }
  20048. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20049. Server svr;
  20050. svr.set_trusted_proxies({"203.0.113.66"});
  20051. std::string observed_remote_addr;
  20052. std::string observed_xff;
  20053. svr.Get("/ip", [&](const Request &req, Response &res) {
  20054. observed_remote_addr = req.remote_addr;
  20055. observed_xff = req.get_header_value("X-Forwarded-For");
  20056. res.set_content("ok", "text/plain");
  20057. });
  20058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20059. auto se = detail::scope_exit([&] {
  20060. svr.stop();
  20061. t.join();
  20062. ASSERT_FALSE(svr.is_running());
  20063. });
  20064. svr.wait_until_ready();
  20065. Client cli(HOST, PORT);
  20066. auto res = cli.Get("/ip");
  20067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20068. EXPECT_EQ(StatusCode::OK_200, res->status);
  20069. EXPECT_EQ(observed_xff, "");
  20070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20071. observed_remote_addr == "127.0.0.1");
  20072. }
  20073. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20074. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20075. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20076. Server svr;
  20077. svr.set_trusted_proxies({"127.0.0.1"});
  20078. svr.Get("/ip", [](const Request &req, Response &res) {
  20079. res.set_content(req.remote_addr, "text/plain");
  20080. });
  20081. auto port = svr.bind_to_any_port("::");
  20082. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20083. thread t = thread([&] { svr.listen_after_bind(); });
  20084. auto se = detail::scope_exit([&] {
  20085. svr.stop();
  20086. t.join();
  20087. ASSERT_FALSE(svr.is_running());
  20088. });
  20089. svr.wait_until_ready();
  20090. Client cli("127.0.0.1", port);
  20091. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20093. EXPECT_EQ("198.51.100.23", res->body);
  20094. }
  20095. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20096. Server svr;
  20097. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20098. svr.Get("/ip", [](const Request &req, Response &res) {
  20099. res.set_content(req.remote_addr, "text/plain");
  20100. });
  20101. auto port = svr.bind_to_any_port(HOST);
  20102. ASSERT_GT(port, 0);
  20103. thread t = thread([&] { svr.listen_after_bind(); });
  20104. auto se = detail::scope_exit([&] {
  20105. svr.stop();
  20106. t.join();
  20107. ASSERT_FALSE(svr.is_running());
  20108. });
  20109. svr.wait_until_ready();
  20110. Client cli(HOST, port);
  20111. auto res = cli.Get(
  20112. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20114. EXPECT_EQ("198.51.100.23", res->body);
  20115. }
  20116. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20117. Server svr;
  20118. // Include the loopback address the test client actually connects from, so
  20119. // the direct connection itself is recognized as the trusted proxy hop.
  20120. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20121. std::string observed_remote_addr;
  20122. std::string observed_xff;
  20123. svr.Get("/ip", [&](const Request &req, Response &res) {
  20124. observed_remote_addr = req.remote_addr;
  20125. observed_xff = req.get_header_value("X-Forwarded-For");
  20126. res.set_content("ok", "text/plain");
  20127. });
  20128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20129. auto se = detail::scope_exit([&] {
  20130. svr.stop();
  20131. t.join();
  20132. ASSERT_FALSE(svr.is_running());
  20133. });
  20134. svr.wait_until_ready();
  20135. Client cli(HOST, PORT);
  20136. auto res = cli.Get(
  20137. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20139. EXPECT_EQ(StatusCode::OK_200, res->status);
  20140. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20141. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20142. }
  20143. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20144. Server svr;
  20145. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20146. std::string observed_remote_addr;
  20147. std::string observed_xff;
  20148. svr.Get("/ip", [&](const Request &req, Response &res) {
  20149. observed_remote_addr = req.remote_addr;
  20150. observed_xff = req.get_header_value("X-Forwarded-For");
  20151. res.set_content("ok", "text/plain");
  20152. });
  20153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20154. auto se = detail::scope_exit([&] {
  20155. svr.stop();
  20156. t.join();
  20157. ASSERT_FALSE(svr.is_running());
  20158. });
  20159. svr.wait_until_ready();
  20160. Client cli(HOST, PORT);
  20161. auto res = cli.Get(
  20162. "/ip",
  20163. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20165. EXPECT_EQ(StatusCode::OK_200, res->status);
  20166. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20167. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20168. }
  20169. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20170. Server svr;
  20171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20172. std::string observed_remote_addr;
  20173. std::string observed_xff;
  20174. svr.Get("/ip", [&](const Request &req, Response &res) {
  20175. observed_remote_addr = req.remote_addr;
  20176. observed_xff = req.get_header_value("X-Forwarded-For");
  20177. res.set_content("ok", "text/plain");
  20178. });
  20179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20180. auto se = detail::scope_exit([&] {
  20181. svr.stop();
  20182. t.join();
  20183. ASSERT_FALSE(svr.is_running());
  20184. });
  20185. svr.wait_until_ready();
  20186. Client cli(HOST, PORT);
  20187. auto res = cli.Get(
  20188. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20190. EXPECT_EQ(StatusCode::OK_200, res->status);
  20191. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20192. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20193. // and must not be selected.
  20194. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20195. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20196. }
  20197. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20198. Server svr;
  20199. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20200. std::string observed_remote_addr;
  20201. svr.Get("/ip", [&](const Request &req, Response &res) {
  20202. observed_remote_addr = req.remote_addr;
  20203. res.set_content("ok", "text/plain");
  20204. });
  20205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20206. auto se = detail::scope_exit([&] {
  20207. svr.stop();
  20208. t.join();
  20209. ASSERT_FALSE(svr.is_running());
  20210. });
  20211. svr.wait_until_ready();
  20212. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20213. // a forged address and the trusted proxy's own address; the forged value must
  20214. // not win over the address the trusted proxy actually recorded.
  20215. Client cli(HOST, PORT);
  20216. auto res = cli.Get(
  20217. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20219. EXPECT_EQ(StatusCode::OK_200, res->status);
  20220. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20221. }
  20222. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20223. Server svr;
  20224. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20225. std::string observed_remote_addr;
  20226. std::string observed_xff;
  20227. svr.Get("/ip", [&](const Request &req, Response &res) {
  20228. observed_remote_addr = req.remote_addr;
  20229. observed_xff = req.get_header_value("X-Forwarded-For");
  20230. res.set_content("ok", "text/plain");
  20231. });
  20232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20233. auto se = detail::scope_exit([&] {
  20234. svr.stop();
  20235. t.join();
  20236. ASSERT_FALSE(svr.is_running());
  20237. });
  20238. svr.wait_until_ready();
  20239. Client cli(HOST, PORT);
  20240. auto res = cli.Get(
  20241. "/ip",
  20242. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20244. EXPECT_EQ(StatusCode::OK_200, res->status);
  20245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20246. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20247. }
  20248. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20249. Server svr;
  20250. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20251. std::string observed_remote_addr;
  20252. std::string observed_xff;
  20253. svr.Get("/ip", [&](const Request &req, Response &res) {
  20254. observed_remote_addr = req.remote_addr;
  20255. observed_xff = req.get_header_value("X-Forwarded-For");
  20256. res.set_content("ok", "text/plain");
  20257. });
  20258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20259. auto se = detail::scope_exit([&] {
  20260. svr.stop();
  20261. t.join();
  20262. ASSERT_FALSE(svr.is_running());
  20263. });
  20264. svr.wait_until_ready();
  20265. std::string raw_req =
  20266. "GET /ip HTTP/1.1\r\n"
  20267. "Host: localhost\r\n"
  20268. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20269. "Connection: close\r\n"
  20270. "\r\n";
  20271. std::string out;
  20272. ASSERT_TRUE(send_request(5, raw_req, &out));
  20273. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20274. // Header parser trims surrounding whitespace of the header value
  20275. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20276. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20277. }
  20278. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20279. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20280. // their own X-Forwarded-For as a separate field line rather than extending the
  20281. // one the client sent, so every occurrence has to be taken into account.
  20282. // Reading only the first one hands back the address the client chose.
  20283. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20284. Server svr;
  20285. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20286. std::string observed_remote_addr;
  20287. size_t observed_xff_count = 0;
  20288. svr.Get("/ip", [&](const Request &req, Response &res) {
  20289. observed_remote_addr = req.remote_addr;
  20290. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20291. res.set_content("ok", "text/plain");
  20292. });
  20293. auto port = svr.bind_to_any_port(HOST);
  20294. thread t = thread([&]() { svr.listen_after_bind(); });
  20295. auto se = detail::scope_exit([&] {
  20296. svr.stop();
  20297. t.join();
  20298. ASSERT_FALSE(svr.is_running());
  20299. });
  20300. svr.wait_until_ready();
  20301. // The client supplies the first field line; the trusted proxy appends the
  20302. // address it observed as a second one.
  20303. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20304. "Host: localhost\r\n"
  20305. "X-Forwarded-For: 1.2.3.4\r\n"
  20306. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20307. "Connection: close\r\n"
  20308. "\r\n";
  20309. std::string out;
  20310. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20312. EXPECT_EQ(observed_xff_count, 2U);
  20313. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20314. // The same chain spread over one field line per hop derives the same client
  20315. // address, i.e. the split and the comma-joined representations agree.
  20316. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20317. "Host: localhost\r\n"
  20318. "X-Forwarded-For: 1.2.3.4\r\n"
  20319. "X-Forwarded-For: 198.51.100.23\r\n"
  20320. "X-Forwarded-For: 192.0.2.45\r\n"
  20321. "Connection: close\r\n"
  20322. "\r\n";
  20323. out.clear();
  20324. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20325. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20326. EXPECT_EQ(observed_xff_count, 3U);
  20327. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20328. }
  20329. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20330. // crash the server (it used to call front() on an empty vector inside
  20331. // get_client_ip). The connection-level remote address must be retained instead.
  20332. static void run_malformed_xff_test(const std::string &xff_value) {
  20333. Server svr;
  20334. svr.set_trusted_proxies({"192.0.2.45"});
  20335. std::string observed_remote_addr;
  20336. svr.Get("/ip", [&](const Request &req, Response &res) {
  20337. observed_remote_addr = req.remote_addr;
  20338. res.set_content("ok", "text/plain");
  20339. });
  20340. int port = 0;
  20341. thread t = thread([&]() {
  20342. port = svr.bind_to_any_port(HOST);
  20343. svr.listen_after_bind();
  20344. });
  20345. auto se = detail::scope_exit([&] {
  20346. svr.stop();
  20347. t.join();
  20348. ASSERT_FALSE(svr.is_running());
  20349. });
  20350. svr.wait_until_ready();
  20351. Client cli(HOST, port);
  20352. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20354. EXPECT_EQ(StatusCode::OK_200, res->status);
  20355. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20356. observed_remote_addr == "127.0.0.1");
  20357. }
  20358. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20359. run_malformed_xff_test("");
  20360. }
  20361. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20362. run_malformed_xff_test(",");
  20363. }
  20364. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20365. run_malformed_xff_test(", , ,");
  20366. }
  20367. // The same rule applies to Accept: a request whose acceptable types are spread
  20368. // over several field lines must be negotiated against all of them.
  20369. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20370. // case-insensitive connection options. Comparing the whole field value against
  20371. // one option misses a client that sends several of them, and misses every
  20372. // casing but the one written in the comparison.
  20373. //
  20374. // Sends req, reads the response, then reuses the same socket for a second
  20375. // request to find out whether the server kept the connection.
  20376. static void probe_connection_reuse(int port, const std::string &req,
  20377. bool *announced_close, bool *reusable) {
  20378. auto error = Error::Success;
  20379. auto sock = detail::create_client_socket(
  20380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20381. /*connection_timeout_sec=*/5, 0,
  20382. /*read_timeout_sec=*/1, 0,
  20383. /*write_timeout_sec=*/5, 0, std::string(), error);
  20384. ASSERT_NE(sock, INVALID_SOCKET);
  20385. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20386. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20387. "Host: localhost\r\n"
  20388. "Connection: close\r\n"
  20389. "\r\n";
  20390. std::string first_response;
  20391. std::string second_response;
  20392. detail::process_client_socket(
  20393. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20394. [&](Stream &strm) {
  20395. if (strm.write(req.data(), req.size()) !=
  20396. static_cast<ssize_t>(req.size())) {
  20397. return false;
  20398. }
  20399. char buf[512];
  20400. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20401. // Headers plus the two-byte body of the handler below
  20402. while (reader.getline()) {
  20403. first_response += reader.ptr();
  20404. if (first_response.find("ok") != std::string::npos) { break; }
  20405. }
  20406. if (strm.write(second.data(), second.size()) !=
  20407. static_cast<ssize_t>(second.size())) {
  20408. return true;
  20409. }
  20410. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20411. while (reader2.getline()) {
  20412. second_response += reader2.ptr();
  20413. if (second_response.find("ok") != std::string::npos) { break; }
  20414. }
  20415. return true;
  20416. });
  20417. *announced_close =
  20418. first_response.find("Connection: close") != std::string::npos;
  20419. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20420. }
  20421. class ConnectionTokenTest : public ::testing::Test {
  20422. protected:
  20423. void SetUp() override {
  20424. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20425. res.set_content("ok", "text/plain");
  20426. });
  20427. port_ = svr_.bind_to_any_port(HOST);
  20428. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20429. svr_.wait_until_ready();
  20430. }
  20431. void TearDown() override {
  20432. svr_.stop();
  20433. if (thread_.joinable()) { thread_.join(); }
  20434. }
  20435. Server svr_;
  20436. int port_ = 0;
  20437. thread thread_;
  20438. };
  20439. // "close" alongside another option still closes the connection, and the
  20440. // response says so rather than leaving the peer to discover it.
  20441. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20442. bool announced_close = false;
  20443. bool reusable = true;
  20444. probe_connection_reuse(port_,
  20445. "GET /keepalive HTTP/1.1\r\n"
  20446. "Host: localhost\r\n"
  20447. "Connection: keep-alive, close\r\n"
  20448. "\r\n",
  20449. &announced_close, &reusable);
  20450. EXPECT_TRUE(announced_close);
  20451. EXPECT_FALSE(reusable);
  20452. }
  20453. // "close" split over two field lines is the same list, so it is honored too.
  20454. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20455. bool announced_close = false;
  20456. bool reusable = true;
  20457. probe_connection_reuse(port_,
  20458. "GET /keepalive HTTP/1.1\r\n"
  20459. "Host: localhost\r\n"
  20460. "Connection: keep-alive\r\n"
  20461. "Connection: close\r\n"
  20462. "\r\n",
  20463. &announced_close, &reusable);
  20464. EXPECT_TRUE(announced_close);
  20465. EXPECT_FALSE(reusable);
  20466. }
  20467. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20468. // keep-alive in the spelling everyone actually sends keeps its connection.
  20469. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20470. bool announced_close = false;
  20471. bool reusable = false;
  20472. probe_connection_reuse(port_,
  20473. "GET /keepalive HTTP/1.0\r\n"
  20474. "Host: localhost\r\n"
  20475. "Connection: keep-alive\r\n"
  20476. "\r\n",
  20477. &announced_close, &reusable);
  20478. EXPECT_FALSE(announced_close);
  20479. EXPECT_TRUE(reusable);
  20480. }
  20481. // A token the value merely contains is not the token itself.
  20482. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20483. bool announced_close = false;
  20484. bool reusable = false;
  20485. probe_connection_reuse(port_,
  20486. "GET /keepalive HTTP/1.1\r\n"
  20487. "Host: localhost\r\n"
  20488. "Connection: notclose\r\n"
  20489. "\r\n",
  20490. &announced_close, &reusable);
  20491. EXPECT_FALSE(announced_close);
  20492. EXPECT_TRUE(reusable);
  20493. }
  20494. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20495. Server svr;
  20496. std::vector<std::string> observed_types;
  20497. svr.Get("/", [&](const Request &req, Response &res) {
  20498. observed_types = req.accept_content_types;
  20499. res.set_content("ok", "text/plain");
  20500. });
  20501. auto port = svr.bind_to_any_port(HOST);
  20502. thread t = thread([&]() { svr.listen_after_bind(); });
  20503. auto se = detail::scope_exit([&] {
  20504. svr.stop();
  20505. t.join();
  20506. ASSERT_FALSE(svr.is_running());
  20507. });
  20508. svr.wait_until_ready();
  20509. Client cli(HOST, port);
  20510. Headers headers;
  20511. headers.emplace("Accept", "text/plain;q=0.5");
  20512. headers.emplace("Accept", "application/json");
  20513. auto res = cli.Get("/", headers);
  20514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20515. EXPECT_EQ(StatusCode::OK_200, res->status);
  20516. // Sorted by q-value, so the second field line's type comes first
  20517. ASSERT_EQ(2U, observed_types.size());
  20518. EXPECT_EQ("application/json", observed_types[0]);
  20519. EXPECT_EQ("text/plain", observed_types[1]);
  20520. }
  20521. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20522. // empty field line must not contribute a bare comma to the combined value.
  20523. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20524. Server svr;
  20525. std::vector<std::string> observed_types;
  20526. svr.Get("/", [&](const Request &req, Response &res) {
  20527. observed_types = req.accept_content_types;
  20528. res.set_content("ok", "text/plain");
  20529. });
  20530. auto port = svr.bind_to_any_port(HOST);
  20531. thread t = thread([&]() { svr.listen_after_bind(); });
  20532. auto se = detail::scope_exit([&] {
  20533. svr.stop();
  20534. t.join();
  20535. ASSERT_FALSE(svr.is_running());
  20536. });
  20537. svr.wait_until_ready();
  20538. // Empty first field line, then a real one
  20539. std::string raw_req = "GET / HTTP/1.1\r\n"
  20540. "Host: localhost\r\n"
  20541. "Accept:\r\n"
  20542. "Accept: application/json\r\n"
  20543. "Connection: close\r\n"
  20544. "\r\n";
  20545. std::string out;
  20546. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20548. ASSERT_EQ(1U, observed_types.size());
  20549. EXPECT_EQ("application/json", observed_types[0]);
  20550. }
  20551. // The skip in get_combined_header_value() is what keeps an empty field line
  20552. // from contributing a bare comma. Only a trailing empty field line exercises
  20553. // it: a leading one is already covered by the "combined is still empty" check,
  20554. // and parse_accept_header() now ignores the empty element either way, so the
  20555. // request-level test above can no longer tell the two apart.
  20556. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20557. Headers headers;
  20558. headers.emplace("Accept", "text/html");
  20559. headers.emplace("Accept", "");
  20560. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20561. headers.clear();
  20562. headers.emplace("Accept", "");
  20563. headers.emplace("Accept", "application/json");
  20564. EXPECT_EQ("application/json",
  20565. detail::get_combined_header_value(headers, "Accept"));
  20566. }
  20567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20568. // An encoding offered on a later Accept-Encoding field line is still offered.
  20569. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20570. Server svr;
  20571. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20572. res.set_content(std::string(1024, 'x'), "text/plain");
  20573. });
  20574. auto port = svr.bind_to_any_port(HOST);
  20575. thread t = thread([&]() { svr.listen_after_bind(); });
  20576. auto se = detail::scope_exit([&] {
  20577. svr.stop();
  20578. t.join();
  20579. ASSERT_FALSE(svr.is_running());
  20580. });
  20581. svr.wait_until_ready();
  20582. Client cli(HOST, port);
  20583. cli.set_decompress(false);
  20584. Headers headers;
  20585. headers.emplace("Accept-Encoding", "identity");
  20586. headers.emplace("Accept-Encoding", "gzip");
  20587. auto res = cli.Get("/", headers);
  20588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20589. EXPECT_EQ(StatusCode::OK_200, res->status);
  20590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20591. }
  20592. #endif
  20593. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20594. // Transfer-Encoding is not its body.
  20595. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20596. Server svr;
  20597. svr.set_payload_max_length(8);
  20598. svr.Post("/test", [](const Request &, Response &res) {
  20599. res.set_content("ok", "text/plain");
  20600. });
  20601. auto port = svr.bind_to_any_port(HOST);
  20602. ASSERT_GT(port, 0);
  20603. thread t = thread([&] { svr.listen_after_bind(); });
  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. ASSERT_TRUE(send_request(1,
  20612. "POST /test HTTP/1.1\r\n"
  20613. "Host: localhost\r\n"
  20614. "Connection: close\r\n"
  20615. "\r\n" +
  20616. std::string(16, 'X'),
  20617. &resp, port));
  20618. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20619. }
  20620. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20621. Server svr;
  20622. svr.Post("/post", [&](const Request &req, Response &res) {
  20623. res.set_content(req.body, "text/plain");
  20624. });
  20625. svr.Put("/put", [&](const Request &req, Response &res) {
  20626. res.set_content(req.body, "text/plain");
  20627. });
  20628. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20629. res.set_content(req.body, "text/plain");
  20630. });
  20631. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20632. res.set_content(req.body, "text/plain");
  20633. });
  20634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20635. auto se = detail::scope_exit([&] {
  20636. svr.stop();
  20637. t.join();
  20638. ASSERT_FALSE(svr.is_running());
  20639. });
  20640. svr.wait_until_ready();
  20641. std::string resp;
  20642. // POST without Content-Length
  20643. ASSERT_TRUE(send_request(5,
  20644. "POST /post HTTP/1.1\r\n"
  20645. "Host: localhost\r\n"
  20646. "Connection: close\r\n"
  20647. "\r\n",
  20648. &resp));
  20649. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20650. // PUT without Content-Length
  20651. resp.clear();
  20652. ASSERT_TRUE(send_request(5,
  20653. "PUT /put HTTP/1.1\r\n"
  20654. "Host: localhost\r\n"
  20655. "Connection: close\r\n"
  20656. "\r\n",
  20657. &resp));
  20658. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20659. // PATCH without Content-Length
  20660. resp.clear();
  20661. ASSERT_TRUE(send_request(5,
  20662. "PATCH /patch HTTP/1.1\r\n"
  20663. "Host: localhost\r\n"
  20664. "Connection: close\r\n"
  20665. "\r\n",
  20666. &resp));
  20667. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20668. // DELETE without Content-Length
  20669. resp.clear();
  20670. ASSERT_TRUE(send_request(5,
  20671. "DELETE /delete HTTP/1.1\r\n"
  20672. "Host: localhost\r\n"
  20673. "Connection: close\r\n"
  20674. "\r\n",
  20675. &resp));
  20676. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20677. }
  20678. //==============================================================================
  20679. // open_stream() Tests
  20680. //==============================================================================
  20681. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20682. std::string result;
  20683. char buf[8192];
  20684. ssize_t n;
  20685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20686. result.append(buf, static_cast<size_t>(n));
  20687. }
  20688. return result;
  20689. }
  20690. // Mock stream for unit tests
  20691. class MockStream : public Stream {
  20692. public:
  20693. std::string data;
  20694. size_t pos = 0;
  20695. ssize_t error_after = -1; // -1 = no error
  20696. explicit MockStream(const std::string &d, ssize_t err = -1)
  20697. : data(d), error_after(err) {}
  20698. bool is_readable() const override { return true; }
  20699. bool wait_readable() const override { return true; }
  20700. bool wait_writable() const override { return true; }
  20701. ssize_t read(char *ptr, size_t size) override {
  20702. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20703. if (pos >= data.size()) return 0;
  20704. size_t limit =
  20705. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20706. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20707. std::memcpy(ptr, data.data() + pos, to_read);
  20708. pos += to_read;
  20709. return static_cast<ssize_t>(to_read);
  20710. }
  20711. ssize_t write(const char *, size_t) override { return -1; }
  20712. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20713. ip = "127.0.0.1";
  20714. port = 0;
  20715. }
  20716. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20717. ip = "127.0.0.1";
  20718. port = 0;
  20719. }
  20720. socket_t socket() const override { return INVALID_SOCKET; }
  20721. time_t duration() const override { return 0; }
  20722. };
  20723. TEST(StreamHandleTest, Basic) {
  20724. ClientImpl::StreamHandle handle;
  20725. EXPECT_FALSE(handle.is_valid());
  20726. handle.response = detail::make_unique<Response>();
  20727. handle.error = Error::Connection;
  20728. EXPECT_FALSE(handle.is_valid());
  20729. handle.error = Error::Success;
  20730. EXPECT_TRUE(handle.is_valid());
  20731. }
  20732. TEST(BodyReaderTest, Basic) {
  20733. MockStream stream("Hello, World!");
  20734. detail::BodyReader reader;
  20735. reader.stream = &stream;
  20736. reader.content_length = 13;
  20737. char buf[32];
  20738. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20739. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20740. EXPECT_TRUE(reader.eof);
  20741. }
  20742. TEST(BodyReaderTest, NoStream) {
  20743. detail::BodyReader reader;
  20744. char buf[32];
  20745. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20746. EXPECT_EQ(Error::Connection, reader.last_error);
  20747. }
  20748. TEST(BodyReaderTest, Error) {
  20749. MockStream stream("Hello, World!", 5);
  20750. detail::BodyReader reader;
  20751. reader.stream = &stream;
  20752. reader.content_length = 13;
  20753. char buf[32];
  20754. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20755. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20756. EXPECT_EQ(Error::Read, reader.last_error);
  20757. }
  20758. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20759. // Mock-based StreamHandle tests relying on private internals are removed.
  20760. class OpenStreamTest : public ::testing::Test {
  20761. protected:
  20762. void SetUp() override {
  20763. svr_.Get("/hello", [](const Request &, Response &res) {
  20764. res.set_content("Hello World!", "text/plain");
  20765. });
  20766. svr_.Get("/large", [](const Request &, Response &res) {
  20767. res.set_content(std::string(10000, 'X'), "text/plain");
  20768. });
  20769. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20770. res.set_content("Hello World!", "image/jpeg");
  20771. res.set_header("Content-Encoding", "UTF-8");
  20772. });
  20773. svr_.Get("/chunked", [](const Request &, Response &res) {
  20774. res.set_chunked_content_provider("text/plain",
  20775. [](size_t offset, DataSink &sink) {
  20776. if (offset < 15) {
  20777. sink.write("chunk", 5);
  20778. return true;
  20779. }
  20780. sink.done();
  20781. return true;
  20782. });
  20783. });
  20784. svr_.Get("/compressible", [](const Request &, Response &res) {
  20785. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20786. DataSink &sink) {
  20787. if (offset < 100 * 1024) {
  20788. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20789. sink.write(chunk.data(), chunk.size());
  20790. return true;
  20791. }
  20792. sink.done();
  20793. return true;
  20794. });
  20795. });
  20796. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20797. [](const Request & /*req*/, Response &res) {
  20798. auto i = new int(0);
  20799. res.set_header("Trailer", "Content-Length, X-Allowed");
  20800. res.set_chunked_content_provider(
  20801. "text/plain",
  20802. [i](size_t /*offset*/, DataSink &sink) {
  20803. switch (*i) {
  20804. case 0: sink.os << "123"; break;
  20805. case 1: sink.os << "456"; break;
  20806. case 2: sink.os << "789"; break;
  20807. case 3: {
  20808. sink.done_with_trailer(
  20809. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20810. } break;
  20811. }
  20812. (*i)++;
  20813. return true;
  20814. },
  20815. [i](bool success) {
  20816. EXPECT_TRUE(success);
  20817. delete i;
  20818. });
  20819. });
  20820. // Echo headers endpoint for header-related tests
  20821. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20822. std::string body;
  20823. for (const auto &h : req.headers) {
  20824. body.append(h.first);
  20825. body.push_back(':');
  20826. body.append(h.second);
  20827. body.push_back('\n');
  20828. }
  20829. res.set_content(body, "text/plain");
  20830. });
  20831. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20832. std::string body;
  20833. for (const auto &h : req.headers) {
  20834. body.append(h.first);
  20835. body.push_back(':');
  20836. body.append(h.second);
  20837. body.push_back('\n');
  20838. }
  20839. res.set_content(body, "text/plain");
  20840. });
  20841. port_ = svr_.bind_to_any_port("127.0.0.1");
  20842. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20843. svr_.wait_until_ready();
  20844. }
  20845. void TearDown() override {
  20846. svr_.stop();
  20847. if (thread_.joinable()) thread_.join();
  20848. }
  20849. Server svr_;
  20850. std::thread thread_;
  20851. int port_ = 0;
  20852. };
  20853. TEST_F(OpenStreamTest, Basic) {
  20854. Client cli("127.0.0.1", port_);
  20855. auto handle = cli.open_stream("GET", "/hello");
  20856. EXPECT_TRUE(handle.is_valid());
  20857. EXPECT_EQ("Hello World!", read_all(handle));
  20858. }
  20859. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20860. Client cli("127.0.0.1", port_);
  20861. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20862. ASSERT_TRUE(handle.is_valid());
  20863. EXPECT_EQ("Hello World!", read_all(handle));
  20864. }
  20865. TEST_F(OpenStreamTest, SmallBuffer) {
  20866. Client cli("127.0.0.1", port_);
  20867. auto handle = cli.open_stream("GET", "/hello");
  20868. std::string result;
  20869. char buf[4];
  20870. ssize_t n;
  20871. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20872. result.append(buf, static_cast<size_t>(n));
  20873. EXPECT_EQ("Hello World!", result);
  20874. }
  20875. TEST_F(OpenStreamTest, DefaultHeaders) {
  20876. Client cli("127.0.0.1", port_);
  20877. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20878. {
  20879. auto handle = cli.open_stream("GET", "/echo-headers");
  20880. ASSERT_TRUE(handle.is_valid());
  20881. auto body = read_all(handle);
  20882. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20883. std::string::npos);
  20884. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20885. std::string::npos);
  20886. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20887. }
  20888. // open_stream POST with body and no explicit content_type should NOT add
  20889. // text/plain Content-Type (behavior differs from non-streaming path), but
  20890. // should include Content-Length
  20891. {
  20892. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20893. ASSERT_TRUE(handle.is_valid());
  20894. auto body = read_all(handle);
  20895. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20896. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20897. }
  20898. // open_stream POST with explicit Content-Type should preserve it
  20899. {
  20900. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20901. {{"Content-Type", "application/custom"}},
  20902. "{}", "application/custom");
  20903. ASSERT_TRUE(handle.is_valid());
  20904. auto body = read_all(handle);
  20905. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20906. }
  20907. // User-specified User-Agent must not be overwritten for stream API
  20908. {
  20909. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20910. {{"User-Agent", "MyAgent/1.2"}});
  20911. ASSERT_TRUE(handle.is_valid());
  20912. auto body = read_all(handle);
  20913. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20914. }
  20915. }
  20916. TEST_F(OpenStreamTest, Large) {
  20917. Client cli("127.0.0.1", port_);
  20918. auto handle = cli.open_stream("GET", "/large");
  20919. EXPECT_EQ(10000u, read_all(handle).size());
  20920. }
  20921. TEST_F(OpenStreamTest, ConnectionError) {
  20922. Client cli("127.0.0.1", 9999);
  20923. auto handle = cli.open_stream("GET", "/hello");
  20924. EXPECT_FALSE(handle.is_valid());
  20925. }
  20926. TEST_F(OpenStreamTest, Chunked) {
  20927. Client cli("127.0.0.1", port_);
  20928. auto handle = cli.open_stream("GET", "/chunked");
  20929. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20930. "Transfer-Encoding") == "chunked");
  20931. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20932. }
  20933. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20934. Client cli("127.0.0.1", port_);
  20935. auto handle =
  20936. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20937. ASSERT_TRUE(handle.is_valid());
  20938. // Consume body to allow trailers to be received/parsed
  20939. auto body = read_all(handle);
  20940. // Explicitly parse trailers (ensure trailers are available for assertion)
  20941. handle.parse_trailers_if_needed();
  20942. EXPECT_EQ(std::string("123456789"), body);
  20943. // The response should include a Trailer header declaring both names
  20944. ASSERT_TRUE(handle.response);
  20945. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20946. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20947. handle.response->get_header_value("Trailer"));
  20948. // Prohibited trailer must not be present
  20949. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20950. // Allowed trailer should be present
  20951. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20952. EXPECT_EQ(std::string("yes"),
  20953. handle.response->get_trailer_value("X-Allowed"));
  20954. // Verify trailers are NOT present as regular headers
  20955. EXPECT_EQ(std::string(""),
  20956. handle.response->get_header_value("Content-Length"));
  20957. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20958. }
  20959. // Accepts one connection on an OS-assigned port, which it hands over through
  20960. // port_promise, reads the request head and sends back response. after_send,
  20961. // if given, runs on the connection before it is closed.
  20962. static std::thread
  20963. serve_single_response(std::promise<int> &port_promise,
  20964. const std::string &response,
  20965. std::function<void(socket_t)> after_send = nullptr) {
  20966. return std::thread([&port_promise, response, after_send] {
  20967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20968. default_socket_options(srv);
  20969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20971. sockaddr_in addr{};
  20972. addr.sin_family = AF_INET;
  20973. addr.sin_port = htons(0); // Let OS assign a free port
  20974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20975. int opt = 1;
  20976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20977. #ifdef _WIN32
  20978. reinterpret_cast<const char *>(&opt),
  20979. #else
  20980. &opt,
  20981. #endif
  20982. sizeof(opt));
  20983. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20984. ::listen(srv, 1) != 0) {
  20985. port_promise.set_value(-1);
  20986. detail::close_socket(srv);
  20987. return;
  20988. }
  20989. socklen_t addr_len = sizeof(addr);
  20990. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20991. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20992. sockaddr_in cli_addr{};
  20993. socklen_t cli_len = sizeof(cli_addr);
  20994. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20995. if (cli != INVALID_SOCKET) {
  20996. // Read the complete HTTP request (until the blank line that terminates
  20997. // headers) before sending the response. If the server closes the socket
  20998. // while the client's request data is still unread in the kernel receive
  20999. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21000. // connection on both sides: it discards the client's receive buffer
  21001. // (which already holds our response) and causes any in-progress write on
  21002. // the client to fail with ECONNRESET. Reading all request data first
  21003. // ensures close() emits a graceful FIN.
  21004. {
  21005. char rbuf[256];
  21006. std::string req;
  21007. while (req.find("\r\n\r\n") == std::string::npos) {
  21008. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21009. if (n <= 0) { break; }
  21010. req.append(rbuf, static_cast<size_t>(n));
  21011. }
  21012. }
  21013. ::send(cli,
  21014. #ifdef _WIN32
  21015. static_cast<const char *>(response.c_str()),
  21016. static_cast<int>(response.size()),
  21017. #else
  21018. response.c_str(), response.size(),
  21019. #endif
  21020. 0);
  21021. if (after_send) { after_send(cli); }
  21022. detail::close_socket(cli);
  21023. }
  21024. detail::close_socket(srv);
  21025. });
  21026. }
  21027. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21028. #ifndef _WIN32
  21029. signal(SIGPIPE, SIG_IGN);
  21030. #endif
  21031. std::promise<int> port_promise;
  21032. auto port_future = port_promise.get_future();
  21033. auto server_thread =
  21034. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21035. "Content-Type: text/plain\r\n"
  21036. "Content-Length: not-a-number\r\n"
  21037. "Connection: close\r\n"
  21038. "\r\n"
  21039. "hello");
  21040. auto port = port_future.get();
  21041. ASSERT_GT(port, 0);
  21042. Client cli("127.0.0.1", port);
  21043. auto handle = cli.open_stream("GET", "/");
  21044. EXPECT_FALSE(handle.is_valid());
  21045. server_thread.join();
  21046. }
  21047. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21048. #ifndef _WIN32
  21049. signal(SIGPIPE, SIG_IGN);
  21050. #endif
  21051. std::promise<int> port_promise;
  21052. auto port_future = port_promise.get_future();
  21053. auto server_thread = serve_single_response(
  21054. port_promise, "HTTP/1.1 200 OK\r\n"
  21055. "Content-Type: text/plain\r\n"
  21056. "Content-Length: 99999999999999999999999999\r\n"
  21057. "Connection: close\r\n"
  21058. "\r\n"
  21059. "hello");
  21060. auto port = port_future.get();
  21061. ASSERT_GT(port, 0);
  21062. // Historically std::stoull would throw std::out_of_range here and crash
  21063. // the process, then parsing silently clamped to a bogus framing length and
  21064. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21065. // so the stream fails to open, matching the not-a-number case above. The
  21066. // process still must NOT terminate.
  21067. Client cli("127.0.0.1", port);
  21068. auto handle = cli.open_stream("GET", "/");
  21069. EXPECT_FALSE(handle.is_valid());
  21070. server_thread.join();
  21071. }
  21072. #ifndef _WIN32
  21073. // As above for the body of a streamed request: a send() cut short by the write
  21074. // timeout must not leave the rest of the body unsent.
  21075. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21076. signal(SIGPIPE, SIG_IGN);
  21077. Server svr;
  21078. svr.set_socket_options([](socket_t sock) {
  21079. int size = 8192;
  21080. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21081. reinterpret_cast<const char *>(&size), sizeof(size));
  21082. });
  21083. svr.Post("/size", [](const Request &, Response &res,
  21084. const ContentReader &content_reader) {
  21085. // Outlast the client's write timeout before reading the body.
  21086. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21087. size_t received = 0;
  21088. content_reader([&](const char *, size_t len) {
  21089. received += len;
  21090. return true;
  21091. });
  21092. res.set_content(std::to_string(received), "text/plain");
  21093. });
  21094. auto port = svr.bind_to_any_port(HOST);
  21095. std::thread t([&]() { svr.listen_after_bind(); });
  21096. auto se = detail::scope_exit([&] {
  21097. svr.stop();
  21098. t.join();
  21099. });
  21100. svr.wait_until_ready();
  21101. Client cli(HOST, port);
  21102. cli.set_write_timeout(0, 500000);
  21103. cli.set_socket_options([](socket_t sock) {
  21104. int size = 8192;
  21105. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21106. reinterpret_cast<const char *>(&size), sizeof(size));
  21107. });
  21108. const std::string body(4 * 1024 * 1024, 'A');
  21109. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21110. "application/octet-stream");
  21111. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21112. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21113. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21114. }
  21115. #endif
  21116. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21117. std::promise<void> slow_started;
  21118. auto slow_started_future = slow_started.get_future();
  21119. Server svr;
  21120. svr.Get("/slow", [&](const Request &, Response &res) {
  21121. slow_started.set_value();
  21122. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21123. res.set_content("slow", "text/plain");
  21124. });
  21125. svr.Get("/fast", [](const Request &, Response &res) {
  21126. res.set_content("fast", "text/plain");
  21127. });
  21128. auto port = svr.bind_to_any_port(HOST);
  21129. std::thread t([&]() { svr.listen_after_bind(); });
  21130. auto se = detail::scope_exit([&] {
  21131. svr.stop();
  21132. t.join();
  21133. });
  21134. svr.wait_until_ready();
  21135. Client cli(HOST, port);
  21136. std::string slow_body;
  21137. std::thread slow_thread([&] {
  21138. auto res = cli.Get("/slow");
  21139. if (res) { slow_body = res->body; }
  21140. });
  21141. slow_started_future.wait();
  21142. auto result = stream::Get(cli, "/fast");
  21143. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21144. slow_thread.join();
  21145. EXPECT_EQ("slow", slow_body);
  21146. EXPECT_EQ("fast", fast_body);
  21147. }
  21148. // Serves `response` to the single request `fn` makes with a fresh client.
  21149. template <typename Fn>
  21150. static void with_single_response(const std::string &response, Fn fn) {
  21151. #ifndef _WIN32
  21152. signal(SIGPIPE, SIG_IGN);
  21153. #endif
  21154. std::promise<int> port_promise;
  21155. auto port_future = port_promise.get_future();
  21156. auto server_thread = serve_single_response(port_promise, response);
  21157. auto se = detail::scope_exit([&] { server_thread.join(); });
  21158. auto port = port_future.get();
  21159. ASSERT_GT(port, 0);
  21160. Client cli("127.0.0.1", port);
  21161. fn(cli);
  21162. }
  21163. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21164. // too, also in a build without the decoder for the advertised coding.
  21165. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21166. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21167. const auto response = "HTTP/1.1 200 OK\r\n"
  21168. "Content-Encoding: gzip\r\n"
  21169. "Content-Length: " +
  21170. std::to_string(gzipped.size()) +
  21171. "\r\n"
  21172. "Connection: close\r\n\r\n" +
  21173. gzipped;
  21174. with_single_response(response, [&](Client &cli) {
  21175. cli.set_decompress(false);
  21176. auto handle = cli.open_stream("GET", "/");
  21177. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21178. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21179. EXPECT_EQ(gzipped, read_all(handle));
  21180. EXPECT_FALSE(handle.has_read_error());
  21181. });
  21182. with_single_response(response, [&](Client &cli) {
  21183. cli.set_decompress(false);
  21184. auto res = stream::Get(cli, "/", 7);
  21185. ASSERT_TRUE(res) << to_string(res.error());
  21186. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21187. EXPECT_EQ(gzipped, res.read_all());
  21188. EXPECT_FALSE(res.has_read_error());
  21189. });
  21190. }
  21191. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21192. // Neither Content-Length nor chunked: the body ends at the close
  21193. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21194. "Connection: close\r\n"
  21195. "\r\n"
  21196. "hello";
  21197. with_single_response(close_delimited, [](Client &cli) {
  21198. auto handle = cli.open_stream("GET", "/");
  21199. ASSERT_TRUE(handle.is_valid());
  21200. EXPECT_EQ("hello", read_all(handle));
  21201. EXPECT_FALSE(handle.has_read_error());
  21202. });
  21203. // A close before the end of the Content-Length is still an error
  21204. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21205. "Content-Length: 10\r\n"
  21206. "\r\n"
  21207. "hello";
  21208. with_single_response(short_content_length, [](Client &cli) {
  21209. auto handle = cli.open_stream("GET", "/");
  21210. ASSERT_TRUE(handle.is_valid());
  21211. read_all(handle);
  21212. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21213. });
  21214. // So is a close before the last chunk
  21215. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21216. "Transfer-Encoding: chunked\r\n"
  21217. "\r\n"
  21218. "5\r\nhello\r\n";
  21219. with_single_response(short_chunked, [](Client &cli) {
  21220. auto handle = cli.open_stream("GET", "/");
  21221. ASSERT_TRUE(handle.is_valid());
  21222. read_all(handle);
  21223. EXPECT_TRUE(handle.has_read_error());
  21224. });
  21225. }
  21226. #ifdef CPPHTTPLIB_SSL_ENABLED
  21227. // Serves `response` to one request, then closes with or without a close_notify
  21228. template <typename Fn>
  21229. static void with_single_tls_response(const std::string &response,
  21230. bool close_notify, Fn fn) {
  21231. #ifndef _WIN32
  21232. signal(SIGPIPE, SIG_IGN);
  21233. #endif
  21234. std::promise<int> port_promise;
  21235. auto port_future = port_promise.get_future();
  21236. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21237. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21238. default_socket_options(srv);
  21239. sockaddr_in addr{};
  21240. addr.sin_family = AF_INET;
  21241. addr.sin_port = htons(0);
  21242. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21243. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21244. ::listen(srv, 1) != 0) {
  21245. port_promise.set_value(-1);
  21246. detail::close_socket(srv);
  21247. return;
  21248. }
  21249. socklen_t addr_len = sizeof(addr);
  21250. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21251. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21252. auto cli = ::accept(srv, nullptr, nullptr);
  21253. if (cli != INVALID_SOCKET) {
  21254. auto ctx = tls::create_server_context();
  21255. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21256. nullptr);
  21257. auto session = tls::create_session(ctx, cli);
  21258. tls::TlsError err;
  21259. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21260. // The request head first, so that closing the socket sends a FIN
  21261. // rather than an RST for the unread bytes.
  21262. std::string req;
  21263. char buf[256];
  21264. while (req.find("\r\n\r\n") == std::string::npos) {
  21265. auto n = tls::read(session, buf, sizeof(buf), err);
  21266. if (n <= 0) { break; }
  21267. req.append(buf, static_cast<size_t>(n));
  21268. }
  21269. size_t sent = 0;
  21270. while (sent < response.size()) {
  21271. auto n = tls::write(session, response.data() + sent,
  21272. response.size() - sent, err);
  21273. if (n <= 0) { break; }
  21274. sent += static_cast<size_t>(n);
  21275. }
  21276. if (close_notify) { tls::shutdown(session, true); }
  21277. }
  21278. tls::free_session(session);
  21279. detail::close_socket(cli);
  21280. tls::free_context(ctx);
  21281. }
  21282. detail::close_socket(srv);
  21283. });
  21284. auto se = detail::scope_exit([&] { server_thread.join(); });
  21285. auto port = port_future.get();
  21286. ASSERT_GT(port, 0);
  21287. SSLClient cli("127.0.0.1", port);
  21288. cli.enable_server_certificate_verification(false);
  21289. fn(cli);
  21290. }
  21291. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21292. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21293. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21294. "Connection: close\r\n"
  21295. "\r\n"
  21296. "hello";
  21297. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21298. auto res = cli.Get("/");
  21299. ASSERT_TRUE(res) << to_string(res.error());
  21300. EXPECT_EQ("hello", res->body);
  21301. });
  21302. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21303. auto res = cli.Get("/");
  21304. ASSERT_FALSE(res);
  21305. EXPECT_EQ(Error::Read, res.error());
  21306. });
  21307. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21308. auto handle = cli.open_stream("GET", "/");
  21309. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21310. read_all(handle);
  21311. EXPECT_TRUE(handle.has_read_error());
  21312. });
  21313. // A framed body ends where its framing says, with or without the alert
  21314. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21315. "Content-Length: 5\r\n"
  21316. "Connection: close\r\n"
  21317. "\r\n"
  21318. "hello";
  21319. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21320. auto res = cli.Get("/");
  21321. ASSERT_TRUE(res) << to_string(res.error());
  21322. EXPECT_EQ("hello", res->body);
  21323. });
  21324. }
  21325. #endif
  21326. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21327. const char *responses[] = {
  21328. "HTTP/1.1 103 Early Hints\r\n"
  21329. "Link: </style.css>; rel=preload\r\n"
  21330. "\r\n"
  21331. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21332. "HTTP/1.1 100 Continue\r\n"
  21333. "X-Note: interim\r\n"
  21334. "\r\n"
  21335. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21336. };
  21337. for (auto response : responses) {
  21338. with_single_response(response, [](Client &cli) {
  21339. auto res = cli.Get("/");
  21340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21341. EXPECT_EQ(StatusCode::OK_200, res->status);
  21342. EXPECT_EQ("ok", res->body);
  21343. });
  21344. }
  21345. }
  21346. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21347. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21348. const std::string final_response =
  21349. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21350. std::string interims;
  21351. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21352. interims += interim;
  21353. }
  21354. with_single_response(interims + final_response, [](Client &cli) {
  21355. auto res = cli.Get("/");
  21356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21357. EXPECT_EQ("ok", res->body);
  21358. });
  21359. with_single_response(interims + interim + final_response, [](Client &cli) {
  21360. auto res = cli.Get("/");
  21361. ASSERT_FALSE(res);
  21362. EXPECT_EQ(Error::Read, res.error());
  21363. });
  21364. }
  21365. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21366. #ifndef _WIN32
  21367. signal(SIGPIPE, SIG_IGN);
  21368. #endif
  21369. // The server answers the head without asking for the body. Bytes it then
  21370. // reads on the connection would be taken for the body the request declared.
  21371. auto closed_by_client = false;
  21372. std::promise<int> port_promise;
  21373. auto server_thread = serve_single_response(
  21374. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21375. [&](socket_t sock) {
  21376. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21377. char buf[256];
  21378. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21379. });
  21380. Client cli("127.0.0.1", port_promise.get_future().get());
  21381. cli.set_keep_alive(true);
  21382. cli.set_read_timeout(1, 0);
  21383. // Long enough for the client to send Expect: 100-continue.
  21384. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21386. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21387. cli.Get("/second");
  21388. server_thread.join();
  21389. EXPECT_TRUE(closed_by_client);
  21390. }
  21391. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21392. // Long enough for the client to send Expect: 100-continue
  21393. with_single_response(
  21394. "HTTP/1.1 103 Early Hints\r\n"
  21395. "Link: </style.css>; rel=preload\r\n"
  21396. "\r\n"
  21397. "HTTP/1.1 401 Unauthorized\r\n"
  21398. "Content-Length: 0\r\n\r\n",
  21399. [](Client &cli) {
  21400. cli.set_read_timeout(2, 0);
  21401. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21403. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21404. });
  21405. }
  21406. #ifdef CPPHTTPLIB_SSL_ENABLED
  21407. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21408. #ifndef _WIN32
  21409. signal(SIGPIPE, SIG_IGN);
  21410. #endif
  21411. auto reused = false;
  21412. std::promise<int> port_promise;
  21413. auto server_thread = serve_single_response(
  21414. port_promise,
  21415. "HTTP/1.1 401 Unauthorized\r\n"
  21416. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21417. "Content-Length: 0\r\n\r\n",
  21418. [&](socket_t sock) {
  21419. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21420. char buf[256];
  21421. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21422. });
  21423. Client cli("127.0.0.1", port_promise.get_future().get());
  21424. cli.set_keep_alive(true);
  21425. cli.set_digest_auth("user", "pass");
  21426. cli.set_read_timeout(1, 0);
  21427. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21428. server_thread.join();
  21429. EXPECT_FALSE(reused);
  21430. }
  21431. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21432. // Any other answer to CONNECT would read as the origin's response.
  21433. struct {
  21434. const char *response;
  21435. bool passed_on;
  21436. } cases[] = {
  21437. {"HTTP/1.1 201 Created\r\n"
  21438. "Set-Cookie: session=from-proxy\r\n"
  21439. "Content-Length: 0\r\n\r\n",
  21440. false},
  21441. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21442. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21443. "Content-Length: 0\r\n\r\n",
  21444. true},
  21445. };
  21446. for (const auto &c : cases) {
  21447. std::promise<int> port_promise;
  21448. auto server_thread = serve_single_response(port_promise, c.response);
  21449. SSLClient cli("example.com", 443);
  21450. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21451. auto res = cli.Get("/");
  21452. server_thread.join();
  21453. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21454. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21455. if (res) {
  21456. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21457. }
  21458. }
  21459. }
  21460. #endif
  21461. // Records the client's error logger calls as "error METHOD path", or
  21462. // "error null" for a call without a request
  21463. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21464. return [&log](const Error &err, const Request *req) {
  21465. log.push_back(to_string(err) + " " +
  21466. (req ? req->method + " " + req->path : "null"));
  21467. };
  21468. }
  21469. // A failed request is reported once, with the request the caller made
  21470. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21471. Server svr;
  21472. svr.Get("/big", [](const Request &, Response &res) {
  21473. res.set_content(std::string(100000, 'b'), "text/plain");
  21474. });
  21475. auto port = svr.bind_to_any_port(HOST);
  21476. std::thread t([&]() { svr.listen_after_bind(); });
  21477. auto se = detail::scope_exit([&] {
  21478. svr.stop();
  21479. t.join();
  21480. });
  21481. svr.wait_until_ready();
  21482. Client cli(HOST, port);
  21483. std::vector<std::string> log;
  21484. cli.set_error_logger(record_errors(log));
  21485. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21486. cli.Get("/big", [](const char *, size_t) { return false; });
  21487. EXPECT_EQ(expected, log);
  21488. log.clear();
  21489. cli.Get("/big", [](size_t, size_t) { return false; });
  21490. EXPECT_EQ(expected, log);
  21491. }
  21492. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21493. // Fails while the body is read
  21494. auto broken = [](const Request &, Response &res) {
  21495. res.set_content_provider(10, "text/plain",
  21496. [](size_t, size_t, DataSink &) { return false; });
  21497. };
  21498. Server other;
  21499. other.Get("/broken", broken);
  21500. auto other_port = other.bind_to_any_port(HOST);
  21501. std::thread other_t([&]() { other.listen_after_bind(); });
  21502. auto other_se = detail::scope_exit([&] {
  21503. other.stop();
  21504. other_t.join();
  21505. });
  21506. other.wait_until_ready();
  21507. Server svr;
  21508. svr.Get("/broken", broken);
  21509. svr.Get("/same-origin",
  21510. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21511. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21512. res.set_redirect("http://" + std::string(HOST) + ":" +
  21513. std::to_string(other_port) + "/broken");
  21514. });
  21515. auto port = svr.bind_to_any_port(HOST);
  21516. std::thread t([&]() { svr.listen_after_bind(); });
  21517. auto se = detail::scope_exit([&] {
  21518. svr.stop();
  21519. t.join();
  21520. });
  21521. svr.wait_until_ready();
  21522. Client cli(HOST, port);
  21523. cli.set_follow_location(true);
  21524. std::vector<std::string> log;
  21525. cli.set_error_logger(record_errors(log));
  21526. for (auto path : {"/same-origin", "/cross-origin"}) {
  21527. log.clear();
  21528. auto res = cli.Get(path);
  21529. ASSERT_FALSE(res);
  21530. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21531. log);
  21532. }
  21533. }
  21534. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21535. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21536. std::vector<std::string> log;
  21537. cli.set_error_logger(record_errors(log));
  21538. auto handle = cli.open_stream("GET", "/x");
  21539. EXPECT_FALSE(handle.is_valid());
  21540. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21541. log);
  21542. });
  21543. }
  21544. #ifdef CPPHTTPLIB_SSL_ENABLED
  21545. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21546. // Not a TLS server, so the handshake fails. It waits for a request line in
  21547. // the handshake bytes, so a short read timeout lets it close quickly.
  21548. Server svr;
  21549. svr.set_read_timeout(0, 100000);
  21550. svr.Get("/x", [](const Request &, Response &res) {
  21551. res.set_content("x", "text/plain");
  21552. });
  21553. auto port = svr.bind_to_any_port(HOST);
  21554. std::thread t([&]() { svr.listen_after_bind(); });
  21555. auto se = detail::scope_exit([&] {
  21556. svr.stop();
  21557. t.join();
  21558. });
  21559. svr.wait_until_ready();
  21560. std::vector<std::string> log;
  21561. SSLClient cli(HOST, port);
  21562. cli.enable_server_certificate_verification(false);
  21563. cli.set_error_logger(record_errors(log));
  21564. auto res = cli.Get("/x");
  21565. ASSERT_FALSE(res);
  21566. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21567. log.clear();
  21568. auto handle = cli.open_stream("GET", "/x");
  21569. EXPECT_FALSE(handle.is_valid());
  21570. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21571. log.clear();
  21572. SSLClient no_ca(HOST, port);
  21573. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21574. no_ca.set_error_logger(record_errors(log));
  21575. res = no_ca.Get("/x");
  21576. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21577. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21578. }
  21579. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21580. #ifndef _WIN32
  21581. signal(SIGPIPE, SIG_IGN);
  21582. #endif
  21583. // Refused, answered with a challenge, or closed without an answer
  21584. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21585. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21586. "Content-Length: 0\r\n\r\n",
  21587. ""}) {
  21588. std::promise<int> port_promise;
  21589. auto server_thread = serve_single_response(port_promise, response);
  21590. SSLClient cli("example.com", 443);
  21591. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21592. std::vector<std::string> log;
  21593. cli.set_error_logger(record_errors(log));
  21594. auto res = cli.Get("/");
  21595. server_thread.join();
  21596. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21597. << response;
  21598. }
  21599. }
  21600. #endif
  21601. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21602. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21603. // the chunked coding and drop Content-Length, so a front-end that trusts
  21604. // Content-Length would disagree about where the body ends (response
  21605. // smuggling). The client must reject such a response.
  21606. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21607. for (const char *te : {"chunked", "gzip, chunked"}) {
  21608. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21609. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21610. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21611. "5\r\nhello\r\n0\r\n\r\n";
  21612. with_single_response(response, [&](Client &cli) {
  21613. auto res = cli.Get("/");
  21614. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21615. EXPECT_EQ(Error::Read, res.error()) << te;
  21616. });
  21617. with_single_response(response, [&](Client &cli) {
  21618. auto handle = cli.open_stream("GET", "/");
  21619. EXPECT_FALSE(handle.is_valid()) << te;
  21620. EXPECT_EQ(Error::Read, handle.error) << te;
  21621. });
  21622. }
  21623. }
  21624. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21625. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21626. // closing the connection (unlike a request, which must be rejected).
  21627. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21628. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21629. "Transfer-Encoding: chunked\r\n"
  21630. "Connection: close\r\n"
  21631. "\r\n"
  21632. "5\r\nhello\r\n0\r\n\r\n",
  21633. "HTTP/1.1 200 OK\r\n"
  21634. "Transfer-Encoding: gzip\r\n"
  21635. "Connection: close\r\n"
  21636. "\r\n"
  21637. "hello"}) {
  21638. with_single_response(response, [&](Client &cli) {
  21639. auto res = cli.Get("/");
  21640. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21641. EXPECT_EQ("hello", res->body);
  21642. });
  21643. with_single_response(response, [&](Client &cli) {
  21644. auto handle = cli.open_stream("GET", "/");
  21645. ASSERT_TRUE(handle.is_valid()) << response;
  21646. EXPECT_EQ("hello", read_all(handle));
  21647. });
  21648. }
  21649. }
  21650. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21651. // framing headers describe nothing to read and must not be rejected.
  21652. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21653. const std::string framing = "Content-Length: 5\r\n"
  21654. "Transfer-Encoding: chunked\r\n"
  21655. "Connection: close\r\n"
  21656. "\r\n";
  21657. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21658. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21659. });
  21660. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21661. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21662. });
  21663. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21664. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21665. with_single_response(response, [&](Client &cli) {
  21666. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21667. });
  21668. with_single_response(response, [&](Client &cli) {
  21669. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21670. });
  21671. }
  21672. }
  21673. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21674. // header section, so a stream opened on one has nothing to read, whatever
  21675. // framing or coding headers it carries.
  21676. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21677. struct Case {
  21678. const char *method;
  21679. const char *status;
  21680. };
  21681. // A reader of the declared body reports an early close when nothing
  21682. // follows, and hands back what does.
  21683. struct Framing {
  21684. const char *headers;
  21685. const char *after;
  21686. };
  21687. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21688. Case{"GET", "304 Not Modified"}}) {
  21689. for (const auto &f :
  21690. {Framing{"Content-Length: 5\r\n", ""},
  21691. Framing{"Content-Length: 5\r\n", "hello"},
  21692. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21693. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21694. // Not decoded, so a build without Brotli opens it too
  21695. Framing{"Content-Encoding: br\r\n", ""}}) {
  21696. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21697. "Connection: close\r\n"
  21698. "\r\n" +
  21699. f.after;
  21700. with_single_response(response, [&](Client &cli) {
  21701. auto handle = cli.open_stream(c.method, "/");
  21702. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21703. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21704. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21705. });
  21706. }
  21707. }
  21708. }
  21709. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21710. // response, is faulty framing, so the connection is not reused after it.
  21711. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21712. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21713. "Content-Length: 0\r\n"
  21714. "Transfer-Encoding: chunked\r\n"
  21715. "\r\n"
  21716. "5\r\nhello\r\n0\r\n\r\n",
  21717. "HTTP/1.0 200 Connection established\r\n"
  21718. "Connection: keep-alive\r\n"
  21719. "Transfer-Encoding: chunked\r\n"
  21720. "\r\n"
  21721. "5\r\nhello\r\n0\r\n\r\n"}) {
  21722. with_single_response(response, [&](Client &cli) {
  21723. cli.set_keep_alive(true);
  21724. auto res = cli.Get("/");
  21725. ASSERT_TRUE(res) << response;
  21726. EXPECT_EQ("hello", res->body);
  21727. EXPECT_FALSE(cli.is_socket_open()) << response;
  21728. });
  21729. }
  21730. }
  21731. // A payload max length of 0 means no limit, however the body is framed.
  21732. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21733. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21734. "Transfer-Encoding: chunked\r\n"
  21735. "\r\n"
  21736. "5\r\nhello\r\n0\r\n\r\n",
  21737. "HTTP/1.1 200 OK\r\n"
  21738. "Connection: close\r\n"
  21739. "\r\n"
  21740. "hello"}) {
  21741. with_single_response(response, [&](Client &cli) {
  21742. cli.set_payload_max_length(0);
  21743. auto res = cli.Get("/");
  21744. ASSERT_TRUE(res) << response;
  21745. EXPECT_EQ("hello", res->body) << response;
  21746. });
  21747. }
  21748. }
  21749. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21750. Server svr;
  21751. svr.set_payload_max_length(0);
  21752. svr.Post("/echo", [](const Request &req, Response &res) {
  21753. res.set_content(req.body, "text/plain");
  21754. });
  21755. auto port = svr.bind_to_any_port(HOST);
  21756. thread t = thread([&] { svr.listen_after_bind(); });
  21757. auto se = detail::scope_exit([&] {
  21758. svr.stop();
  21759. t.join();
  21760. ASSERT_FALSE(svr.is_running());
  21761. });
  21762. svr.wait_until_ready();
  21763. Client cli(HOST, port);
  21764. auto res = cli.Post(
  21765. "/echo",
  21766. [](size_t /*offset*/, DataSink &sink) {
  21767. sink.write("hello", 5);
  21768. sink.done();
  21769. return true;
  21770. },
  21771. "text/plain");
  21772. ASSERT_TRUE(res);
  21773. EXPECT_EQ(StatusCode::OK_200, res->status);
  21774. EXPECT_EQ("hello", res->body);
  21775. }
  21776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21777. TEST_F(OpenStreamTest, Gzip) {
  21778. Client cli("127.0.0.1", port_);
  21779. auto handle = cli.open_stream("GET", "/compressible", {},
  21780. {{"Accept-Encoding", "gzip"}});
  21781. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21782. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21783. }
  21784. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21785. Client cli("127.0.0.1", port_);
  21786. auto handle =
  21787. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21788. {{"Accept-Encoding", "gzip"}});
  21789. ASSERT_TRUE(handle.is_valid());
  21790. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21791. EXPECT_EQ("123456789", read_all(handle));
  21792. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21793. }
  21794. #endif
  21795. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21796. TEST_F(OpenStreamTest, Brotli) {
  21797. Client cli("127.0.0.1", port_);
  21798. auto handle =
  21799. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21800. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21801. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21802. }
  21803. #endif
  21804. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21805. TEST_F(OpenStreamTest, Zstd) {
  21806. Client cli("127.0.0.1", port_);
  21807. auto handle = cli.open_stream("GET", "/compressible", {},
  21808. {{"Accept-Encoding", "zstd"}});
  21809. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21810. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21811. }
  21812. #endif
  21813. #ifdef CPPHTTPLIB_SSL_ENABLED
  21814. class SSLOpenStreamTest : public ::testing::Test {
  21815. protected:
  21816. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21817. void SetUp() override {
  21818. svr_.Get("/hello", [](const Request &, Response &res) {
  21819. res.set_content("Hello SSL World!", "text/plain");
  21820. });
  21821. svr_.Get("/chunked", [](const Request &, Response &res) {
  21822. res.set_chunked_content_provider("text/plain",
  21823. [](size_t offset, DataSink &sink) {
  21824. if (offset < 15) {
  21825. sink.write("chunk", 5);
  21826. return true;
  21827. }
  21828. sink.done();
  21829. return true;
  21830. });
  21831. });
  21832. svr_.Post("/echo", [](const Request &req, Response &res) {
  21833. res.set_content(req.body, req.get_header_value("Content-Type"));
  21834. });
  21835. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21836. std::string body = req.body;
  21837. res.set_chunked_content_provider(
  21838. "text/plain", [body](size_t offset, DataSink &sink) {
  21839. if (offset < body.size()) {
  21840. sink.write(body.data() + offset, body.size() - offset);
  21841. }
  21842. sink.done();
  21843. return true;
  21844. });
  21845. });
  21846. port_ = svr_.bind_to_any_port("127.0.0.1");
  21847. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21848. svr_.wait_until_ready();
  21849. }
  21850. void TearDown() override {
  21851. svr_.stop();
  21852. if (thread_.joinable()) thread_.join();
  21853. }
  21854. SSLServer svr_;
  21855. std::thread thread_;
  21856. int port_ = 0;
  21857. };
  21858. TEST_F(SSLOpenStreamTest, Basic) {
  21859. SSLClient cli("127.0.0.1", port_);
  21860. cli.enable_server_certificate_verification(false);
  21861. auto handle = cli.open_stream("GET", "/hello");
  21862. ASSERT_TRUE(handle.is_valid());
  21863. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21864. }
  21865. TEST_F(SSLOpenStreamTest, Chunked) {
  21866. SSLClient cli("127.0.0.1", port_);
  21867. cli.enable_server_certificate_verification(false);
  21868. auto handle = cli.open_stream("GET", "/chunked");
  21869. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21870. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21871. "Transfer-Encoding") == "chunked");
  21872. auto body = read_all(handle);
  21873. EXPECT_EQ("chunkchunkchunk", body);
  21874. }
  21875. TEST_F(SSLOpenStreamTest, Post) {
  21876. SSLClient cli("127.0.0.1", port_);
  21877. cli.enable_server_certificate_verification(false);
  21878. auto handle =
  21879. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21880. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21881. EXPECT_EQ(200, handle.response->status);
  21882. auto body = read_all(handle);
  21883. EXPECT_EQ("Hello SSL POST", body);
  21884. }
  21885. TEST_F(SSLOpenStreamTest, PostChunked) {
  21886. SSLClient cli("127.0.0.1", port_);
  21887. cli.enable_server_certificate_verification(false);
  21888. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21889. "Chunked SSL Data", "text/plain");
  21890. ASSERT_TRUE(handle.is_valid());
  21891. EXPECT_EQ(200, handle.response->status);
  21892. auto body = read_all(handle);
  21893. EXPECT_EQ("Chunked SSL Data", body);
  21894. }
  21895. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21896. // Content-Length is terminated by the server closing the connection. When the
  21897. // SSL peer sends a close_notify after the body, the client must treat it as a
  21898. // clean EOF and return a successful response rather than an error.
  21899. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21901. ASSERT_TRUE(svr.is_valid());
  21902. svr.set_keep_alive_max_count(1);
  21903. const std::string expected_body = "Hello from connection-close response!";
  21904. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21905. res.set_content_provider("text/plain",
  21906. [&](size_t offset, DataSink &sink) -> bool {
  21907. if (offset < expected_body.size()) {
  21908. sink.write(expected_body.data() + offset,
  21909. expected_body.size() - offset);
  21910. }
  21911. sink.done();
  21912. return true;
  21913. });
  21914. });
  21915. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21916. auto se = detail::scope_exit([&] {
  21917. svr.stop();
  21918. listen_thread.join();
  21919. ASSERT_FALSE(svr.is_running());
  21920. });
  21921. svr.wait_until_ready();
  21922. SSLClient cli(HOST, PORT);
  21923. cli.enable_server_certificate_verification(false);
  21924. auto res = cli.Get("/no-content-length");
  21925. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21926. EXPECT_EQ(StatusCode::OK_200, res->status);
  21927. EXPECT_EQ(expected_body, res->body);
  21928. }
  21929. // Without Content-Length, the full buffer size reaches tls::read().
  21930. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21931. if (sizeof(size_t) <= sizeof(int)) {
  21932. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21933. }
  21934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21935. ASSERT_TRUE(svr.is_valid());
  21936. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21937. res.set_content_provider("text/plain",
  21938. [&](size_t offset, DataSink &sink) -> bool {
  21939. if (offset == 0) { sink.write("Hello", 5); }
  21940. sink.done();
  21941. return true;
  21942. });
  21943. });
  21944. auto port = svr.bind_to_any_port(HOST);
  21945. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21946. auto se = detail::scope_exit([&] {
  21947. svr.stop();
  21948. listen_thread.join();
  21949. });
  21950. svr.wait_until_ready();
  21951. SSLClient cli(HOST, port);
  21952. cli.enable_server_certificate_verification(false);
  21953. auto handle = cli.open_stream("GET", "/no-content-length");
  21954. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21955. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21956. std::unique_ptr<char[]> buf(new char[len]);
  21957. std::string body;
  21958. ssize_t n;
  21959. while ((n = handle.read(buf.get(), len)) > 0) {
  21960. body.append(buf.get(), static_cast<size_t>(n));
  21961. }
  21962. EXPECT_EQ(0, n);
  21963. EXPECT_EQ("Hello", body);
  21964. }
  21965. #endif // CPPHTTPLIB_SSL_ENABLED
  21966. //==============================================================================
  21967. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21968. // results for various scenarios.
  21969. //==============================================================================
  21970. TEST(ParityTest, GetVsOpenStream) {
  21971. Server svr;
  21972. const std::string path = "/parity";
  21973. const std::string content = "Parity test content: hello world";
  21974. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21975. res.set_content(content, "text/plain");
  21976. });
  21977. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21978. auto se = detail::scope_exit([&] {
  21979. svr.stop();
  21980. t.join();
  21981. ASSERT_FALSE(svr.is_running());
  21982. });
  21983. svr.wait_until_ready();
  21984. Client cli(HOST, PORT);
  21985. // Non-stream path
  21986. auto r1 = cli.Get(path);
  21987. ASSERT_TRUE(r1);
  21988. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21989. // Stream path
  21990. auto h = cli.open_stream("GET", path);
  21991. ASSERT_TRUE(h.is_valid());
  21992. EXPECT_EQ(r1->body, read_all(h));
  21993. }
  21994. // Helper to compress data with provided compressor type T
  21995. template <typename Compressor>
  21996. static std::string compress_payload_for_parity(const std::string &in) {
  21997. std::string out;
  21998. Compressor compressor;
  21999. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22000. [&](const char *data, size_t n) {
  22001. out.append(data, n);
  22002. return true;
  22003. });
  22004. EXPECT_TRUE(ok);
  22005. return out;
  22006. }
  22007. // Helper function for compression parity tests
  22008. template <typename Compressor>
  22009. static void test_compression_parity(const std::string &original,
  22010. const std::string &path,
  22011. const std::string &encoding) {
  22012. const std::string compressed =
  22013. compress_payload_for_parity<Compressor>(original);
  22014. Server svr;
  22015. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22016. res.set_content(compressed, "application/octet-stream");
  22017. res.set_header("Content-Encoding", encoding);
  22018. });
  22019. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22020. auto se = detail::scope_exit([&] {
  22021. svr.stop();
  22022. t.join();
  22023. ASSERT_FALSE(svr.is_running());
  22024. });
  22025. svr.wait_until_ready();
  22026. Client cli(HOST, PORT);
  22027. // Non-streaming
  22028. {
  22029. auto res = cli.Get(path);
  22030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22031. EXPECT_EQ(StatusCode::OK_200, res->status);
  22032. EXPECT_EQ(original, res->body);
  22033. }
  22034. // Streaming
  22035. {
  22036. auto h = cli.open_stream("GET", path);
  22037. ASSERT_TRUE(h.is_valid());
  22038. EXPECT_EQ(original, read_all(h));
  22039. }
  22040. }
  22041. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22042. TEST(ParityTest, Gzip) {
  22043. test_compression_parity<detail::gzip_compressor>(
  22044. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22045. }
  22046. #endif
  22047. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22048. TEST(ParityTest, Brotli) {
  22049. test_compression_parity<detail::brotli_compressor>(
  22050. "Hello, brotli parity test payload", "/parity-br", "br");
  22051. }
  22052. #endif
  22053. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22054. TEST(ParityTest, Zstd) {
  22055. test_compression_parity<detail::zstd_compressor>(
  22056. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22057. }
  22058. #endif
  22059. //==============================================================================
  22060. // New Stream API Tests
  22061. //==============================================================================
  22062. inline std::string read_body(httplib::stream::Result &result) {
  22063. std::string body;
  22064. while (result.next()) {
  22065. body.append(result.data(), result.size());
  22066. }
  22067. return body;
  22068. }
  22069. TEST(ClientConnectionTest, Basic) {
  22070. httplib::ClientConnection conn;
  22071. EXPECT_FALSE(conn.is_open());
  22072. conn.sock = 1;
  22073. EXPECT_TRUE(conn.is_open());
  22074. httplib::ClientConnection conn2(std::move(conn));
  22075. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22076. conn2.sock = INVALID_SOCKET;
  22077. }
  22078. // Unified test server for all stream::* tests
  22079. class StreamApiTest : public ::testing::Test {
  22080. protected:
  22081. void SetUp() override {
  22082. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22083. res.set_content("Hello World!", "text/plain");
  22084. });
  22085. svr_.Get("/echo-params",
  22086. [](const httplib::Request &req, httplib::Response &res) {
  22087. std::string r;
  22088. for (const auto &p : req.params) {
  22089. if (!r.empty()) r += "&";
  22090. r += p.first + "=" + p.second;
  22091. }
  22092. res.set_content(r, "text/plain");
  22093. });
  22094. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22095. res.set_content(req.body, req.get_header_value("Content-Type"));
  22096. });
  22097. svr_.Post("/echo-headers",
  22098. [](const httplib::Request &req, httplib::Response &res) {
  22099. std::string r;
  22100. for (const auto &h : req.headers)
  22101. r += h.first + ": " + h.second + "\n";
  22102. res.set_content(r, "text/plain");
  22103. });
  22104. svr_.Post("/echo-params",
  22105. [](const httplib::Request &req, httplib::Response &res) {
  22106. std::string r = "params:";
  22107. for (const auto &p : req.params)
  22108. r += p.first + "=" + p.second + ";";
  22109. res.set_content(r + " body:" + req.body, "text/plain");
  22110. });
  22111. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22112. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22113. });
  22114. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22115. res.set_content("PUT:" + req.body, "text/plain");
  22116. });
  22117. svr_.Patch("/echo",
  22118. [](const httplib::Request &req, httplib::Response &res) {
  22119. res.set_content("PATCH:" + req.body, "text/plain");
  22120. });
  22121. svr_.Delete(
  22122. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22123. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22124. "text/plain");
  22125. });
  22126. svr_.Get("/head-test",
  22127. [](const httplib::Request &, httplib::Response &res) {
  22128. res.set_content("body for HEAD", "text/plain");
  22129. });
  22130. svr_.Options("/options",
  22131. [](const httplib::Request &, httplib::Response &res) {
  22132. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22133. });
  22134. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22135. svr_.wait_until_ready();
  22136. }
  22137. void TearDown() override {
  22138. svr_.stop();
  22139. if (thread_.joinable()) thread_.join();
  22140. }
  22141. httplib::Server svr_;
  22142. std::thread thread_;
  22143. };
  22144. // stream::Get tests
  22145. TEST_F(StreamApiTest, GetBasic) {
  22146. httplib::Client cli(HOST, PORT);
  22147. auto result = httplib::stream::Get(cli, "/hello");
  22148. ASSERT_TRUE(result.is_valid());
  22149. EXPECT_EQ(200, result.status());
  22150. EXPECT_EQ("Hello World!", read_body(result));
  22151. }
  22152. TEST_F(StreamApiTest, GetWithParams) {
  22153. httplib::Client cli(HOST, PORT);
  22154. httplib::Params params{{"foo", "bar"}};
  22155. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22156. ASSERT_TRUE(result.is_valid());
  22157. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22158. }
  22159. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22160. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22161. httplib::Client cli(HOST, PORT);
  22162. cli.set_payload_max_length(0);
  22163. auto result = httplib::stream::Get(cli, "/hello");
  22164. ASSERT_TRUE(result.is_valid());
  22165. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22166. EXPECT_EQ("Hello World!", read_body(result));
  22167. }
  22168. #endif
  22169. TEST_F(StreamApiTest, GetConnectionError) {
  22170. httplib::Client cli(HOST, 9999);
  22171. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22172. }
  22173. TEST_F(StreamApiTest, Get404) {
  22174. httplib::Client cli(HOST, PORT);
  22175. auto result = httplib::stream::Get(cli, "/nonexistent");
  22176. EXPECT_TRUE(result.is_valid());
  22177. EXPECT_EQ(404, result.status());
  22178. }
  22179. // stream::Post tests
  22180. TEST_F(StreamApiTest, PostBasic) {
  22181. httplib::Client cli(HOST, PORT);
  22182. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22183. "application/json");
  22184. ASSERT_TRUE(result.is_valid());
  22185. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22186. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22187. }
  22188. TEST_F(StreamApiTest, PostWithHeaders) {
  22189. httplib::Client cli(HOST, PORT);
  22190. httplib::Headers headers{{"X-Custom", "value"}};
  22191. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22192. "text/plain");
  22193. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22194. }
  22195. TEST_F(StreamApiTest, PostWithParams) {
  22196. httplib::Client cli(HOST, PORT);
  22197. httplib::Params params{{"k", "v"}};
  22198. auto result =
  22199. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22200. auto body = read_body(result);
  22201. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22202. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22203. }
  22204. TEST_F(StreamApiTest, PostLarge) {
  22205. httplib::Client cli(HOST, PORT);
  22206. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22207. size_t total = 0;
  22208. while (result.next()) {
  22209. total += result.size();
  22210. }
  22211. EXPECT_EQ(100u * 1024u, total);
  22212. }
  22213. // stream::Put/Patch tests
  22214. TEST_F(StreamApiTest, PutAndPatch) {
  22215. httplib::Client cli(HOST, PORT);
  22216. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22217. EXPECT_EQ("PUT:test", read_body(put));
  22218. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22219. EXPECT_EQ("PATCH:test", read_body(patch));
  22220. }
  22221. // stream::Delete tests
  22222. TEST_F(StreamApiTest, Delete) {
  22223. httplib::Client cli(HOST, PORT);
  22224. auto del1 = httplib::stream::Delete(cli, "/resource");
  22225. EXPECT_EQ("Deleted", read_body(del1));
  22226. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22227. EXPECT_EQ("Deleted:data", read_body(del2));
  22228. }
  22229. // stream::Head/Options tests
  22230. TEST_F(StreamApiTest, HeadAndOptions) {
  22231. httplib::Client cli(HOST, PORT);
  22232. auto head = httplib::stream::Head(cli, "/head-test");
  22233. EXPECT_TRUE(head.is_valid());
  22234. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22235. auto opts = httplib::stream::Options(cli, "/options");
  22236. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22237. }
  22238. // SSL stream::* tests
  22239. #ifdef CPPHTTPLIB_SSL_ENABLED
  22240. class SSLStreamApiTest : public ::testing::Test {
  22241. protected:
  22242. void SetUp() override {
  22243. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22244. res.set_content("Hello SSL!", "text/plain");
  22245. });
  22246. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22247. res.set_content(req.body, "text/plain");
  22248. });
  22249. port_ = svr_.bind_to_any_port("127.0.0.1");
  22250. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22251. svr_.wait_until_ready();
  22252. }
  22253. void TearDown() override {
  22254. svr_.stop();
  22255. if (thread_.joinable()) thread_.join();
  22256. }
  22257. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22258. std::thread thread_;
  22259. int port_ = 0;
  22260. };
  22261. TEST_F(SSLStreamApiTest, GetAndPost) {
  22262. httplib::SSLClient cli("127.0.0.1", port_);
  22263. cli.enable_server_certificate_verification(false);
  22264. auto get = httplib::stream::Get(cli, "/hello");
  22265. EXPECT_EQ("Hello SSL!", read_body(get));
  22266. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22267. EXPECT_EQ("test", read_body(post));
  22268. }
  22269. #endif
  22270. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22271. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22272. // BodyReader
  22273. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22274. // Test that read timeout during streaming is detected
  22275. // Use a large content-length response where server delays mid-stream
  22276. Server svr;
  22277. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22278. // Send a large response with delay in the middle
  22279. res.set_content_provider(
  22280. 1000, // content_length
  22281. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22282. if (offset < 100) {
  22283. // Send first 100 bytes immediately
  22284. std::string data(100, 'A');
  22285. sink.write(data.c_str(), data.size());
  22286. return true;
  22287. }
  22288. // Then delay longer than client timeout
  22289. std::this_thread::sleep_for(std::chrono::seconds(3));
  22290. std::string data(900, 'B');
  22291. sink.write(data.c_str(), data.size());
  22292. return true;
  22293. });
  22294. });
  22295. auto port = 8091;
  22296. std::thread t([&]() { svr.listen("localhost", port); });
  22297. svr.wait_until_ready();
  22298. Client cli("localhost", port);
  22299. cli.set_read_timeout(1, 0); // 1 second timeout
  22300. auto handle = cli.open_stream("GET", "/slow-stream");
  22301. ASSERT_TRUE(handle.is_valid());
  22302. char buf[256];
  22303. ssize_t total = 0;
  22304. ssize_t n;
  22305. bool got_error = false;
  22306. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22307. total += n;
  22308. }
  22309. if (n < 0) {
  22310. got_error = true;
  22311. // Should be timeout or read error
  22312. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22313. handle.get_read_error() == Error::Read)
  22314. << "Actual error: " << to_string(handle.get_read_error());
  22315. }
  22316. // Either we got an error, or we got less data than expected
  22317. EXPECT_TRUE(got_error || total < 1000)
  22318. << "Expected timeout but got all " << total << " bytes";
  22319. svr.stop();
  22320. t.join();
  22321. }
  22322. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22323. // Test connection closed detection via BodyReader
  22324. Server svr;
  22325. std::atomic<bool> close_now{false};
  22326. svr.Get("/will-close", [&](const Request &, Response &res) {
  22327. res.set_content_provider(
  22328. 10000, // Large content_length that we won't fully send
  22329. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22330. if (offset < 100) {
  22331. std::string data(100, 'X');
  22332. sink.write(data.c_str(), data.size());
  22333. return true;
  22334. }
  22335. // Wait for signal then abort
  22336. while (!close_now) {
  22337. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22338. }
  22339. return false; // Abort - server will close connection
  22340. });
  22341. });
  22342. auto port = 8092;
  22343. std::thread t([&]() { svr.listen("localhost", port); });
  22344. svr.wait_until_ready();
  22345. Client cli("localhost", port);
  22346. auto handle = cli.open_stream("GET", "/will-close");
  22347. ASSERT_TRUE(handle.is_valid());
  22348. char buf[256];
  22349. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22350. EXPECT_GT(n, 0) << "First read should succeed";
  22351. // Signal server to close
  22352. close_now = true;
  22353. // Keep reading until error or EOF
  22354. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22355. // Keep reading
  22356. }
  22357. // Should get an error since content_length wasn't satisfied
  22358. if (n < 0) {
  22359. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22360. handle.get_read_error() == Error::Read)
  22361. << "Actual error: " << to_string(handle.get_read_error());
  22362. }
  22363. svr.stop();
  22364. t.join();
  22365. }
  22366. #ifdef CPPHTTPLIB_SSL_ENABLED
  22367. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22368. // Test that read timeout during SSL streaming is detected
  22369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22370. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22371. res.set_content_provider(
  22372. 1000, "text/plain",
  22373. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22374. if (offset < 100) {
  22375. std::string data(100, 'A');
  22376. sink.write(data.c_str(), data.size());
  22377. return true;
  22378. }
  22379. std::this_thread::sleep_for(std::chrono::seconds(3));
  22380. std::string data(900, 'B');
  22381. sink.write(data.c_str(), data.size());
  22382. return true;
  22383. });
  22384. });
  22385. auto port = 8093;
  22386. std::thread t([&]() { svr.listen("localhost", port); });
  22387. svr.wait_until_ready();
  22388. SSLClient cli("localhost", port);
  22389. cli.enable_server_certificate_verification(false);
  22390. cli.set_read_timeout(1, 0); // 1 second timeout
  22391. auto handle = cli.open_stream("GET", "/slow-stream");
  22392. ASSERT_TRUE(handle.is_valid());
  22393. char buf[256];
  22394. ssize_t total = 0;
  22395. ssize_t n;
  22396. bool got_error = false;
  22397. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22398. total += n;
  22399. }
  22400. if (n < 0) {
  22401. got_error = true;
  22402. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22403. handle.get_read_error() == Error::Read)
  22404. << "Actual error: " << to_string(handle.get_read_error());
  22405. }
  22406. EXPECT_TRUE(got_error || total < 1000)
  22407. << "Expected timeout but got all " << total << " bytes";
  22408. svr.stop();
  22409. t.join();
  22410. }
  22411. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22412. // Test SSL connection closed detection
  22413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22414. std::atomic<bool> close_now{false};
  22415. svr.Get("/will-close", [&](const Request &, Response &res) {
  22416. res.set_content_provider(
  22417. 10000, "text/plain",
  22418. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22419. if (offset < 100) {
  22420. std::string data(100, 'X');
  22421. sink.write(data.c_str(), data.size());
  22422. return true;
  22423. }
  22424. while (!close_now) {
  22425. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22426. }
  22427. return false;
  22428. });
  22429. });
  22430. auto port = 8094;
  22431. std::thread t([&]() { svr.listen("localhost", port); });
  22432. svr.wait_until_ready();
  22433. SSLClient cli("localhost", port);
  22434. cli.enable_server_certificate_verification(false);
  22435. auto handle = cli.open_stream("GET", "/will-close");
  22436. ASSERT_TRUE(handle.is_valid());
  22437. char buf[256];
  22438. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22439. EXPECT_GT(n, 0);
  22440. // Signal server to close
  22441. close_now = true;
  22442. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22443. // Keep reading
  22444. }
  22445. if (n < 0) {
  22446. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22447. handle.get_read_error() == Error::Read)
  22448. << "Actual error: " << to_string(handle.get_read_error());
  22449. }
  22450. svr.stop();
  22451. t.join();
  22452. }
  22453. #endif
  22454. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22455. using namespace httplib;
  22456. // Create a test file
  22457. const char *fname = "etag_testfile.txt";
  22458. const char *content = "etag-content";
  22459. {
  22460. std::ofstream ofs(fname);
  22461. ofs << content;
  22462. ASSERT_TRUE(ofs.good());
  22463. }
  22464. Server svr;
  22465. svr.set_mount_point("/static", ".");
  22466. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22467. svr.wait_until_ready();
  22468. Client cli(HOST, PORT);
  22469. // First request: should get 200 with ETag header
  22470. auto res1 = cli.Get("/static/etag_testfile.txt");
  22471. ASSERT_TRUE(res1);
  22472. ASSERT_EQ(200, res1->status);
  22473. ASSERT_TRUE(res1->has_header("ETag"));
  22474. std::string etag = res1->get_header_value("ETag");
  22475. EXPECT_FALSE(etag.empty());
  22476. // Verify ETag format: W/"hex-hex"
  22477. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22478. EXPECT_EQ('W', etag[0]);
  22479. EXPECT_EQ('/', etag[1]);
  22480. EXPECT_EQ('"', etag[2]);
  22481. EXPECT_EQ('"', etag.back());
  22482. // Exact match: expect 304 Not Modified
  22483. Headers h2 = {{"If-None-Match", etag}};
  22484. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22485. ASSERT_TRUE(res2);
  22486. EXPECT_EQ(304, res2->status);
  22487. // Wildcard match: expect 304 Not Modified
  22488. Headers h3 = {{"If-None-Match", "*"}};
  22489. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22490. ASSERT_TRUE(res3);
  22491. EXPECT_EQ(304, res3->status);
  22492. // Non-matching ETag: expect 200
  22493. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22494. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22495. ASSERT_TRUE(res4);
  22496. EXPECT_EQ(200, res4->status);
  22497. // Multiple ETags with one matching: expect 304
  22498. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22499. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22500. ASSERT_TRUE(res5);
  22501. EXPECT_EQ(304, res5->status);
  22502. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22503. // that equivalent to the single comma-separated list above, so the match on
  22504. // the second line must still be found.
  22505. Headers h6;
  22506. h6.emplace("If-None-Match", "W/\"other\"");
  22507. h6.emplace("If-None-Match", etag);
  22508. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22509. ASSERT_TRUE(res6);
  22510. EXPECT_EQ(304, res6->status);
  22511. svr.stop();
  22512. t.join();
  22513. std::remove(fname);
  22514. }
  22515. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22516. using namespace httplib;
  22517. Server svr;
  22518. svr.set_mount_point("/static", ".");
  22519. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22520. svr.wait_until_ready();
  22521. Client cli(HOST, PORT);
  22522. // Send If-None-Match: * to a non-existent file
  22523. Headers h = {{"If-None-Match", "*"}};
  22524. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22526. EXPECT_EQ(404, res->status);
  22527. svr.stop();
  22528. t.join();
  22529. }
  22530. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22531. using namespace httplib;
  22532. // Create a test file
  22533. const char *fname = "etag_boundary_testfile.txt";
  22534. const char *content = "boundary-test";
  22535. {
  22536. std::ofstream ofs(fname);
  22537. ofs << content;
  22538. ASSERT_TRUE(ofs.good());
  22539. }
  22540. Server svr;
  22541. svr.set_mount_point("/static", ".");
  22542. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22543. svr.wait_until_ready();
  22544. Client cli(HOST, PORT);
  22545. // Get the actual ETag
  22546. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22547. ASSERT_TRUE(res1);
  22548. ASSERT_EQ(200, res1->status);
  22549. ASSERT_TRUE(res1->has_header("ETag"));
  22550. std::string etag = res1->get_header_value("ETag");
  22551. // Test 1: Very long ETag value (longer than actual ETag)
  22552. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22553. Headers h1 = {{"If-None-Match", "W/"
  22554. "\"very-long-etag-value-that-is-much-longer-"
  22555. "than-the-actual-etag-value\""}};
  22556. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22557. ASSERT_TRUE(res2);
  22558. EXPECT_EQ(200, res2->status); // Should not match
  22559. // Test 2: Long string followed by wildcard
  22560. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22561. // string)
  22562. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22563. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22564. ASSERT_TRUE(res3);
  22565. EXPECT_EQ(304, res3->status); // Should match on "*"
  22566. // Test 3: Wildcard followed by long string
  22567. // Should match on "*" immediately and return 304
  22568. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22569. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22570. ASSERT_TRUE(res4);
  22571. EXPECT_EQ(304, res4->status); // Should match on "*"
  22572. // Test 4: Multiple long non-matching values
  22573. // Should NOT match and return 200 (test that all comparisons are safe)
  22574. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22575. "W/\"second-long-non-matching-value\", "
  22576. "W/\"third-long-non-matching-value\""}};
  22577. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22578. ASSERT_TRUE(res5);
  22579. EXPECT_EQ(200, res5->status); // Should not match
  22580. // Test 5: Single character that is not "*" (edge case)
  22581. Headers h5 = {{"If-None-Match", "X"}};
  22582. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22583. ASSERT_TRUE(res6);
  22584. EXPECT_EQ(200, res6->status); // Should not match
  22585. svr.stop();
  22586. t.join();
  22587. std::remove(fname);
  22588. }
  22589. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22590. using namespace httplib;
  22591. // Create a test file
  22592. const char *fname = "ims_testfile.txt";
  22593. const char *content = "if-modified-since-test";
  22594. {
  22595. std::ofstream ofs(fname);
  22596. ofs << content;
  22597. ASSERT_TRUE(ofs.good());
  22598. }
  22599. Server svr;
  22600. svr.set_mount_point("/static", ".");
  22601. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22602. svr.wait_until_ready();
  22603. Client cli(HOST, PORT);
  22604. // First request: should get 200 with Last-Modified header
  22605. auto res1 = cli.Get("/static/ims_testfile.txt");
  22606. ASSERT_TRUE(res1);
  22607. ASSERT_EQ(200, res1->status);
  22608. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22609. std::string last_modified = res1->get_header_value("Last-Modified");
  22610. EXPECT_FALSE(last_modified.empty());
  22611. // If-Modified-Since with same time: expect 304
  22612. Headers h2 = {{"If-Modified-Since", last_modified}};
  22613. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22614. ASSERT_TRUE(res2);
  22615. EXPECT_EQ(304, res2->status);
  22616. // If-Modified-Since with future time: expect 304
  22617. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22618. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22619. ASSERT_TRUE(res3);
  22620. EXPECT_EQ(304, res3->status);
  22621. // If-Modified-Since with past time: expect 200
  22622. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22623. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22624. ASSERT_TRUE(res4);
  22625. EXPECT_EQ(200, res4->status);
  22626. // If-None-Match takes precedence over If-Modified-Since
  22627. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22628. ASSERT_TRUE(res1->has_header("ETag"));
  22629. std::string etag = res1->get_header_value("ETag");
  22630. Headers h5 = {{"If-None-Match", etag},
  22631. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22632. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22633. ASSERT_TRUE(res5);
  22634. EXPECT_EQ(304, res5->status);
  22635. svr.stop();
  22636. t.join();
  22637. std::remove(fname);
  22638. }
  22639. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22640. using namespace httplib;
  22641. Server svr;
  22642. // Endpoint that returns compressible content
  22643. svr.Get("/compressible", [](const Request &, Response &res) {
  22644. // Return a large enough body to trigger compression
  22645. std::string body(1000, 'a');
  22646. res.set_content(body, "text/plain");
  22647. });
  22648. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22649. svr.wait_until_ready();
  22650. Client cli(HOST, PORT);
  22651. // Request with gzip support: should get Vary header when compressed
  22652. cli.set_compress(true);
  22653. auto res1 = cli.Get("/compressible");
  22654. ASSERT_TRUE(res1);
  22655. EXPECT_EQ(200, res1->status);
  22656. // If Content-Encoding is set, Vary should also be set
  22657. if (res1->has_header("Content-Encoding")) {
  22658. EXPECT_TRUE(res1->has_header("Vary"));
  22659. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22660. }
  22661. // Request without Accept-Encoding header: should not have compression
  22662. Headers h_no_compress;
  22663. auto res2 = cli.Get("/compressible", h_no_compress);
  22664. ASSERT_TRUE(res2);
  22665. EXPECT_EQ(200, res2->status);
  22666. // Verify Vary header is present when compression is applied
  22667. // (the exact behavior depends on server configuration)
  22668. svr.stop();
  22669. t.join();
  22670. }
  22671. TEST(ETagTest, IfRangeWithETag) {
  22672. using namespace httplib;
  22673. // Create a test file with known content
  22674. const char *fname = "if_range_testfile.txt";
  22675. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22676. {
  22677. std::ofstream ofs(fname);
  22678. ofs << content;
  22679. ASSERT_TRUE(ofs.good());
  22680. }
  22681. Server svr;
  22682. svr.set_mount_point("/static", ".");
  22683. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22684. svr.wait_until_ready();
  22685. Client cli(HOST, PORT);
  22686. // First request: get ETag
  22687. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22688. ASSERT_TRUE(res1);
  22689. ASSERT_EQ(200, res1->status);
  22690. ASSERT_TRUE(res1->has_header("ETag"));
  22691. std::string etag = res1->get_header_value("ETag");
  22692. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22693. // Since our server generates weak ETags (W/"..."), If-Range with our
  22694. // ETag should NOT result in partial content - it should return full content.
  22695. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22696. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22697. ASSERT_TRUE(res2);
  22698. // Weak ETag in If-Range -> full content (200), not partial (206)
  22699. EXPECT_EQ(200, res2->status);
  22700. EXPECT_EQ(content, res2->body);
  22701. EXPECT_FALSE(res2->has_header("Content-Range"));
  22702. // Range request with non-matching If-Range (ETag): should get 200 (full
  22703. // content)
  22704. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22705. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22706. ASSERT_TRUE(res3);
  22707. EXPECT_EQ(200, res3->status);
  22708. EXPECT_EQ(content, res3->body);
  22709. EXPECT_FALSE(res3->has_header("Content-Range"));
  22710. // Range request with strong ETag (hypothetical - our server doesn't generate
  22711. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22712. // should return full content)
  22713. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22714. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22715. ASSERT_TRUE(res4);
  22716. EXPECT_EQ(200, res4->status);
  22717. EXPECT_EQ(content, res4->body);
  22718. EXPECT_FALSE(res4->has_header("Content-Range"));
  22719. svr.stop();
  22720. t.join();
  22721. std::remove(fname);
  22722. }
  22723. TEST(ETagTest, IfRangeWithDate) {
  22724. using namespace httplib;
  22725. // Create a test file
  22726. const char *fname = "if_range_date_testfile.txt";
  22727. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22728. {
  22729. std::ofstream ofs(fname);
  22730. ofs << content;
  22731. ASSERT_TRUE(ofs.good());
  22732. }
  22733. Server svr;
  22734. svr.set_mount_point("/static", ".");
  22735. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22736. svr.wait_until_ready();
  22737. Client cli(HOST, PORT);
  22738. // First request: get Last-Modified
  22739. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22740. ASSERT_TRUE(res1);
  22741. ASSERT_EQ(200, res1->status);
  22742. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22743. std::string last_modified = res1->get_header_value("Last-Modified");
  22744. // Range request with matching If-Range (date): should get 206
  22745. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22746. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22747. ASSERT_TRUE(res2);
  22748. EXPECT_EQ(206, res2->status);
  22749. EXPECT_EQ("FGHIJ", res2->body);
  22750. // Range request with old If-Range date: should get 200 (full content)
  22751. Headers h3 = {{"Range", "bytes=5-9"},
  22752. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22753. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22754. ASSERT_TRUE(res3);
  22755. EXPECT_EQ(200, res3->status);
  22756. EXPECT_EQ(content, res3->body);
  22757. // Range request with future If-Range date: should get 206
  22758. Headers h4 = {{"Range", "bytes=0-4"},
  22759. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22760. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22761. ASSERT_TRUE(res4);
  22762. EXPECT_EQ(206, res4->status);
  22763. EXPECT_EQ("ABCDE", res4->body);
  22764. svr.stop();
  22765. t.join();
  22766. std::remove(fname);
  22767. }
  22768. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22769. using namespace httplib;
  22770. const char *fname = "etag_malformed.txt";
  22771. const char *content = "malformed-etag";
  22772. {
  22773. std::ofstream ofs(fname);
  22774. ofs << content;
  22775. ASSERT_TRUE(ofs.good());
  22776. }
  22777. Server svr;
  22778. svr.set_mount_point("/static", ".");
  22779. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22780. svr.wait_until_ready();
  22781. Client cli(HOST, PORT);
  22782. // baseline: should get 200 and an ETag
  22783. auto res1 = cli.Get("/static/etag_malformed.txt");
  22784. ASSERT_TRUE(res1);
  22785. ASSERT_EQ(200, res1->status);
  22786. ASSERT_TRUE(res1->has_header("ETag"));
  22787. // Malformed ETag value (missing quotes) should be treated as non-matching
  22788. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22789. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22790. ASSERT_TRUE(res_bad);
  22791. EXPECT_EQ(200, res_bad->status);
  22792. // Whitespace-only header value should be considered invalid / non-matching
  22793. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22794. "Host: localhost\r\n"
  22795. "If-None-Match: \r\n"
  22796. "Connection: close\r\n"
  22797. "\r\n";
  22798. std::string out;
  22799. ASSERT_TRUE(send_request(5, raw_req, &out));
  22800. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22801. svr.stop();
  22802. t.join();
  22803. std::remove(fname);
  22804. }
  22805. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22806. using namespace httplib;
  22807. const char *fname = "ims_invalid_format.txt";
  22808. const char *content = "ims-bad-format";
  22809. {
  22810. std::ofstream ofs(fname);
  22811. ofs << content;
  22812. ASSERT_TRUE(ofs.good());
  22813. }
  22814. Server svr;
  22815. svr.set_mount_point("/static", ".");
  22816. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22817. svr.wait_until_ready();
  22818. Client cli(HOST, PORT);
  22819. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22820. ASSERT_TRUE(res1);
  22821. ASSERT_EQ(200, res1->status);
  22822. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22823. // If-Modified-Since with invalid format should not result in 304
  22824. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22825. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22826. ASSERT_TRUE(res_bad);
  22827. EXPECT_EQ(200, res_bad->status);
  22828. // If-Range with invalid date format should be treated as mismatch -> full
  22829. // content (200)
  22830. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22831. {"If-Range", "invalid-date"}};
  22832. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22833. ASSERT_TRUE(res_ifrange);
  22834. EXPECT_EQ(200, res_ifrange->status);
  22835. svr.stop();
  22836. t.join();
  22837. std::remove(fname);
  22838. }
  22839. TEST(ETagTest, IfRangeWithMalformedETag) {
  22840. using namespace httplib;
  22841. const char *fname = "ifrange_malformed.txt";
  22842. const std::string content = "0123456789";
  22843. {
  22844. std::ofstream ofs(fname);
  22845. ofs << content;
  22846. ASSERT_TRUE(ofs.good());
  22847. }
  22848. Server svr;
  22849. svr.set_mount_point("/static", ".");
  22850. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22851. svr.wait_until_ready();
  22852. Client cli(HOST, PORT);
  22853. // First request: get ETag
  22854. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22855. ASSERT_TRUE(res1);
  22856. ASSERT_EQ(200, res1->status);
  22857. ASSERT_TRUE(res1->has_header("ETag"));
  22858. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22859. // full content (200)
  22860. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22861. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22862. ASSERT_TRUE(res2);
  22863. EXPECT_EQ(200, res2->status);
  22864. EXPECT_EQ(content, res2->body);
  22865. svr.stop();
  22866. t.join();
  22867. std::remove(fname);
  22868. }
  22869. TEST(ETagTest, ExtremeLargeDateValues) {
  22870. using namespace httplib;
  22871. const char *fname = "ims_extreme_date.txt";
  22872. const char *content = "ims-extreme-date";
  22873. {
  22874. std::ofstream ofs(fname);
  22875. ofs << content;
  22876. ASSERT_TRUE(ofs.good());
  22877. }
  22878. Server svr;
  22879. svr.set_mount_point("/static", ".");
  22880. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22881. svr.wait_until_ready();
  22882. Client cli(HOST, PORT);
  22883. auto res1 = cli.Get(std::string("/static/") + fname);
  22884. ASSERT_TRUE(res1);
  22885. ASSERT_EQ(200, res1->status);
  22886. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22887. // Extremely large year that may overflow date parsing routines.
  22888. Headers h_large_date = {
  22889. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22890. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22891. ASSERT_TRUE(res_bad);
  22892. // Expect server to treat this as invalid/mismatch and return full content
  22893. EXPECT_EQ(200, res_bad->status);
  22894. // If-Range with extremely large date should be treated as mismatch -> full
  22895. // content (200)
  22896. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22897. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22898. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22899. ASSERT_TRUE(res_ifrange);
  22900. EXPECT_EQ(200, res_ifrange->status);
  22901. svr.stop();
  22902. t.join();
  22903. std::remove(fname);
  22904. }
  22905. TEST(ETagTest, NegativeFileModificationTime) {
  22906. using namespace httplib;
  22907. const char *fname = "ims_negative_mtime.txt";
  22908. const std::string content = "negative-mtime";
  22909. {
  22910. std::ofstream ofs(fname);
  22911. ofs << content;
  22912. ASSERT_TRUE(ofs.good());
  22913. }
  22914. // Try to set file mtime to a negative value. This may fail on some
  22915. // platforms/filesystems; if it fails, the test will still verify server
  22916. // behaves safely by performing a regular conditional request.
  22917. #if defined(__APPLE__) || defined(__linux__)
  22918. bool set_negative = false;
  22919. do {
  22920. struct timeval times[2];
  22921. // access time: now
  22922. times[0].tv_sec = time(nullptr);
  22923. times[0].tv_usec = 0;
  22924. // modification time: negative (e.g., -1)
  22925. times[1].tv_sec = -1;
  22926. times[1].tv_usec = 0;
  22927. if (utimes(fname, times) == 0) { set_negative = true; }
  22928. } while (0);
  22929. #else
  22930. bool set_negative = false;
  22931. #endif
  22932. Server svr;
  22933. svr.set_mount_point("/static", ".");
  22934. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22935. svr.wait_until_ready();
  22936. Client cli(HOST, PORT);
  22937. auto res1 = cli.Get(std::string("/static/") + fname);
  22938. ASSERT_TRUE(res1);
  22939. ASSERT_EQ(200, res1->status);
  22940. bool has_last_modified = res1->has_header("Last-Modified");
  22941. std::string last_modified;
  22942. if (has_last_modified) {
  22943. last_modified = res1->get_header_value("Last-Modified");
  22944. }
  22945. if (set_negative) {
  22946. // If we successfully set a negative mtime, ensure server returns a
  22947. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22948. // with an old date and ensure server handles it without crash.
  22949. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22950. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22951. ASSERT_TRUE(res2);
  22952. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22953. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22954. } else {
  22955. // Could not set negative mtime on this platform; fall back to verifying
  22956. // that normal invalid/malformed dates are treated safely (non-304).
  22957. Headers h_bad_date = {
  22958. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22959. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22960. ASSERT_TRUE(res_bad);
  22961. EXPECT_EQ(200, res_bad->status);
  22962. }
  22963. svr.stop();
  22964. t.join();
  22965. std::remove(fname);
  22966. }
  22967. //==============================================================================
  22968. // Integration Tests with Server
  22969. //==============================================================================
  22970. class SSEIntegrationTest : public ::testing::Test {
  22971. protected:
  22972. void SetUp() override {
  22973. stop_server_.store(false);
  22974. events_.clear();
  22975. server_ = httplib::detail::make_unique<Server>();
  22976. setup_server();
  22977. start_server();
  22978. }
  22979. void TearDown() override {
  22980. stop_server_.store(true);
  22981. event_cv_.notify_all();
  22982. server_->stop();
  22983. if (server_thread_.joinable()) { server_thread_.join(); }
  22984. }
  22985. void setup_server() {
  22986. // Simple SSE endpoint
  22987. server_->Get("/events", [this](const Request &req, Response &res) {
  22988. auto last_id = req.get_header_value("Last-Event-ID");
  22989. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22990. res.set_chunked_content_provider(
  22991. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22992. std::unique_lock<std::mutex> lock(event_mutex_);
  22993. if (event_cv_.wait_for(
  22994. lock, std::chrono::milliseconds(200), [this] {
  22995. return !events_.empty() || stop_server_.load();
  22996. })) {
  22997. if (stop_server_.load()) { return false; }
  22998. if (!events_.empty()) {
  22999. std::string event = events_.front();
  23000. events_.erase(events_.begin());
  23001. sink.write(event.data(), event.size());
  23002. return true;
  23003. }
  23004. }
  23005. return !stop_server_.load();
  23006. });
  23007. });
  23008. // Endpoint that returns error
  23009. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23010. res.status = 500;
  23011. res.set_content("Internal Server Error", "text/plain");
  23012. });
  23013. // Endpoint for custom event types
  23014. server_->Get("/custom-events", [](const Request &, Response &res) {
  23015. res.set_chunked_content_provider(
  23016. "text/event-stream", [](size_t offset, DataSink &sink) {
  23017. if (offset == 0) {
  23018. std::string event = "event: update\ndata: updated\n\n"
  23019. "event: delete\ndata: deleted\n\n";
  23020. sink.write(event.data(), event.size());
  23021. }
  23022. return false; // End stream after sending
  23023. });
  23024. });
  23025. }
  23026. void start_server() {
  23027. port_ = server_->bind_to_any_port(HOST);
  23028. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23029. // Wait for server to start
  23030. while (!server_->is_running()) {
  23031. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23032. }
  23033. }
  23034. int get_port() const { return port_; }
  23035. void send_event(const std::string &event) {
  23036. std::lock_guard<std::mutex> lock(event_mutex_);
  23037. events_.push_back(event);
  23038. event_cv_.notify_all();
  23039. }
  23040. std::unique_ptr<Server> server_;
  23041. std::thread server_thread_;
  23042. std::mutex event_mutex_;
  23043. std::condition_variable event_cv_;
  23044. std::vector<std::string> events_;
  23045. std::atomic<bool> stop_server_{false};
  23046. std::string last_received_event_id_;
  23047. int port_ = 0;
  23048. };
  23049. //==============================================================================
  23050. // SSE Parser Tests
  23051. //==============================================================================
  23052. struct SSEParseResult {
  23053. std::vector<sse::SSEMessage> events;
  23054. std::vector<std::string> ids;
  23055. std::vector<int> retries;
  23056. bool ok = true;
  23057. std::string trace; // Every handler call in order
  23058. };
  23059. static SSEParseResult
  23060. sse_parse(const std::vector<std::string> &chunks,
  23061. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23062. SSEParseResult r;
  23063. detail::SSEParser parser(
  23064. [&](const sse::SSEMessage &msg) {
  23065. r.events.push_back(msg);
  23066. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23067. },
  23068. [&](const std::string &id) {
  23069. r.ids.push_back(id);
  23070. r.trace += "id[" + id + "]";
  23071. },
  23072. [&](int retry_ms) {
  23073. r.retries.push_back(retry_ms);
  23074. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23075. },
  23076. max_event_length);
  23077. for (const auto &chunk : chunks) {
  23078. if (!parser.parse(chunk.data(), chunk.size())) {
  23079. r.ok = false;
  23080. break;
  23081. }
  23082. }
  23083. return r;
  23084. }
  23085. static SSEParseResult sse_parse(const std::string &stream) {
  23086. return sse_parse(std::vector<std::string>{stream});
  23087. }
  23088. TEST(SSEParserTest, SingleLineData) {
  23089. auto r = sse_parse("data: hello\n\n");
  23090. ASSERT_EQ(r.events.size(), 1u);
  23091. EXPECT_EQ(r.events[0].data, "hello");
  23092. EXPECT_EQ(r.events[0].event, "message");
  23093. }
  23094. TEST(SSEParserTest, MultiLineData) {
  23095. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23096. ASSERT_EQ(r.events.size(), 1u);
  23097. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23098. }
  23099. TEST(SSEParserTest, CustomEventType) {
  23100. auto r = sse_parse("event: update\ndata: payload\n\n");
  23101. ASSERT_EQ(r.events.size(), 1u);
  23102. EXPECT_EQ(r.events[0].event, "update");
  23103. EXPECT_EQ(r.events[0].data, "payload");
  23104. }
  23105. TEST(SSEParserTest, EventIdHandling) {
  23106. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23107. ASSERT_EQ(r.events.size(), 1u);
  23108. EXPECT_EQ(r.events[0].id, "12345");
  23109. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23110. }
  23111. TEST(SSEParserTest, EmptyEventId) {
  23112. auto r = sse_parse("id:\ndata: test\n\n");
  23113. ASSERT_EQ(r.events.size(), 1u);
  23114. EXPECT_EQ(r.events[0].id, "");
  23115. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23116. }
  23117. TEST(SSEParserTest, CommentsIgnored) {
  23118. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23119. ASSERT_EQ(r.events.size(), 1u);
  23120. EXPECT_EQ(r.events[0].data, "hello");
  23121. EXPECT_EQ(r.events[0].event, "message");
  23122. }
  23123. TEST(SSEParserTest, ColonInValue) {
  23124. auto r = sse_parse("data: hello:world:test\n\n");
  23125. ASSERT_EQ(r.events.size(), 1u);
  23126. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23127. }
  23128. TEST(SSEParserTest, FieldNameOnly) {
  23129. // A line without a colon is a field name with an empty value
  23130. auto r = sse_parse("data\n\n");
  23131. ASSERT_EQ(r.events.size(), 1u);
  23132. EXPECT_EQ(r.events[0].data, "");
  23133. }
  23134. TEST(SSEParserTest, TrailingCarriageReturn) {
  23135. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23136. ASSERT_EQ(r.events.size(), 1u);
  23137. EXPECT_EQ(r.events[0].event, "update");
  23138. EXPECT_EQ(r.events[0].data, "hello");
  23139. }
  23140. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23141. auto r = sse_parse("data\r\n\r\n");
  23142. ASSERT_EQ(r.events.size(), 1u);
  23143. EXPECT_EQ(r.events[0].data, "");
  23144. }
  23145. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23146. auto r = sse_parse("event: update\rdata: hello\r\r");
  23147. ASSERT_EQ(r.events.size(), 1u);
  23148. EXPECT_EQ(r.events[0].event, "update");
  23149. EXPECT_EQ(r.events[0].data, "hello");
  23150. }
  23151. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23152. // Chunk boundaries fall inside every \r\n and right before the first one
  23153. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23154. "\ndata: hello\r", "\n\r", "\n"});
  23155. ASSERT_EQ(r.events.size(), 1u);
  23156. EXPECT_EQ(r.events[0].event, "update");
  23157. EXPECT_EQ(r.events[0].data, "hello");
  23158. }
  23159. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23160. // Only a BOM at the start of the stream is ignored
  23161. auto r = sse_parse("\xEF\xBB\xBF"
  23162. "data: first\n\n"
  23163. "\xEF\xBB\xBF"
  23164. "data: second\n\n");
  23165. ASSERT_EQ(r.events.size(), 1u);
  23166. EXPECT_EQ(r.events[0].data, "first");
  23167. }
  23168. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23169. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23170. ASSERT_EQ(r.events.size(), 1u);
  23171. EXPECT_EQ(r.events[0].data, "hello");
  23172. EXPECT_EQ(r.events[0].event, "message");
  23173. }
  23174. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23175. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23176. ASSERT_EQ(r.events.size(), 2u);
  23177. EXPECT_EQ(r.events[0].data, "hello");
  23178. EXPECT_EQ(r.events[1].data, "hello");
  23179. }
  23180. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23181. // An event without data is not dispatched, and its type must not leak
  23182. // into the next event
  23183. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23184. ASSERT_EQ(r.events.size(), 1u);
  23185. EXPECT_EQ(r.events[0].event, "message");
  23186. EXPECT_EQ(r.events[0].data, "hello");
  23187. }
  23188. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23189. // Also when the empty field replaces an earlier type
  23190. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23191. ASSERT_EQ(r.events.size(), 2u);
  23192. EXPECT_EQ(r.events[0].event, "message");
  23193. EXPECT_EQ(r.events[1].event, "message");
  23194. }
  23195. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23196. auto r = sse_parse("id: 42\n\n");
  23197. EXPECT_TRUE(r.events.empty());
  23198. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23199. }
  23200. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23201. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23202. ASSERT_EQ(r.events.size(), 2u);
  23203. EXPECT_EQ(r.events[0].id, "1");
  23204. EXPECT_EQ(r.events[1].id, "");
  23205. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23206. }
  23207. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23208. // Ids that cannot be carried in a Last-Event-ID header
  23209. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23210. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23211. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23212. }
  23213. TEST(SSEParserTest, RetryDigitsOnly) {
  23214. auto r = sse_parse("retry: 1000\n");
  23215. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23216. // A value that is not all ASCII digits, or does not fit, is ignored
  23217. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23218. EXPECT_TRUE(r.retries.empty());
  23219. }
  23220. TEST(SSEParserTest, CompleteEventParsing) {
  23221. auto r = sse_parse("event: notification\nid: evt-42\n"
  23222. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23223. ASSERT_EQ(r.events.size(), 1u);
  23224. EXPECT_EQ(r.events[0].event, "notification");
  23225. EXPECT_EQ(r.events[0].id, "evt-42");
  23226. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23227. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23228. }
  23229. TEST(SSEParserTest, IncompleteEventNotReported) {
  23230. // An event still waiting for its blank line when the stream ends is
  23231. // discarded per the SSE spec
  23232. auto r = sse_parse("id: 1\ndata: x\n");
  23233. EXPECT_TRUE(r.events.empty());
  23234. EXPECT_TRUE(r.ids.empty());
  23235. }
  23236. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23237. const std::vector<std::string> streams = {
  23238. "\xEF\xBB\xBF"
  23239. "data: bom\r\n\r\n",
  23240. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23241. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23242. };
  23243. for (const auto &stream : streams) {
  23244. auto expected = sse_parse(stream).trace;
  23245. ASSERT_FALSE(expected.empty());
  23246. for (size_t i = 0; i <= stream.size(); i++) {
  23247. auto r = sse_parse(
  23248. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23249. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23250. }
  23251. std::vector<std::string> bytes;
  23252. for (auto c : stream) {
  23253. bytes.emplace_back(1, c);
  23254. }
  23255. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23256. }
  23257. }
  23258. TEST(SSEParserTest, MaxEventLength) {
  23259. // A line still waiting for its end
  23260. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23261. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23262. // Data accumulated over the lines of one event
  23263. EXPECT_TRUE(
  23264. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23265. EXPECT_FALSE(
  23266. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23267. // 0 means no limit
  23268. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23269. // Events completed in the same chunk are still reported
  23270. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23271. EXPECT_FALSE(r.ok);
  23272. ASSERT_EQ(r.events.size(), 1u);
  23273. EXPECT_EQ(r.events[0].data, "a");
  23274. }
  23275. TEST(SSEMessageTest, Clear) {
  23276. sse::SSEMessage msg;
  23277. msg.event = "custom";
  23278. msg.data = "some data";
  23279. msg.id = "123";
  23280. msg.clear();
  23281. EXPECT_EQ(msg.event, "message");
  23282. EXPECT_EQ(msg.data, "");
  23283. EXPECT_EQ(msg.id, "");
  23284. }
  23285. //==============================================================================
  23286. // SSE Integration Tests
  23287. //==============================================================================
  23288. // Test: Successful connection and on_open callback
  23289. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23290. // Add a simple endpoint that sends one event and closes
  23291. server_->Get("/simple-event", [](const Request &, Response &res) {
  23292. res.set_chunked_content_provider(
  23293. "text/event-stream", [](size_t offset, DataSink &sink) {
  23294. if (offset == 0) {
  23295. std::string event = "data: hello\n\n";
  23296. sink.write(event.data(), event.size());
  23297. }
  23298. return false; // Close stream after sending
  23299. });
  23300. });
  23301. Client client("localhost", get_port());
  23302. sse::SSEClient sse(client, "/simple-event");
  23303. std::atomic<bool> open_called{false};
  23304. std::atomic<bool> message_received{false};
  23305. sse.on_open([&open_called]() { open_called.store(true); });
  23306. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23307. if (msg.data == "hello") { message_received.store(true); }
  23308. });
  23309. sse.set_reconnect_interval(100);
  23310. sse.set_max_reconnect_attempts(1);
  23311. // Start async
  23312. sse.start_async();
  23313. // Wait for message to be processed
  23314. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23315. sse.stop();
  23316. EXPECT_TRUE(open_called.load());
  23317. EXPECT_TRUE(message_received.load());
  23318. }
  23319. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23320. // A data line that never ends.
  23321. server_->Get("/endless-line", [](const Request &, Response &res) {
  23322. res.set_chunked_content_provider(
  23323. "text/event-stream", [](size_t offset, DataSink &sink) {
  23324. if (offset == 0) { sink.write("data: ", 6); }
  23325. std::string chunk(64 * 1024, 'A');
  23326. return sink.write(chunk.data(), chunk.size());
  23327. });
  23328. });
  23329. Client client("localhost", get_port());
  23330. sse::SSEClient sse(client, "/endless-line");
  23331. std::atomic<bool> too_long{false};
  23332. sse.on_error([&](Error err) {
  23333. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23334. });
  23335. sse.set_max_reconnect_attempts(1);
  23336. sse.start_async();
  23337. for (int i = 0; i < 500 && !too_long; i++) {
  23338. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23339. }
  23340. sse.stop();
  23341. EXPECT_TRUE(too_long);
  23342. }
  23343. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23344. // Far more in all than the client's payload limit below.
  23345. server_->Get("/many-events", [](const Request &, Response &res) {
  23346. res.set_chunked_content_provider(
  23347. "text/event-stream", [](size_t offset, DataSink &sink) {
  23348. if (offset == 0) {
  23349. std::string events;
  23350. for (int i = 0; i < 1000; i++) {
  23351. events += "data: message\n\n";
  23352. }
  23353. sink.write(events.data(), events.size());
  23354. }
  23355. return false;
  23356. });
  23357. });
  23358. Client client("localhost", get_port());
  23359. client.set_payload_max_length(1024);
  23360. sse::SSEClient sse(client, "/many-events");
  23361. std::atomic<int> messages{0};
  23362. std::atomic<bool> too_large{false};
  23363. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23364. sse.on_error([&](Error err) {
  23365. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23366. });
  23367. sse.set_max_reconnect_attempts(1);
  23368. sse.start_async();
  23369. for (int i = 0; i < 500 && messages < 1000; i++) {
  23370. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23371. }
  23372. sse.stop();
  23373. EXPECT_GE(messages.load(), 1000);
  23374. EXPECT_FALSE(too_large);
  23375. }
  23376. // Test: on_message callback
  23377. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23378. // Endpoint that sends multiple events then closes
  23379. server_->Get("/multi-event", [](const Request &, Response &res) {
  23380. res.set_chunked_content_provider(
  23381. "text/event-stream", [](size_t offset, DataSink &sink) {
  23382. if (offset == 0) {
  23383. std::string events = "data: message1\n\ndata: message2\n\n";
  23384. sink.write(events.data(), events.size());
  23385. }
  23386. return false;
  23387. });
  23388. });
  23389. Client client("localhost", get_port());
  23390. sse::SSEClient sse(client, "/multi-event");
  23391. std::vector<std::string> received_messages;
  23392. std::mutex messages_mutex;
  23393. sse.on_message([&](const sse::SSEMessage &msg) {
  23394. std::lock_guard<std::mutex> lock(messages_mutex);
  23395. received_messages.push_back(msg.data);
  23396. });
  23397. sse.set_reconnect_interval(100);
  23398. sse.set_max_reconnect_attempts(1);
  23399. sse.start_async();
  23400. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23401. sse.stop();
  23402. std::lock_guard<std::mutex> lock(messages_mutex);
  23403. EXPECT_GE(received_messages.size(), 2u);
  23404. if (received_messages.size() >= 2) {
  23405. EXPECT_EQ(received_messages[0], "message1");
  23406. EXPECT_EQ(received_messages[1], "message2");
  23407. }
  23408. }
  23409. // Test: on_event for specific types
  23410. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23411. Client client("localhost", get_port());
  23412. sse::SSEClient sse(client, "/custom-events");
  23413. std::atomic<bool> update_received{false};
  23414. std::atomic<bool> delete_received{false};
  23415. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23416. if (msg.data == "updated") { update_received.store(true); }
  23417. });
  23418. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23419. if (msg.data == "deleted") { delete_received.store(true); }
  23420. });
  23421. sse.set_max_reconnect_attempts(1);
  23422. sse.start_async();
  23423. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23424. sse.stop();
  23425. EXPECT_TRUE(update_received.load());
  23426. EXPECT_TRUE(delete_received.load());
  23427. }
  23428. // Test: on_error callback on connection failure
  23429. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23430. // Connect to a non-existent port
  23431. Client client("localhost", 59999);
  23432. sse::SSEClient sse(client, "/events");
  23433. std::atomic<bool> error_called{false};
  23434. Error received_error = Error::Success;
  23435. sse.on_error([&](Error err) {
  23436. error_called.store(true);
  23437. received_error = err;
  23438. });
  23439. sse.set_reconnect_interval(50);
  23440. sse.set_max_reconnect_attempts(1);
  23441. sse.start_async();
  23442. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23443. sse.stop();
  23444. EXPECT_TRUE(error_called.load());
  23445. EXPECT_NE(received_error, Error::Success);
  23446. }
  23447. // Test: Last-Event-ID header sent on reconnect
  23448. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23449. // Endpoint that sends event with ID
  23450. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23451. res.set_chunked_content_provider(
  23452. "text/event-stream", [](size_t offset, DataSink &sink) {
  23453. if (offset == 0) {
  23454. std::string event = "id: evt-123\ndata: test\n\n";
  23455. sink.write(event.data(), event.size());
  23456. }
  23457. return false;
  23458. });
  23459. });
  23460. Client client("localhost", get_port());
  23461. sse::SSEClient sse(client, "/event-with-id");
  23462. std::atomic<bool> id_received{false};
  23463. sse.on_message([&](const sse::SSEMessage &msg) {
  23464. if (!msg.id.empty()) { id_received.store(true); }
  23465. });
  23466. sse.set_reconnect_interval(100);
  23467. sse.set_max_reconnect_attempts(1);
  23468. sse.start_async();
  23469. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23470. sse.stop();
  23471. EXPECT_TRUE(id_received.load());
  23472. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23473. }
  23474. // Test: last_event_id() read from another thread while start_async() runs
  23475. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23476. // Ids of every length up to 200, so the stored id keeps changing size
  23477. server_->Get("/many-ids", [](const Request &, Response &res) {
  23478. res.set_chunked_content_provider(
  23479. "text/event-stream", [](size_t offset, DataSink &sink) {
  23480. if (offset == 0) {
  23481. std::string events;
  23482. for (size_t i = 0; i < 2000; i++) {
  23483. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23484. events += "data: x\n\n";
  23485. }
  23486. events += "id: end\ndata: x\n\n";
  23487. sink.write(events.data(), events.size());
  23488. }
  23489. return false;
  23490. });
  23491. });
  23492. Client client("localhost", get_port());
  23493. sse::SSEClient sse(client, "/many-ids");
  23494. // Wait out the rest of the test rather than replay the stream
  23495. sse.set_reconnect_interval(10000);
  23496. sse.set_max_reconnect_attempts(1);
  23497. sse.start_async();
  23498. auto well_formed = true;
  23499. std::string id;
  23500. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23501. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23502. id = sse.last_event_id();
  23503. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23504. well_formed = false;
  23505. }
  23506. }
  23507. sse.stop();
  23508. EXPECT_TRUE(well_formed);
  23509. EXPECT_EQ(sse.last_event_id(), "end");
  23510. }
  23511. // Test: Manual stop
  23512. TEST_F(SSEIntegrationTest, ManualStop) {
  23513. // Endpoint that sends one event and stays open briefly. The server outlives
  23514. // this test body, so the provider uses the fixture's flag, not a local.
  23515. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23516. res.set_chunked_content_provider(
  23517. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23518. if (offset == 0) {
  23519. std::string event = "data: connected\n\n";
  23520. sink.write(event.data(), event.size());
  23521. }
  23522. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23523. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23524. }
  23525. return false;
  23526. });
  23527. });
  23528. Client client("localhost", get_port());
  23529. sse::SSEClient sse(client, "/stay-open");
  23530. std::atomic<bool> connected{false};
  23531. sse.on_open([&connected]() { connected.store(true); });
  23532. sse.set_reconnect_interval(100);
  23533. sse.set_max_reconnect_attempts(1);
  23534. sse.start_async();
  23535. // Wait for connection to establish
  23536. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23537. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23538. }
  23539. EXPECT_TRUE(connected.load());
  23540. EXPECT_TRUE(sse.is_connected());
  23541. // Signal handler to stop
  23542. stop_server_.store(true);
  23543. // Stop SSE client
  23544. sse.stop();
  23545. EXPECT_FALSE(sse.is_connected());
  23546. }
  23547. // Sends one event, then nothing until stop is set
  23548. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23549. return [&stop](const Request &, Response &res) {
  23550. res.set_chunked_content_provider(
  23551. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23552. if (offset == 0) {
  23553. std::string event = "data: hello\n\n";
  23554. sink.write(event.data(), event.size());
  23555. }
  23556. while (!stop.load()) {
  23557. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23558. }
  23559. return false;
  23560. });
  23561. };
  23562. }
  23563. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23564. static void check_stop_interrupts_blocked_read(Client &client) {
  23565. client.set_read_timeout(30, 0);
  23566. for (auto by_destructor : {false, true}) {
  23567. std::atomic<bool> received{false};
  23568. std::chrono::steady_clock::time_point start;
  23569. {
  23570. sse::SSEClient sse(client, "/idle-stream");
  23571. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23572. sse.start_async();
  23573. for (int i = 0; i < 500 && !received.load(); ++i) {
  23574. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23575. }
  23576. ASSERT_TRUE(received.load());
  23577. // Let the client block in the next read
  23578. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23579. start = std::chrono::steady_clock::now();
  23580. if (!by_destructor) { sse.stop(); }
  23581. }
  23582. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23583. std::chrono::seconds(2));
  23584. }
  23585. }
  23586. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23587. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23588. Client client("localhost", get_port());
  23589. check_stop_interrupts_blocked_read(client);
  23590. }
  23591. #ifdef CPPHTTPLIB_SSL_ENABLED
  23592. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23594. std::atomic<bool> done{false};
  23595. svr.Get("/idle-stream", idle_event_stream(done));
  23596. auto port = svr.bind_to_any_port(HOST);
  23597. std::thread t([&] { svr.listen_after_bind(); });
  23598. auto se = detail::scope_exit([&] {
  23599. done.store(true);
  23600. svr.stop();
  23601. t.join();
  23602. });
  23603. svr.wait_until_ready();
  23604. Client client("https://localhost:" + std::to_string(port));
  23605. client.enable_server_certificate_verification(false);
  23606. check_stop_interrupts_blocked_read(client);
  23607. }
  23608. #endif
  23609. // Test: SSEClient with custom headers
  23610. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23611. // Setup a server endpoint that checks for custom header
  23612. std::atomic<bool> header_received{false};
  23613. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23614. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23615. header_received.store(true);
  23616. }
  23617. res.set_chunked_content_provider("text/event-stream",
  23618. [](size_t, DataSink &) { return false; });
  23619. });
  23620. Client client("localhost", get_port());
  23621. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23622. sse::SSEClient sse(client, "/header-check", headers);
  23623. sse.set_max_reconnect_attempts(1);
  23624. sse.start_async();
  23625. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23626. sse.stop();
  23627. EXPECT_TRUE(header_received.load());
  23628. }
  23629. // Test: Reconnect interval configuration
  23630. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23631. Client client("localhost", get_port());
  23632. sse::SSEClient sse(client, "/events");
  23633. auto &result = sse.set_reconnect_interval(500);
  23634. // Builder pattern should return reference to self
  23635. EXPECT_EQ(&result, &sse);
  23636. }
  23637. // Test: Max reconnect attempts
  23638. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23639. // Connect to non-existent port to force reconnects
  23640. Client client("localhost", 59998);
  23641. sse::SSEClient sse(client, "/events");
  23642. std::atomic<int> error_count{0};
  23643. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23644. sse.set_reconnect_interval(50);
  23645. sse.set_max_reconnect_attempts(2);
  23646. auto start = std::chrono::steady_clock::now();
  23647. sse.start(); // Blocking call
  23648. auto end = std::chrono::steady_clock::now();
  23649. // Should have stopped after 2 failed attempts
  23650. EXPECT_GE(error_count.load(), 2);
  23651. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23652. auto duration =
  23653. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23654. #ifdef _WIN32
  23655. // Windows is much slower for socket connection failures
  23656. EXPECT_LT(duration.count(), 7000);
  23657. #else
  23658. EXPECT_LT(duration.count(), 1000);
  23659. #endif
  23660. }
  23661. // Test: Multi-line data in integration
  23662. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23663. // Endpoint with multi-line data
  23664. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23665. res.set_chunked_content_provider(
  23666. "text/event-stream", [](size_t offset, DataSink &sink) {
  23667. if (offset == 0) {
  23668. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23669. sink.write(event.data(), event.size());
  23670. }
  23671. return false;
  23672. });
  23673. });
  23674. Client client("localhost", get_port());
  23675. sse::SSEClient sse(client, "/multiline-data");
  23676. std::string received_data;
  23677. std::mutex data_mutex;
  23678. sse.on_message([&](const sse::SSEMessage &msg) {
  23679. std::lock_guard<std::mutex> lock(data_mutex);
  23680. received_data = msg.data;
  23681. });
  23682. sse.set_reconnect_interval(100);
  23683. sse.set_max_reconnect_attempts(1);
  23684. sse.start_async();
  23685. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23686. sse.stop();
  23687. std::lock_guard<std::mutex> lock(data_mutex);
  23688. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23689. }
  23690. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23691. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23692. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23693. DataSink &sink) {
  23694. if (offset == 0) {
  23695. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23696. sink.write(events.data(), events.size());
  23697. }
  23698. return false;
  23699. });
  23700. });
  23701. Client client("localhost", get_port());
  23702. sse::SSEClient sse(client, "/empty-data-lines");
  23703. std::mutex mutex;
  23704. std::condition_variable cv;
  23705. std::vector<std::string> received;
  23706. sse.on_message([&](const sse::SSEMessage &msg) {
  23707. std::lock_guard<std::mutex> lock(mutex);
  23708. received.push_back(msg.data);
  23709. cv.notify_all();
  23710. });
  23711. sse.set_max_reconnect_attempts(1);
  23712. sse.start_async();
  23713. {
  23714. std::unique_lock<std::mutex> lock(mutex);
  23715. cv.wait_for(lock, std::chrono::seconds(2),
  23716. [&] { return received.size() >= 3; });
  23717. }
  23718. sse.stop();
  23719. ASSERT_GE(received.size(), 3u);
  23720. EXPECT_EQ(received[0], "");
  23721. EXPECT_EQ(received[1], "\nhello");
  23722. EXPECT_EQ(received[2], "");
  23723. }
  23724. // Test: Auto-reconnect after server disconnection
  23725. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23726. std::atomic<int> connection_count{0};
  23727. std::atomic<int> message_count{0};
  23728. // Endpoint that sends one event and closes, forcing reconnect
  23729. server_->Get("/reconnect-test",
  23730. [&connection_count](const Request &, Response &res) {
  23731. connection_count.fetch_add(1);
  23732. res.set_chunked_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. }
  23738. return false; // Close connection after sending
  23739. });
  23740. });
  23741. Client client("localhost", get_port());
  23742. sse::SSEClient sse(client, "/reconnect-test");
  23743. sse.on_message([&message_count](const sse::SSEMessage &) {
  23744. message_count.fetch_add(1);
  23745. });
  23746. sse.set_reconnect_interval(100);
  23747. sse.set_max_reconnect_attempts(3);
  23748. sse.start_async();
  23749. // Wait long enough for multiple reconnects
  23750. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23751. sse.stop();
  23752. // Should have connected multiple times (initial + reconnects)
  23753. EXPECT_GE(connection_count.load(), 2);
  23754. // Should have received messages from multiple connections
  23755. EXPECT_GE(message_count.load(), 2);
  23756. }
  23757. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23758. std::atomic<int> connection_count{0};
  23759. // Neither Content-Length nor chunked: the close ends the stream
  23760. server_->Get("/close-delimited",
  23761. [&connection_count](const Request &, Response &res) {
  23762. connection_count.fetch_add(1);
  23763. res.set_content_provider(
  23764. "text/event-stream", [](size_t offset, DataSink &sink) {
  23765. if (offset == 0) {
  23766. std::string event = "data: hello\n\n";
  23767. sink.write(event.data(), event.size());
  23768. } else {
  23769. sink.done();
  23770. }
  23771. return true;
  23772. });
  23773. });
  23774. Client client("localhost", get_port());
  23775. sse::SSEClient sse(client, "/close-delimited");
  23776. std::atomic<int> error_count{0};
  23777. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23778. sse.set_reconnect_interval(100);
  23779. sse.start_async();
  23780. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23781. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23782. }
  23783. sse.stop();
  23784. // Reconnects as after any end of the stream, but reports no error
  23785. EXPECT_GE(connection_count.load(), 2);
  23786. EXPECT_EQ(0, error_count.load());
  23787. }
  23788. // Test: A retry field of all ASCII digits sets the reconnection time
  23789. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23790. std::mutex mutex;
  23791. std::condition_variable cv;
  23792. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23793. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23794. {
  23795. std::lock_guard<std::mutex> lock(mutex);
  23796. connected_at.push_back(std::chrono::steady_clock::now());
  23797. cv.notify_all();
  23798. }
  23799. res.set_chunked_content_provider(
  23800. "text/event-stream", [](size_t offset, DataSink &sink) {
  23801. if (offset == 0) {
  23802. std::string event = "retry: 0\ndata: hello\n\n";
  23803. sink.write(event.data(), event.size());
  23804. }
  23805. return false;
  23806. });
  23807. });
  23808. Client client("localhost", get_port());
  23809. sse::SSEClient sse(client, "/zero-retry");
  23810. sse.set_reconnect_interval(10000);
  23811. sse.start_async();
  23812. {
  23813. std::unique_lock<std::mutex> lock(mutex);
  23814. cv.wait_for(lock, std::chrono::seconds(5),
  23815. [&] { return connected_at.size() >= 2; });
  23816. }
  23817. sse.stop();
  23818. // The server-supplied interval is applied, but never below 100ms, so
  23819. // "retry: 0" does not cause a busy reconnect loop
  23820. std::lock_guard<std::mutex> lock(mutex);
  23821. ASSERT_GE(connected_at.size(), 2u);
  23822. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23823. connected_at[1] - connected_at[0])
  23824. .count();
  23825. EXPECT_GE(interval_ms, 100);
  23826. }
  23827. // Test: Last-Event-ID sent on reconnect
  23828. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23829. std::atomic<int> connection_count{0};
  23830. std::vector<std::string> received_last_event_ids;
  23831. std::mutex id_mutex;
  23832. // Endpoint that checks Last-Event-ID header and sends event with ID
  23833. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23834. int conn = connection_count.fetch_add(1);
  23835. // Capture the Last-Event-ID header from each connection
  23836. {
  23837. std::lock_guard<std::mutex> lock(id_mutex);
  23838. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23839. }
  23840. res.set_chunked_content_provider(
  23841. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23842. if (offset == 0) {
  23843. std::string event =
  23844. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23845. sink.write(event.data(), event.size());
  23846. }
  23847. return false;
  23848. });
  23849. });
  23850. Client client("localhost", get_port());
  23851. sse::SSEClient sse(client, "/reconnect-with-id");
  23852. sse.set_reconnect_interval(100);
  23853. sse.set_max_reconnect_attempts(3);
  23854. sse.start_async();
  23855. // Wait for at least 2 connections
  23856. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23857. sse.stop();
  23858. // Verify behavior
  23859. std::lock_guard<std::mutex> lock(id_mutex);
  23860. EXPECT_GE(received_last_event_ids.size(), 2u);
  23861. // First connection should have no Last-Event-ID
  23862. if (!received_last_event_ids.empty()) {
  23863. EXPECT_EQ(received_last_event_ids[0], "");
  23864. }
  23865. // Second connection should have Last-Event-ID from first connection
  23866. if (received_last_event_ids.size() >= 2) {
  23867. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23868. }
  23869. }
  23870. // Test: set_headers updates headers used on reconnect
  23871. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23872. std::vector<std::string> received_tokens;
  23873. std::mutex token_mutex;
  23874. // Endpoint that captures Authorization header
  23875. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23876. {
  23877. std::lock_guard<std::mutex> lock(token_mutex);
  23878. received_tokens.push_back(req.get_header_value("Authorization"));
  23879. }
  23880. res.set_chunked_content_provider(
  23881. "text/event-stream", [](size_t offset, DataSink &sink) {
  23882. if (offset == 0) {
  23883. std::string event = "data: hello\n\n";
  23884. sink.write(event.data(), event.size());
  23885. }
  23886. return false; // Close connection to trigger reconnect
  23887. });
  23888. });
  23889. Client client("localhost", get_port());
  23890. Headers headers = {{"Authorization", "Bearer old-token"}};
  23891. sse::SSEClient sse(client, "/auth-check", headers);
  23892. // Update headers on each successful connection
  23893. sse.on_open(
  23894. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23895. sse.set_reconnect_interval(100);
  23896. sse.set_max_reconnect_attempts(3);
  23897. sse.start_async();
  23898. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23899. sse.stop();
  23900. std::lock_guard<std::mutex> lock(token_mutex);
  23901. ASSERT_GE(received_tokens.size(), 2u);
  23902. // First connection uses original header
  23903. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23904. // Second connection uses updated header from set_headers
  23905. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23906. }
  23907. // Test: 401 allows reconnection (so on_error can refresh headers)
  23908. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23909. std::atomic<int> connection_count{0};
  23910. // Endpoint: returns 401 on first attempt, 200 on second
  23911. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23912. int conn = connection_count.fetch_add(1);
  23913. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23914. res.status = StatusCode::Unauthorized_401;
  23915. res.set_content("Unauthorized", "text/plain");
  23916. return;
  23917. }
  23918. res.set_chunked_content_provider(
  23919. "text/event-stream", [](size_t offset, DataSink &sink) {
  23920. if (offset == 0) {
  23921. std::string event = "data: authenticated\n\n";
  23922. sink.write(event.data(), event.size());
  23923. }
  23924. return false;
  23925. });
  23926. });
  23927. Client client("localhost", get_port());
  23928. Headers headers = {{"Authorization", "Bearer expired"}};
  23929. sse::SSEClient sse(client, "/auth-retry", headers);
  23930. std::atomic<bool> message_received{false};
  23931. // Refresh token on error
  23932. sse.on_error(
  23933. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23934. sse.on_message([&](const sse::SSEMessage &msg) {
  23935. if (msg.data == "authenticated") { message_received.store(true); }
  23936. });
  23937. sse.set_reconnect_interval(100);
  23938. sse.set_max_reconnect_attempts(3);
  23939. sse.start_async();
  23940. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23941. sse.stop();
  23942. // Should have reconnected after 401 and succeeded with new token
  23943. EXPECT_GE(connection_count.load(), 2);
  23944. EXPECT_TRUE(message_received.load());
  23945. }
  23946. TEST(Issue2318Test, EmptyHostString) {
  23947. {
  23948. httplib::Client cli_empty("", PORT);
  23949. auto res = cli_empty.Get("/");
  23950. ASSERT_FALSE(res);
  23951. EXPECT_EQ(httplib::Error::Connection, res.error());
  23952. }
  23953. {
  23954. httplib::Client cli(" ", PORT);
  23955. auto res = cli.Get("/");
  23956. ASSERT_FALSE(res);
  23957. EXPECT_EQ(httplib::Error::Connection, res.error());
  23958. }
  23959. }
  23960. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23961. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23962. Server svr;
  23963. // Set a small payload limit (1KB)
  23964. svr.set_payload_max_length(1024);
  23965. svr.Post("/test", [&](const Request &req, Response &res) {
  23966. res.set_content("Body size: " + std::to_string(req.body.size()),
  23967. "text/plain");
  23968. });
  23969. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23970. auto se = detail::scope_exit([&] {
  23971. svr.stop();
  23972. listen_thread.join();
  23973. });
  23974. svr.wait_until_ready();
  23975. // Create data that compresses well but exceeds limit when decompressed
  23976. // 8KB of repeated null bytes compresses to a very small size
  23977. std::string original_data(8 * 1024, '\0');
  23978. // Compress the data using gzip
  23979. std::string compressed_data;
  23980. detail::gzip_compressor compressor;
  23981. compressor.compress(original_data.data(), original_data.size(), true,
  23982. [&](const char *data, size_t size) {
  23983. compressed_data.append(data, size);
  23984. return true;
  23985. });
  23986. // Verify compression worked (compressed should be much smaller)
  23987. ASSERT_LT(compressed_data.size(), original_data.size());
  23988. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23989. // Send compressed data with Content-Encoding: gzip
  23990. Client cli(HOST, PORT);
  23991. Headers headers = {{"Content-Encoding", "gzip"}};
  23992. auto res =
  23993. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23994. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23996. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23997. }
  23998. #endif
  23999. // ============================================================================
  24000. // OpenSSL-Specific Tests
  24001. // ============================================================================
  24002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24003. X509 *readCertificate(const std::string &strFileName) {
  24004. std::ifstream inStream(strFileName);
  24005. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24006. std::istreambuf_iterator<char>());
  24007. if (strCertPEM.empty()) return (nullptr);
  24008. BIO *pbCert = BIO_new(BIO_s_mem());
  24009. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24010. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24011. BIO_free(pbCert);
  24012. return (pCert);
  24013. }
  24014. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24015. std::ifstream inStream(strFileName);
  24016. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24017. std::istreambuf_iterator<char>());
  24018. if (strPrivateKeyPEM.empty()) return (nullptr);
  24019. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24020. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24021. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24022. BIO_free(pbPrivKey);
  24023. return (pPrivateKey);
  24024. }
  24025. TEST(BindServerTest, UpdateCerts) {
  24026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24027. int port = svr.bind_to_any_port("0.0.0.0");
  24028. ASSERT_TRUE(svr.is_valid());
  24029. ASSERT_TRUE(port > 0);
  24030. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24031. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24032. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24033. ASSERT_TRUE(cert != nullptr);
  24034. ASSERT_TRUE(ca_cert != nullptr);
  24035. ASSERT_TRUE(key != nullptr);
  24036. X509_STORE *cert_store = X509_STORE_new();
  24037. X509_STORE_add_cert(cert_store, ca_cert);
  24038. // svr.update_certs(cert, key, cert_store); // deprecated
  24039. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24040. CLIENT_CA_CERT_FILE);
  24041. ASSERT_TRUE(svr.is_valid());
  24042. svr.stop();
  24043. X509_STORE_free(cert_store);
  24044. X509_free(cert);
  24045. X509_free(ca_cert);
  24046. EVP_PKEY_free(key);
  24047. }
  24048. // Test that update_certs() updates client CA list correctly
  24049. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24050. // Start with file-based constructor
  24051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24052. ASSERT_TRUE(svr.is_valid());
  24053. // Initially no client CA list should be set
  24054. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24055. ASSERT_TRUE(ssl_ctx != nullptr);
  24056. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24057. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24058. // Now update with client CA (PEM string)
  24059. std::string cert_pem, key_pem, ca_pem;
  24060. read_file(SERVER_CERT_FILE, cert_pem);
  24061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24063. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24064. ASSERT_TRUE(svr.is_valid());
  24065. // Now client CA list should be set
  24066. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24067. ASSERT_TRUE(ca_list_after != nullptr);
  24068. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24069. }
  24070. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24071. // Test that the file-path SSLServer constructor properly sets the client CA
  24072. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24074. ASSERT_TRUE(svr.is_valid());
  24075. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24076. ASSERT_TRUE(ssl_ctx != nullptr);
  24077. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24078. ASSERT_TRUE(ca_list != nullptr);
  24079. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24080. }
  24081. #endif
  24082. // ============================================================================
  24083. // MbedTLS-Specific Tests
  24084. // ============================================================================
  24085. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24086. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24087. using namespace httplib::tls;
  24088. // Track if callback was invoked
  24089. bool callback_invoked = false;
  24090. // The callback receives void* ctx which is actually MbedTlsContext*
  24091. // We can access the mbedtls_ssl_config via the context
  24092. auto setup_callback = [&callback_invoked](void *ctx) {
  24093. callback_invoked = true;
  24094. // Cast to MbedTlsContext* to access the ssl config
  24095. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24096. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24097. // Use static variables to hold certificate data (simplified for test)
  24098. static mbedtls_x509_crt own_cert;
  24099. static mbedtls_pk_context own_key;
  24100. static mbedtls_x509_crt ca_chain;
  24101. static bool initialized = false;
  24102. if (!initialized) {
  24103. mbedtls_x509_crt_init(&own_cert);
  24104. mbedtls_pk_init(&own_key);
  24105. mbedtls_x509_crt_init(&ca_chain);
  24106. // Load server certificate
  24107. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24108. return false;
  24109. }
  24110. // Load server private key.
  24111. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24112. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24113. #if MBEDTLS_VERSION_MAJOR == 3
  24114. ,
  24115. mbedtls_ctr_drbg_random, nullptr
  24116. #endif
  24117. ) != 0) {
  24118. return false;
  24119. }
  24120. // Load CA chain for client verification
  24121. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24122. return false;
  24123. }
  24124. initialized = true;
  24125. }
  24126. // Configure the SSL config
  24127. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24128. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24129. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24130. // Set minimum TLS version using mbedTLS native API
  24131. #if MBEDTLS_VERSION_MAJOR >= 3
  24132. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24133. #else
  24134. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24135. MBEDTLS_SSL_MINOR_VERSION_3);
  24136. #endif
  24137. return true;
  24138. };
  24139. SSLServer svr(setup_callback);
  24140. ASSERT_TRUE(svr.is_valid());
  24141. ASSERT_TRUE(callback_invoked);
  24142. svr.Get("/test", [&](const Request &req, Response &res) {
  24143. res.set_content("test", "text/plain");
  24144. auto cert = req.peer_cert();
  24145. ASSERT_TRUE(static_cast<bool>(cert));
  24146. auto common_name = cert.subject_cn();
  24147. EXPECT_EQ("Common Name", common_name);
  24148. });
  24149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24150. auto se = detail::scope_exit([&] {
  24151. svr.stop();
  24152. t.join();
  24153. ASSERT_FALSE(svr.is_running());
  24154. });
  24155. svr.wait_until_ready();
  24156. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24157. cli.enable_server_certificate_verification(false);
  24158. cli.set_connection_timeout(30);
  24159. auto res = cli.Get("/test");
  24160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24161. ASSERT_EQ(StatusCode::OK_200, res->status);
  24162. }
  24163. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24164. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24165. // keep-alive SSL session, which reads through that config in
  24166. // mbedtls_ssl_close_notify.
  24167. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24169. ASSERT_TRUE(svr.is_valid());
  24170. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24171. res.set_content("test", "text/plain");
  24172. });
  24173. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24174. auto se = detail::scope_exit([&] {
  24175. svr.stop();
  24176. t.join();
  24177. ASSERT_FALSE(svr.is_running());
  24178. });
  24179. svr.wait_until_ready();
  24180. {
  24181. SSLClient cli(HOST, PORT);
  24182. cli.enable_server_certificate_verification(false);
  24183. cli.set_keep_alive(true);
  24184. auto res = cli.Get("/test");
  24185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24186. ASSERT_EQ(StatusCode::OK_200, res->status);
  24187. // cli is destructed here with the keep-alive SSL session still open.
  24188. }
  24189. }
  24190. #endif
  24191. // WebSocket Tests
  24192. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24193. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24194. // defining the meaning of these bits has been negotiated.
  24195. auto make_frame = [](uint8_t first_byte) {
  24196. std::string frame;
  24197. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24198. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24199. frame += "Hello";
  24200. return frame;
  24201. };
  24202. // RSV1 set (0x40)
  24203. {
  24204. detail::BufferStream strm;
  24205. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24206. ws::Opcode opcode;
  24207. std::string payload;
  24208. bool fin;
  24209. EXPECT_EQ(
  24210. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24211. ws::impl::FrameRead::Fail);
  24212. }
  24213. // RSV2 set (0x20)
  24214. {
  24215. detail::BufferStream strm;
  24216. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24217. ws::Opcode opcode;
  24218. std::string payload;
  24219. bool fin;
  24220. EXPECT_EQ(
  24221. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24222. ws::impl::FrameRead::Fail);
  24223. }
  24224. // RSV3 set (0x10)
  24225. {
  24226. detail::BufferStream strm;
  24227. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24228. ws::Opcode opcode;
  24229. std::string payload;
  24230. bool fin;
  24231. EXPECT_EQ(
  24232. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24233. ws::impl::FrameRead::Fail);
  24234. }
  24235. // No RSV bits set - should succeed
  24236. {
  24237. detail::BufferStream strm;
  24238. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24239. ws::Opcode opcode;
  24240. std::string payload;
  24241. bool fin;
  24242. EXPECT_EQ(
  24243. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24244. ws::impl::FrameRead::Ok);
  24245. EXPECT_EQ(ws::Opcode::Text, opcode);
  24246. EXPECT_EQ("Hello", payload);
  24247. EXPECT_TRUE(fin);
  24248. }
  24249. }
  24250. TEST(WebSocketTest, ControlFrameValidation) {
  24251. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24252. // payload length <= 125.
  24253. // Ping with FIN=0 - must be rejected
  24254. {
  24255. detail::BufferStream strm;
  24256. std::string frame;
  24257. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24258. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  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. // Close with FIN=0 - must be rejected
  24268. {
  24269. detail::BufferStream strm;
  24270. std::string frame;
  24271. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24272. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24273. strm.write(frame.data(), frame.size());
  24274. ws::Opcode opcode;
  24275. std::string payload;
  24276. bool fin;
  24277. EXPECT_EQ(
  24278. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24279. ws::impl::FrameRead::Fail);
  24280. }
  24281. // Ping with payload_len=126 (extended length) - must be rejected
  24282. {
  24283. detail::BufferStream strm;
  24284. std::string frame;
  24285. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24286. frame += static_cast<char>(126); // payload_len=126 (>125)
  24287. frame += static_cast<char>(0x00); // extended length high byte
  24288. frame += static_cast<char>(126); // extended length low byte
  24289. frame += std::string(126, 'x');
  24290. strm.write(frame.data(), frame.size());
  24291. ws::Opcode opcode;
  24292. std::string payload;
  24293. bool fin;
  24294. EXPECT_EQ(
  24295. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24296. ws::impl::FrameRead::Fail);
  24297. }
  24298. // Ping with FIN=1 and payload_len=125 - should succeed
  24299. {
  24300. detail::BufferStream strm;
  24301. std::string frame;
  24302. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24303. frame += static_cast<char>(125); // payload_len=125
  24304. frame += std::string(125, 'x');
  24305. strm.write(frame.data(), frame.size());
  24306. ws::Opcode opcode;
  24307. std::string payload;
  24308. bool fin;
  24309. EXPECT_EQ(
  24310. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24311. ws::impl::FrameRead::Ok);
  24312. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24313. EXPECT_EQ(125u, payload.size());
  24314. EXPECT_TRUE(fin);
  24315. }
  24316. }
  24317. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24318. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24319. // length MUST be 0.
  24320. // MSB set - must be rejected
  24321. {
  24322. detail::BufferStream strm;
  24323. std::string frame;
  24324. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24325. frame += static_cast<char>(127); // 64-bit extended length
  24326. frame += static_cast<char>(0x80); // MSB set (invalid)
  24327. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24328. strm.write(frame.data(), frame.size());
  24329. ws::Opcode opcode;
  24330. std::string payload;
  24331. bool fin;
  24332. EXPECT_EQ(
  24333. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24334. ws::impl::FrameRead::Fail);
  24335. }
  24336. // MSB clear - should pass length parsing (will be rejected by max_len,
  24337. // but that's a different check; use a small length to verify)
  24338. {
  24339. detail::BufferStream strm;
  24340. std::string frame;
  24341. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24342. frame += static_cast<char>(127); // 64-bit extended length
  24343. frame += std::string(7, '\0'); // high bytes = 0
  24344. frame += static_cast<char>(0x03); // length = 3
  24345. frame += "abc";
  24346. strm.write(frame.data(), frame.size());
  24347. ws::Opcode opcode;
  24348. std::string payload;
  24349. bool fin;
  24350. EXPECT_EQ(
  24351. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24352. ws::impl::FrameRead::Ok);
  24353. EXPECT_EQ(ws::Opcode::Text, opcode);
  24354. EXPECT_EQ("abc", payload);
  24355. }
  24356. }
  24357. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24358. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24359. // Valid UTF-8
  24360. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24361. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24362. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24363. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24364. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24365. // Invalid UTF-8
  24366. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24367. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24368. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24369. EXPECT_FALSE(
  24370. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24371. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24372. }
  24373. TEST(WebSocketTest, ConnectAndDisconnect) {
  24374. Server svr;
  24375. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24376. std::string msg;
  24377. while (ws.read(msg)) {}
  24378. });
  24379. auto port = svr.bind_to_any_port(HOST);
  24380. std::thread t([&]() { svr.listen_after_bind(); });
  24381. svr.wait_until_ready();
  24382. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24383. auto res = client.connect();
  24384. ASSERT_TRUE(res);
  24385. EXPECT_EQ(Error::Success, res.error());
  24386. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24387. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24388. EXPECT_TRUE(client.is_open());
  24389. client.close();
  24390. EXPECT_FALSE(client.is_open());
  24391. svr.stop();
  24392. t.join();
  24393. }
  24394. TEST(WebSocketTest, ValidURL) {
  24395. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24396. EXPECT_TRUE(ws1.is_valid());
  24397. ws::WebSocketClient ws2("ws://example.com/path");
  24398. EXPECT_TRUE(ws2.is_valid());
  24399. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24400. EXPECT_TRUE(ws3.is_valid());
  24401. #ifdef CPPHTTPLIB_SSL_ENABLED
  24402. ws::WebSocketClient wss1("wss://example.com/path");
  24403. EXPECT_TRUE(wss1.is_valid());
  24404. ws::WebSocketClient wss2("wss://example.com:443/path");
  24405. EXPECT_TRUE(wss2.is_valid());
  24406. #endif
  24407. }
  24408. TEST(WebSocketTest, InvalidURL) {
  24409. // No scheme
  24410. ws::WebSocketClient ws1("localhost:8080/path");
  24411. EXPECT_FALSE(ws1.is_valid());
  24412. // No path
  24413. ws::WebSocketClient ws2("ws://localhost:8080");
  24414. EXPECT_FALSE(ws2.is_valid());
  24415. // Empty string
  24416. ws::WebSocketClient ws3("");
  24417. EXPECT_FALSE(ws3.is_valid());
  24418. // Missing host
  24419. ws::WebSocketClient ws4("ws://:8080/path");
  24420. EXPECT_FALSE(ws4.is_valid());
  24421. // Port number overflow — should not crash
  24422. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24423. EXPECT_FALSE(ws5.is_valid());
  24424. // Port out of range
  24425. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24426. EXPECT_FALSE(ws6.is_valid());
  24427. }
  24428. TEST(WebSocketTest, UnsupportedScheme) {
  24429. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24430. ws::WebSocketClient ws1("http://localhost:8080/path");
  24431. EXPECT_FALSE(ws1.is_valid());
  24432. ws::WebSocketClient ws2("https://localhost:8080/path");
  24433. EXPECT_FALSE(ws2.is_valid());
  24434. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24435. EXPECT_FALSE(ws3.is_valid());
  24436. #else
  24437. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24438. std::invalid_argument);
  24439. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24440. std::invalid_argument);
  24441. #endif
  24442. }
  24443. TEST(WebSocketTest, ConnectWhenInvalid) {
  24444. ws::WebSocketClient ws("not a valid url");
  24445. EXPECT_FALSE(ws.is_valid());
  24446. auto res = ws.connect();
  24447. EXPECT_FALSE(res);
  24448. EXPECT_EQ(Error::Connection, res.error());
  24449. EXPECT_EQ(-1, res.status());
  24450. }
  24451. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24452. // Grab a port that is free, then close it again so nothing listens there
  24453. Server svr;
  24454. auto port = svr.bind_to_any_port(HOST);
  24455. svr.stop();
  24456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24457. auto res = client.connect();
  24458. ASSERT_FALSE(res);
  24459. EXPECT_EQ(Error::Connection, res.error());
  24460. EXPECT_EQ(-1, res.status());
  24461. }
  24462. TEST(WebSocketTest, DefaultPort) {
  24463. ws::WebSocketClient ws1("ws://example.com/path");
  24464. EXPECT_TRUE(ws1.is_valid());
  24465. // ws:// defaults to port 80 (verified by successful parse)
  24466. #ifdef CPPHTTPLIB_SSL_ENABLED
  24467. ws::WebSocketClient ws2("wss://example.com/path");
  24468. EXPECT_TRUE(ws2.is_valid());
  24469. // wss:// defaults to port 443 (verified by successful parse)
  24470. #endif
  24471. }
  24472. TEST(WebSocketTest, IPv6LiteralAddress) {
  24473. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24474. EXPECT_TRUE(ws1.is_valid());
  24475. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24476. EXPECT_TRUE(ws2.is_valid());
  24477. }
  24478. TEST(WebSocketTest, ComplexPath) {
  24479. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24480. EXPECT_TRUE(ws1.is_valid());
  24481. ws::WebSocketClient ws2("ws://localhost:8080/");
  24482. EXPECT_TRUE(ws2.is_valid());
  24483. }
  24484. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24485. Server svr;
  24486. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24487. std::string msg;
  24488. while (ws.read(msg)) {}
  24489. });
  24490. auto port = svr.bind_to_any_port(HOST);
  24491. std::thread t([&]() { svr.listen_after_bind(); });
  24492. svr.wait_until_ready();
  24493. auto another_host = "example.com";
  24494. auto wrong_ip = "192.0.2.1";
  24495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24496. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24497. ASSERT_TRUE(client.connect());
  24498. EXPECT_TRUE(client.is_open());
  24499. client.close();
  24500. svr.stop();
  24501. t.join();
  24502. }
  24503. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24504. Server svr;
  24505. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24506. std::string msg;
  24507. while (ws.read(msg)) {}
  24508. });
  24509. auto port = svr.bind_to_any_port(HOST);
  24510. std::thread t([&]() { svr.listen_after_bind(); });
  24511. svr.wait_until_ready();
  24512. auto wrong_ip = "192.0.2.1";
  24513. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24514. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24515. client.set_connection_timeout(1);
  24516. client.set_read_timeout(1);
  24517. client.set_write_timeout(1);
  24518. EXPECT_FALSE(client.connect());
  24519. EXPECT_FALSE(client.is_open());
  24520. svr.stop();
  24521. t.join();
  24522. }
  24523. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24524. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24525. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24526. // (RFC 6761) is only a map key and the Host header value.
  24527. auto host = "target.invalid";
  24528. Server svr;
  24529. std::string received_host;
  24530. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24531. received_host = req.get_header_value("Host");
  24532. std::string msg;
  24533. while (ws.read(msg)) {}
  24534. });
  24535. auto port = svr.bind_to_any_port(HOST);
  24536. std::thread t([&]() { svr.listen_after_bind(); });
  24537. // ASSERT_* below returns from the test body, which would leave t joinable
  24538. // and make ~thread call std::terminate.
  24539. auto se = detail::scope_exit([&] {
  24540. svr.stop();
  24541. if (t.joinable()) { t.join(); }
  24542. });
  24543. svr.wait_until_ready();
  24544. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24545. std::to_string(port) + "/ws");
  24546. client.set_direct_hostname_addr_map({{host, HOST}});
  24547. ASSERT_TRUE(client.connect());
  24548. EXPECT_TRUE(client.is_open());
  24549. client.close();
  24550. svr.stop();
  24551. t.join();
  24552. // The mapping only redirects the connection; the identity stays host_.
  24553. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24554. }
  24555. class WebSocketIntegrationTest : public ::testing::Test {
  24556. protected:
  24557. void SetUp() override {
  24558. server_ = httplib::detail::make_unique<Server>();
  24559. setup_server();
  24560. start_server();
  24561. }
  24562. void TearDown() override {
  24563. server_->stop();
  24564. if (server_thread_.joinable()) { server_thread_.join(); }
  24565. }
  24566. void setup_server() {
  24567. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24568. std::string msg;
  24569. ws::ReadResult ret;
  24570. while ((ret = ws.read(msg))) {
  24571. if (ret == ws::Binary) {
  24572. ws.send(msg.data(), msg.size());
  24573. } else {
  24574. ws.send(msg);
  24575. }
  24576. }
  24577. });
  24578. server_->WebSocket("/ws-echo-string",
  24579. [](const Request &, ws::WebSocket &ws) {
  24580. std::string msg;
  24581. while (ws.read(msg)) {
  24582. ws.send("echo: " + msg);
  24583. }
  24584. });
  24585. server_->WebSocket(
  24586. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24587. // Echo back request metadata
  24588. ws.send("path:" + req.path);
  24589. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24590. std::string msg;
  24591. while (ws.read(msg)) {}
  24592. });
  24593. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24594. std::string msg;
  24595. ws.read(msg); // wait for a message
  24596. ws.close();
  24597. });
  24598. server_->WebSocket("/ws-close-status",
  24599. [](const Request &, ws::WebSocket &ws) {
  24600. std::string msg;
  24601. ws.read(msg); // wait for a message
  24602. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24603. });
  24604. server_->WebSocket(
  24605. "/ws-subprotocol",
  24606. [](const Request &, ws::WebSocket &ws) {
  24607. std::string msg;
  24608. while (ws.read(msg)) {
  24609. ws.send(msg);
  24610. }
  24611. },
  24612. [](const std::vector<std::string> &protocols) -> std::string {
  24613. for (const auto &p : protocols) {
  24614. if (p == "graphql-ws") { return p; }
  24615. }
  24616. return "";
  24617. });
  24618. server_->WebSocket(
  24619. "/ws-subprotocol-unoffered",
  24620. [](const Request &, ws::WebSocket &ws) {
  24621. std::string msg;
  24622. while (ws.read(msg)) {
  24623. ws.send(msg);
  24624. }
  24625. },
  24626. [](const std::vector<std::string> &) -> std::string {
  24627. return "admin";
  24628. });
  24629. }
  24630. void start_server() {
  24631. port_ = server_->bind_to_any_port(HOST);
  24632. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24633. server_->wait_until_ready();
  24634. }
  24635. std::unique_ptr<Server> server_;
  24636. std::thread server_thread_;
  24637. int port_ = 0;
  24638. };
  24639. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24640. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24641. "/ws-echo");
  24642. ASSERT_TRUE(client.connect());
  24643. ASSERT_TRUE(client.is_open());
  24644. ASSERT_TRUE(client.send("Hello WebSocket"));
  24645. std::string msg;
  24646. EXPECT_EQ(ws::Text, client.read(msg));
  24647. EXPECT_EQ("Hello WebSocket", msg);
  24648. client.close();
  24649. }
  24650. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24651. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24652. "/ws-echo");
  24653. ASSERT_TRUE(client.connect());
  24654. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24655. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24656. std::string msg;
  24657. EXPECT_EQ(ws::Binary, client.read(msg));
  24658. EXPECT_EQ(binary_data, msg);
  24659. client.close();
  24660. }
  24661. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24663. "/ws-echo");
  24664. ASSERT_TRUE(client.connect());
  24665. for (int i = 0; i < 10; i++) {
  24666. auto text = "message " + std::to_string(i);
  24667. ASSERT_TRUE(client.send(text));
  24668. std::string msg;
  24669. ASSERT_TRUE(client.read(msg));
  24670. EXPECT_EQ(text, msg);
  24671. }
  24672. client.close();
  24673. }
  24674. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24675. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24676. "/ws-close");
  24677. ASSERT_TRUE(client.connect());
  24678. // Send a message to trigger the server to close
  24679. ASSERT_TRUE(client.send("trigger close"));
  24680. // The server will close, so read should return false
  24681. std::string msg;
  24682. EXPECT_FALSE(client.read(msg));
  24683. EXPECT_FALSE(client.is_open());
  24684. }
  24685. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24687. "/ws-echo");
  24688. ASSERT_TRUE(client.connect());
  24689. // 128KB message
  24690. std::string large_data(128 * 1024, 'X');
  24691. ASSERT_TRUE(client.send(large_data));
  24692. std::string msg;
  24693. ASSERT_TRUE(client.read(msg));
  24694. EXPECT_EQ(large_data, msg);
  24695. client.close();
  24696. }
  24697. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24699. "/ws-echo");
  24700. ASSERT_TRUE(client.connect());
  24701. const int num_threads = 4;
  24702. std::vector<std::thread> threads;
  24703. std::atomic<int> send_count{0};
  24704. for (int t = 0; t < num_threads; t++) {
  24705. threads.emplace_back([&client, &send_count, t]() {
  24706. for (int i = 0; i < 5; i++) {
  24707. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24708. if (client.send(text)) { send_count++; }
  24709. }
  24710. });
  24711. }
  24712. for (auto &th : threads) {
  24713. th.join();
  24714. }
  24715. int received = 0;
  24716. std::string msg;
  24717. while (received < send_count.load()) {
  24718. if (!client.read(msg)) { break; }
  24719. received++;
  24720. }
  24721. EXPECT_EQ(send_count.load(), received);
  24722. client.close();
  24723. }
  24724. TEST_F(WebSocketIntegrationTest, ReadString) {
  24725. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24726. "/ws-echo-string");
  24727. ASSERT_TRUE(client.connect());
  24728. ASSERT_TRUE(client.send("hello"));
  24729. std::string msg;
  24730. ASSERT_TRUE(client.read(msg));
  24731. EXPECT_EQ("echo: hello", msg);
  24732. ASSERT_TRUE(client.send("world"));
  24733. ASSERT_TRUE(client.read(msg));
  24734. EXPECT_EQ("echo: world", msg);
  24735. client.close();
  24736. }
  24737. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24738. Headers headers = {{"X-Test-Header", "test-value"}};
  24739. ws::WebSocketClient client(
  24740. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24741. ASSERT_TRUE(client.connect());
  24742. std::string msg;
  24743. ASSERT_TRUE(client.read(msg));
  24744. EXPECT_EQ("path:/ws-request-info", msg);
  24745. ASSERT_TRUE(client.read(msg));
  24746. EXPECT_EQ("header:test-value", msg);
  24747. client.close();
  24748. }
  24749. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24751. "/ws-echo");
  24752. client.set_read_timeout(1, 0); // 1 second
  24753. ASSERT_TRUE(client.connect());
  24754. // Don't send anything — server echo handler waits for a message, so read()
  24755. // should time out. The connection survives it: nothing was consumed.
  24756. std::string msg;
  24757. EXPECT_EQ(client.read(msg), ws::Timeout);
  24758. EXPECT_TRUE(client.is_open());
  24759. // And it is still usable afterwards.
  24760. EXPECT_TRUE(client.send("after timeout"));
  24761. EXPECT_EQ(client.read(msg), ws::Text);
  24762. EXPECT_EQ(msg, "after timeout");
  24763. }
  24764. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24765. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24766. "/ws-echo");
  24767. client.set_read_timeout(1, 0);
  24768. ASSERT_TRUE(client.connect());
  24769. ASSERT_TRUE(client.send("first"));
  24770. std::string msg;
  24771. ASSERT_EQ(client.read(msg), ws::Text);
  24772. ASSERT_EQ(msg, "first");
  24773. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24774. // not be used with a read timeout: it would reprocess the previous message.
  24775. EXPECT_EQ(client.read(msg), ws::Timeout);
  24776. EXPECT_EQ(msg, "first");
  24777. }
  24778. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24780. "/ws-echo");
  24781. ASSERT_TRUE(client.connect());
  24782. // Setting it once the connection is open reaches the live stream, not just
  24783. // the seed for the next connect().
  24784. client.set_read_timeout(1, 0);
  24785. std::string msg;
  24786. EXPECT_EQ(client.read(msg), ws::Timeout);
  24787. EXPECT_TRUE(client.is_open());
  24788. }
  24789. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24791. "/ws-echo");
  24792. client.set_read_timeout(5, 0);
  24793. ASSERT_TRUE(client.connect());
  24794. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24795. // The server should reject it and close the connection.
  24796. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24797. client.send(oversized);
  24798. // The server's read() should have failed due to payload limit,
  24799. // so our read() should return false (connection closed).
  24800. std::string msg;
  24801. EXPECT_FALSE(client.read(msg));
  24802. }
  24803. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24804. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24805. "/ws-echo");
  24806. client.set_read_timeout(10, 0);
  24807. ASSERT_TRUE(client.connect());
  24808. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24809. // This should succeed.
  24810. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24811. ASSERT_TRUE(client.send(at_limit));
  24812. std::string msg;
  24813. ASSERT_TRUE(client.read(msg));
  24814. EXPECT_EQ(at_limit.size(), msg.size());
  24815. client.close();
  24816. }
  24817. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24818. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24819. "/nonexistent");
  24820. auto res = client.connect();
  24821. EXPECT_FALSE(res);
  24822. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24823. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24824. EXPECT_FALSE(client.is_open());
  24825. }
  24826. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24828. "/ws-echo");
  24829. ASSERT_TRUE(client.connect());
  24830. ASSERT_TRUE(client.send(""));
  24831. std::string msg;
  24832. EXPECT_EQ(ws::Text, client.read(msg));
  24833. EXPECT_EQ("", msg);
  24834. client.close();
  24835. }
  24836. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24837. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24838. "/ws-echo");
  24839. // First connection
  24840. ASSERT_TRUE(client.connect());
  24841. ASSERT_TRUE(client.send("first"));
  24842. std::string msg;
  24843. ASSERT_TRUE(client.read(msg));
  24844. EXPECT_EQ("first", msg);
  24845. client.close();
  24846. EXPECT_FALSE(client.is_open());
  24847. // Reconnect using the same client object
  24848. ASSERT_TRUE(client.connect());
  24849. ASSERT_TRUE(client.is_open());
  24850. ASSERT_TRUE(client.send("second"));
  24851. ASSERT_TRUE(client.read(msg));
  24852. EXPECT_EQ("second", msg);
  24853. client.close();
  24854. }
  24855. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24857. "/ws-close-status");
  24858. ASSERT_TRUE(client.connect());
  24859. // Trigger the server to close with GoingAway status
  24860. ASSERT_TRUE(client.send("trigger"));
  24861. // read() should return false after receiving the close frame
  24862. std::string msg;
  24863. EXPECT_FALSE(client.read(msg));
  24864. EXPECT_FALSE(client.is_open());
  24865. }
  24866. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24868. "/ws-echo");
  24869. ASSERT_TRUE(client.connect());
  24870. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24871. EXPECT_FALSE(client.is_open());
  24872. }
  24873. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24874. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24875. ws::WebSocketClient client(
  24876. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24877. ASSERT_TRUE(client.connect());
  24878. // Server should have selected graphql-ws
  24879. EXPECT_EQ("graphql-ws", client.subprotocol());
  24880. client.close();
  24881. }
  24882. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24883. Headers headers;
  24884. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24885. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24886. ws::WebSocketClient client(
  24887. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24888. ASSERT_TRUE(client.connect());
  24889. // The offer on the second field line counts too, so graphql-ws is selected
  24890. EXPECT_EQ("graphql-ws", client.subprotocol());
  24891. client.close();
  24892. }
  24893. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24894. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24895. ws::WebSocketClient client(
  24896. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24897. ASSERT_TRUE(client.connect());
  24898. // Server should not have selected any subprotocol
  24899. EXPECT_TRUE(client.subprotocol().empty());
  24900. client.close();
  24901. }
  24902. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24903. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24905. "/ws-subprotocol-unoffered",
  24906. headers);
  24907. ASSERT_TRUE(client.connect());
  24908. EXPECT_TRUE(client.subprotocol().empty());
  24909. client.close();
  24910. }
  24911. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24912. // Connect without requesting any subprotocol
  24913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24914. "/ws-subprotocol");
  24915. ASSERT_TRUE(client.connect());
  24916. EXPECT_TRUE(client.subprotocol().empty());
  24917. client.close();
  24918. }
  24919. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24921. "/ws-echo");
  24922. client.set_tcp_nodelay(true);
  24923. client.set_connection_timeout(3, 0);
  24924. bool socket_options_called = false;
  24925. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24926. ASSERT_TRUE(client.connect());
  24927. ASSERT_TRUE(client.is_open());
  24928. EXPECT_TRUE(socket_options_called);
  24929. ASSERT_TRUE(client.send("hello"));
  24930. std::string msg;
  24931. auto result = client.read(msg);
  24932. EXPECT_EQ(result, ws::ReadResult::Text);
  24933. EXPECT_EQ(msg, "hello");
  24934. client.close();
  24935. }
  24936. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24938. "/ws-echo");
  24939. client.set_connection_timeout(std::chrono::seconds(3));
  24940. client.set_write_timeout(std::chrono::seconds(3));
  24941. // A sub-second remainder exercises the seconds/microseconds split.
  24942. client.set_read_timeout(std::chrono::milliseconds(1500));
  24943. ASSERT_TRUE(client.connect());
  24944. auto start = std::chrono::steady_clock::now();
  24945. std::string msg;
  24946. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24947. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24948. std::chrono::steady_clock::now() - start)
  24949. .count();
  24950. // Above 1s so that dropping the microseconds half of the split fails here.
  24951. // Ignoring the setter altogether would not reach this line at all: a client
  24952. // waits forever by default.
  24953. EXPECT_GE(elapsed, 1400);
  24954. EXPECT_LT(elapsed, 30000);
  24955. }
  24956. #ifndef _WIN32
  24957. // A send() that times out after part of the data went out returns the count
  24958. // written so far. Every byte of the frame must still be sent, or the peer reads
  24959. // the next frame's header and payload as the rest of this one.
  24960. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24961. signal(SIGPIPE, SIG_IGN);
  24962. const std::string large(4 * 1024 * 1024, 'A');
  24963. std::atomic<bool> large_sent{false};
  24964. std::atomic<bool> small_sent{false};
  24965. Server svr;
  24966. svr.set_write_timeout(0, 500000);
  24967. svr.set_socket_options([](socket_t sock) {
  24968. int size = 8192;
  24969. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24970. reinterpret_cast<const char *>(&size), sizeof(size));
  24971. });
  24972. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24973. large_sent = ws.send(large.data(), large.size());
  24974. small_sent = ws.send("after");
  24975. std::string msg;
  24976. while (ws.read(msg)) {}
  24977. });
  24978. auto port = svr.bind_to_any_port(HOST);
  24979. std::thread t([&]() { svr.listen_after_bind(); });
  24980. auto se = detail::scope_exit([&] {
  24981. svr.stop();
  24982. t.join();
  24983. });
  24984. svr.wait_until_ready();
  24985. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24986. std::to_string(port) + "/ws");
  24987. client.set_read_timeout(5);
  24988. client.set_socket_options([](socket_t sock) {
  24989. int size = 8192;
  24990. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24991. reinterpret_cast<const char *>(&size), sizeof(size));
  24992. });
  24993. ASSERT_TRUE(client.connect());
  24994. // Outlast the server's write timeout, then drain.
  24995. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24996. std::string msg;
  24997. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24998. EXPECT_TRUE(msg == large);
  24999. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25000. EXPECT_EQ("after", msg);
  25001. EXPECT_TRUE(large_sent);
  25002. EXPECT_TRUE(small_sent);
  25003. client.close();
  25004. }
  25005. // A send() that fails partway leaves a frame on the wire whose header announces
  25006. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25007. // as the rest of it and a later payload's bytes as a frame of their own.
  25008. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25009. signal(SIGPIPE, SIG_IGN);
  25010. const std::string large(4 * 1024 * 1024, 'A');
  25011. std::atomic<bool> large_sent{true};
  25012. std::atomic<bool> open_after_failure{true};
  25013. std::atomic<bool> handler_done{false};
  25014. Server svr;
  25015. svr.set_write_timeout(0, 200000);
  25016. svr.set_socket_options([](socket_t sock) {
  25017. int size = 8192;
  25018. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25019. reinterpret_cast<const char *>(&size), sizeof(size));
  25020. });
  25021. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25022. large_sent = ws.send(large.data(), large.size());
  25023. open_after_failure = ws.is_open();
  25024. handler_done = true;
  25025. });
  25026. auto port = svr.bind_to_any_port(HOST);
  25027. std::thread t([&]() { svr.listen_after_bind(); });
  25028. auto se = detail::scope_exit([&] {
  25029. svr.stop();
  25030. t.join();
  25031. });
  25032. svr.wait_until_ready();
  25033. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25034. std::to_string(port) + "/ws");
  25035. client.set_socket_options([](socket_t sock) {
  25036. int size = 8192;
  25037. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25038. reinterpret_cast<const char *>(&size), sizeof(size));
  25039. });
  25040. ASSERT_TRUE(client.connect());
  25041. // Read nothing, so the server's write times out partway through the frame.
  25042. for (int i = 0; i < 100 && !handler_done; i++) {
  25043. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25044. }
  25045. ASSERT_TRUE(handler_done);
  25046. ASSERT_FALSE(large_sent);
  25047. EXPECT_FALSE(open_after_failure);
  25048. client.close();
  25049. }
  25050. #endif
  25051. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25052. Server svr;
  25053. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25054. if (!req.has_header("Authorization")) {
  25055. res.status = StatusCode::Unauthorized_401;
  25056. res.set_content("Unauthorized", "text/plain");
  25057. return Server::HandlerResponse::Handled;
  25058. }
  25059. return Server::HandlerResponse::Unhandled;
  25060. });
  25061. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25062. std::string msg;
  25063. while (ws.read(msg)) {
  25064. ws.send(msg);
  25065. }
  25066. });
  25067. auto port = svr.bind_to_any_port("localhost");
  25068. std::thread t([&]() { svr.listen_after_bind(); });
  25069. svr.wait_until_ready();
  25070. // Without Authorization header - should be rejected before upgrade
  25071. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25072. EXPECT_FALSE(client1.connect());
  25073. // The rejection is framed like any other HTTP response
  25074. {
  25075. Client cli("localhost", port);
  25076. Headers headers = {{"Upgrade", "websocket"},
  25077. {"Connection", "Upgrade"},
  25078. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25079. {"Sec-WebSocket-Version", "13"}};
  25080. auto res = cli.Get("/ws", headers);
  25081. ASSERT_TRUE(res);
  25082. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25083. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25084. EXPECT_EQ("Unauthorized", res->body);
  25085. }
  25086. // With Authorization header - should succeed
  25087. Headers headers = {{"Authorization", "Bearer token123"}};
  25088. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25089. headers);
  25090. ASSERT_TRUE(client2.connect());
  25091. ASSERT_TRUE(client2.send("hello"));
  25092. std::string msg;
  25093. ASSERT_TRUE(client2.read(msg));
  25094. EXPECT_EQ("hello", msg);
  25095. client2.close();
  25096. svr.stop();
  25097. t.join();
  25098. }
  25099. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25100. Server svr;
  25101. std::atomic<int> pre_routing_calls{0};
  25102. std::atomic<int> pre_request_calls{0};
  25103. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25104. pre_routing_calls++;
  25105. if (req.path == "/handled") {
  25106. res.set_content("handled", "text/plain");
  25107. return Server::HandlerResponse::Handled;
  25108. }
  25109. return Server::HandlerResponse::Unhandled;
  25110. });
  25111. svr.set_pre_request_handler([&](const Request &, Response &) {
  25112. pre_request_calls++;
  25113. return Server::HandlerResponse::Unhandled;
  25114. });
  25115. svr.Get("/http", [](const Request &, Response &res) {
  25116. res.set_content("http", "text/plain");
  25117. });
  25118. svr.WebSocket("/ws",
  25119. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25120. auto port = svr.bind_to_any_port("localhost");
  25121. std::thread t([&]() { svr.listen_after_bind(); });
  25122. auto se = detail::scope_exit([&] {
  25123. svr.stop();
  25124. t.join();
  25125. });
  25126. svr.wait_until_ready();
  25127. Headers upgrade = {{"Upgrade", "websocket"},
  25128. {"Connection", "Upgrade"},
  25129. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25130. {"Sec-WebSocket-Version", "13"}};
  25131. auto get = [&](const char *path) {
  25132. pre_routing_calls = 0;
  25133. return Client("localhost", port).Get(path, upgrade);
  25134. };
  25135. // No WebSocket route, but an HTTP one
  25136. auto res = get("/http");
  25137. ASSERT_TRUE(res);
  25138. EXPECT_EQ(StatusCode::OK_200, res->status);
  25139. EXPECT_EQ("http", res->body);
  25140. EXPECT_EQ(1, pre_routing_calls);
  25141. EXPECT_EQ(1, pre_request_calls);
  25142. // No route at all
  25143. res = get("/none");
  25144. ASSERT_TRUE(res);
  25145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25146. EXPECT_EQ(1, pre_routing_calls);
  25147. // Answered by the pre-routing handler
  25148. res = get("/handled");
  25149. ASSERT_TRUE(res);
  25150. EXPECT_EQ(StatusCode::OK_200, res->status);
  25151. EXPECT_EQ("handled", res->body);
  25152. EXPECT_EQ(1, pre_routing_calls);
  25153. // A WebSocket route
  25154. pre_routing_calls = 0;
  25155. pre_request_calls = 0;
  25156. {
  25157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25158. "/ws");
  25159. ASSERT_TRUE(client.connect());
  25160. std::string msg;
  25161. ASSERT_TRUE(client.read(msg));
  25162. EXPECT_EQ("ws", msg);
  25163. client.close();
  25164. }
  25165. EXPECT_EQ(1, pre_routing_calls);
  25166. EXPECT_EQ(1, pre_request_calls);
  25167. }
  25168. // An upgrade request answered by a hook leaves its body unread, so that body
  25169. // must not be served as the next request on the connection.
  25170. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25171. Server svr;
  25172. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25173. if (req.path == "/pre-routing") {
  25174. res.set_content("pre-routing", "text/plain");
  25175. return Server::HandlerResponse::Handled;
  25176. }
  25177. return Server::HandlerResponse::Unhandled;
  25178. });
  25179. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25180. if (req.matched_route == "/pre-request") {
  25181. res.set_content("pre-request", "text/plain");
  25182. return Server::HandlerResponse::Handled;
  25183. }
  25184. return Server::HandlerResponse::Unhandled;
  25185. });
  25186. svr.Get("/smuggled", [](const Request &, Response &res) {
  25187. res.set_content("smuggled", "text/plain");
  25188. });
  25189. svr.WebSocket("/pre-request",
  25190. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25191. auto port = svr.bind_to_any_port(HOST);
  25192. std::thread t([&]() { svr.listen_after_bind(); });
  25193. auto se = detail::scope_exit([&] {
  25194. svr.stop();
  25195. t.join();
  25196. });
  25197. svr.wait_until_ready();
  25198. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25199. for (auto path : {"/pre-routing", "/pre-request"}) {
  25200. std::string req = std::string("GET ") + path +
  25201. " HTTP/1.1\r\n"
  25202. "Host: localhost\r\n"
  25203. "Upgrade: websocket\r\n"
  25204. "Connection: Upgrade\r\n"
  25205. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25206. "Sec-WebSocket-Version: 13\r\n"
  25207. "Content-Length: " +
  25208. std::to_string(body.size()) + "\r\n\r\n" + body;
  25209. std::string res;
  25210. ASSERT_TRUE(send_request(5, req, &res, port));
  25211. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25212. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25213. // Only one response, and the body was not served as a request
  25214. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25215. }
  25216. }
  25217. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25218. Server svr;
  25219. std::atomic<int> pre_request_calls{0};
  25220. std::atomic<bool> route_matched{false};
  25221. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25222. pre_request_calls++;
  25223. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25224. if (req.get_header_value("Authorization") != "Bearer token123") {
  25225. res.status = StatusCode::Unauthorized_401;
  25226. res.set_content("Unauthorized", "text/plain");
  25227. return Server::HandlerResponse::Handled;
  25228. }
  25229. return Server::HandlerResponse::Unhandled;
  25230. });
  25231. std::atomic<bool> handler_called{false};
  25232. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25233. handler_called = true;
  25234. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25235. });
  25236. auto port = svr.bind_to_any_port("localhost");
  25237. std::thread t([&]() { svr.listen_after_bind(); });
  25238. svr.wait_until_ready();
  25239. // Without Authorization header - should be rejected before upgrade
  25240. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25241. "/ws/1");
  25242. EXPECT_FALSE(client1.connect());
  25243. EXPECT_FALSE(handler_called);
  25244. EXPECT_EQ(1, pre_request_calls);
  25245. EXPECT_TRUE(route_matched);
  25246. // The rejection is an ordinary HTTP response, not a protocol switch
  25247. {
  25248. Client cli("localhost", port);
  25249. Headers headers = {{"Upgrade", "websocket"},
  25250. {"Connection", "Upgrade"},
  25251. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25252. {"Sec-WebSocket-Version", "13"}};
  25253. auto res = cli.Get("/ws/1", headers);
  25254. ASSERT_TRUE(res);
  25255. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25256. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25257. EXPECT_EQ("Unauthorized", res->body);
  25258. }
  25259. EXPECT_FALSE(handler_called);
  25260. // With Authorization header - should succeed
  25261. Headers headers = {{"Authorization", "Bearer token123"}};
  25262. ws::WebSocketClient client2(
  25263. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25264. ASSERT_TRUE(client2.connect());
  25265. std::string msg;
  25266. ASSERT_TRUE(client2.read(msg));
  25267. EXPECT_EQ("/ws/:id 2", msg);
  25268. EXPECT_TRUE(handler_called);
  25269. client2.close();
  25270. svr.stop();
  25271. t.join();
  25272. }
  25273. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25274. static Headers websocket_upgrade_headers() {
  25275. return {{"Upgrade", "websocket"},
  25276. {"Connection", "Upgrade"},
  25277. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25278. {"Sec-WebSocket-Version", "13"},
  25279. {"Sec-WebSocket-Protocol", "chat"}};
  25280. }
  25281. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25282. Server svr;
  25283. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25284. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25285. return Server::HandlerResponse::Unhandled;
  25286. });
  25287. svr.set_pre_request_handler([](const Request &req, Response &) {
  25288. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25289. return Server::HandlerResponse::Unhandled;
  25290. });
  25291. svr.set_exception_handler(
  25292. [](const Request &, Response &res, std::exception_ptr ep) {
  25293. try {
  25294. std::rethrow_exception(ep);
  25295. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25296. });
  25297. auto handler = [](const Request &, ws::WebSocket &) {};
  25298. svr.WebSocket("/pre-routing", handler);
  25299. svr.WebSocket("/pre-request", handler);
  25300. svr.WebSocket("/sub-protocol", handler,
  25301. [](const std::vector<std::string> &) -> std::string {
  25302. throw std::runtime_error("/sub-protocol");
  25303. });
  25304. auto port = svr.bind_to_any_port(HOST);
  25305. ASSERT_GT(port, 0);
  25306. thread t = thread([&] { svr.listen_after_bind(); });
  25307. auto se = detail::scope_exit([&] {
  25308. svr.stop();
  25309. t.join();
  25310. ASSERT_FALSE(svr.is_running());
  25311. });
  25312. svr.wait_until_ready();
  25313. Client cli(HOST, port);
  25314. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25315. auto res = cli.Get(path, websocket_upgrade_headers());
  25316. if (!res) {
  25317. ADD_FAILURE() << path << ": " << to_string(res.error());
  25318. continue;
  25319. }
  25320. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25321. EXPECT_EQ(path, res->body);
  25322. }
  25323. }
  25324. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25325. Server svr;
  25326. svr.set_pre_routing_handler(
  25327. [](const Request &, Response &) -> Server::HandlerResponse {
  25328. throw std::runtime_error("pre-routing");
  25329. });
  25330. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25331. auto port = svr.bind_to_any_port(HOST);
  25332. ASSERT_GT(port, 0);
  25333. thread t = thread([&] { svr.listen_after_bind(); });
  25334. auto se = detail::scope_exit([&] {
  25335. svr.stop();
  25336. t.join();
  25337. ASSERT_FALSE(svr.is_running());
  25338. });
  25339. svr.wait_until_ready();
  25340. Client cli(HOST, port);
  25341. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25342. ASSERT_TRUE(res) << to_string(res.error());
  25343. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25344. }
  25345. #endif
  25346. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25347. Server svr;
  25348. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25349. // A read timeout is how a handler gets control back. Without it, a handler
  25350. // parked in read() can never write on the connection it is reading.
  25351. ws.set_read_timeout(std::chrono::milliseconds(100));
  25352. std::string msg;
  25353. while (ws.is_open()) {
  25354. auto r = ws.read(msg);
  25355. if (r == httplib::ws::Timeout) {
  25356. ws.send("tick");
  25357. continue;
  25358. }
  25359. if (r == httplib::ws::Fail) { break; }
  25360. ws.send(msg);
  25361. }
  25362. });
  25363. auto port = svr.bind_to_any_port("localhost");
  25364. std::thread t([&]() { svr.listen_after_bind(); });
  25365. svr.wait_until_ready();
  25366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25367. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25368. ASSERT_TRUE(client.connect());
  25369. // The client sends nothing, so anything it receives came out of the
  25370. // handler's timeout path.
  25371. std::string msg;
  25372. ASSERT_EQ(client.read(msg), ws::Text);
  25373. EXPECT_EQ("tick", msg);
  25374. client.close();
  25375. svr.stop();
  25376. t.join();
  25377. }
  25378. // Stream::read may return fewer bytes than asked for. This is that contract at
  25379. // its worst -- one byte per call -- which is what a frame header straddling a
  25380. // read buffer's boundary looks like to the frame parser.
  25381. class WsByteAtATimeStream : public Stream {
  25382. public:
  25383. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25384. bool is_readable() const override { return true; }
  25385. bool wait_readable() const override { return true; }
  25386. bool wait_writable() const override { return true; }
  25387. ssize_t read(char *ptr, size_t size) override {
  25388. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25389. *ptr = data_[pos_++];
  25390. return 1;
  25391. }
  25392. ssize_t write(const char *, size_t size) override {
  25393. return static_cast<ssize_t>(size);
  25394. }
  25395. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25396. ip = "127.0.0.1";
  25397. port = 0;
  25398. }
  25399. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25400. ip = "127.0.0.1";
  25401. port = 0;
  25402. }
  25403. socket_t socket() const override { return INVALID_SOCKET; }
  25404. time_t duration() const override { return 0; }
  25405. private:
  25406. std::string data_;
  25407. size_t pos_ = 0;
  25408. };
  25409. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25410. // The payload uses the 16-bit extended length, so the header, the length
  25411. // and the mask key are all multi-byte fields here. Each used to be read
  25412. // with a single read() call, which fails as soon as one is split. The
  25413. // payload is also a little over one read chunk, so it is read in two.
  25414. std::string body;
  25415. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25416. body += static_cast<char>(i % 251);
  25417. }
  25418. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25419. std::string frame;
  25420. frame += static_cast<char>(0x81); // FIN + Text
  25421. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25422. frame += static_cast<char>(body.size() >> 8);
  25423. frame += static_cast<char>(body.size() & 0xff);
  25424. for (size_t i = 0; i < 4; i++) {
  25425. frame += static_cast<char>(mask[i]);
  25426. }
  25427. for (size_t i = 0; i < body.size(); i++) {
  25428. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25429. }
  25430. WsByteAtATimeStream strm(frame);
  25431. ws::Opcode opcode;
  25432. std::string payload;
  25433. bool fin = false;
  25434. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25435. /*expect_masked=*/true, body.size()),
  25436. ws::impl::FrameRead::Ok);
  25437. EXPECT_TRUE(fin);
  25438. EXPECT_EQ(opcode, ws::Opcode::Text);
  25439. EXPECT_EQ(payload, body);
  25440. }
  25441. // Keeps what is written, counting the writes, and reads it back.
  25442. class WsWriteCountingStream : public Stream {
  25443. public:
  25444. bool is_readable() const override { return true; }
  25445. bool wait_readable() const override { return true; }
  25446. bool wait_writable() const override { return true; }
  25447. ssize_t read(char *ptr, size_t size) override {
  25448. auto n = (std::min)(size, data_.size() - pos_);
  25449. if (n == 0) { return 0; }
  25450. memcpy(ptr, data_.data() + pos_, n);
  25451. pos_ += n;
  25452. return static_cast<ssize_t>(n);
  25453. }
  25454. ssize_t write(const char *ptr, size_t size) override {
  25455. writes++;
  25456. data_.append(ptr, size);
  25457. return static_cast<ssize_t>(size);
  25458. }
  25459. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25460. ip = "127.0.0.1";
  25461. port = 0;
  25462. }
  25463. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25464. ip = "127.0.0.1";
  25465. port = 0;
  25466. }
  25467. socket_t socket() const override { return INVALID_SOCKET; }
  25468. time_t duration() const override { return 0; }
  25469. int writes = 0;
  25470. private:
  25471. std::string data_;
  25472. size_t pos_ = 0;
  25473. };
  25474. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25475. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25476. // masked and not, reads back as written; a payload over one chunk follows
  25477. // its first in more writes.
  25478. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25479. for (auto mask : {false, true}) {
  25480. std::string body(len, '\0');
  25481. for (size_t i = 0; i < len; i++) {
  25482. body[i] = static_cast<char>(i % 251);
  25483. }
  25484. WsWriteCountingStream strm;
  25485. ASSERT_TRUE(detail::write_websocket_frame(
  25486. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25487. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25488. ws::Opcode opcode;
  25489. std::string payload;
  25490. bool fin = false;
  25491. ASSERT_EQ(
  25492. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25493. ws::impl::FrameRead::Ok)
  25494. << len << " " << mask;
  25495. EXPECT_TRUE(fin);
  25496. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25497. EXPECT_EQ(body, payload) << len << " " << mask;
  25498. }
  25499. }
  25500. }
  25501. // Hands out its pieces one read at a time, timing out between each two.
  25502. class WsTimeoutBetweenPiecesStream : public Stream {
  25503. public:
  25504. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25505. : pieces_(std::move(pieces)) {}
  25506. bool is_readable() const override { return true; }
  25507. bool wait_readable() const override { return true; }
  25508. bool wait_writable() const override { return true; }
  25509. ssize_t read(char *ptr, size_t size) override {
  25510. if (time_out_) {
  25511. time_out_ = false;
  25512. error_ = Error::Timeout;
  25513. return -1;
  25514. }
  25515. if (i_ >= pieces_.size()) {
  25516. error_ = Error::ConnectionClosed;
  25517. return 0;
  25518. }
  25519. auto &piece = pieces_[i_];
  25520. auto n = (std::min)(size, piece.size() - at_);
  25521. memcpy(ptr, piece.data() + at_, n);
  25522. at_ += n;
  25523. if (at_ == piece.size()) {
  25524. i_++;
  25525. at_ = 0;
  25526. time_out_ = true;
  25527. }
  25528. return static_cast<ssize_t>(n);
  25529. }
  25530. ssize_t write(const char *, size_t size) override {
  25531. return static_cast<ssize_t>(size);
  25532. }
  25533. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25534. ip = "127.0.0.1";
  25535. port = 0;
  25536. }
  25537. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25538. ip = "127.0.0.1";
  25539. port = 0;
  25540. }
  25541. socket_t socket() const override { return INVALID_SOCKET; }
  25542. time_t duration() const override { return 0; }
  25543. private:
  25544. std::vector<std::string> pieces_;
  25545. size_t i_ = 0;
  25546. size_t at_ = 0;
  25547. bool time_out_ = false;
  25548. };
  25549. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25550. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25551. std::string frame = "\x81\x85";
  25552. frame.append(4, '\0');
  25553. frame += "Hello";
  25554. // The header's first byte, then its second with half the mask key, then
  25555. // the rest
  25556. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25557. frame.substr(4)};
  25558. WsTimeoutBetweenPiecesStream strm(pieces);
  25559. ws::impl::FrameReader reader;
  25560. ws::Opcode opcode;
  25561. std::string payload;
  25562. bool fin = false;
  25563. for (int i = 0; i < 2; i++) {
  25564. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25565. reader.read(strm, opcode, payload, fin, true, 0));
  25566. EXPECT_TRUE(reader.begun());
  25567. }
  25568. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25569. reader.read(strm, opcode, payload, fin, true, 0));
  25570. EXPECT_FALSE(reader.begun());
  25571. EXPECT_TRUE(fin);
  25572. EXPECT_EQ(ws::Opcode::Text, opcode);
  25573. EXPECT_EQ("Hello", payload);
  25574. // Read in one go, the frame cannot be gone on with after a timeout
  25575. WsTimeoutBetweenPiecesStream again(pieces);
  25576. EXPECT_EQ(
  25577. ws::impl::FrameRead::Fail,
  25578. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25579. }
  25580. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25581. std::string body(2000, 'x');
  25582. std::string frame;
  25583. frame += static_cast<char>(0x82); // FIN + Binary
  25584. frame += static_cast<char>(126); // 16-bit length follows
  25585. frame += static_cast<char>(body.size() >> 8);
  25586. frame += static_cast<char>(body.size() & 0xff);
  25587. frame += body;
  25588. detail::BufferStream strm;
  25589. strm.write(frame.data(), frame.size());
  25590. ws::Opcode opcode;
  25591. std::string payload;
  25592. bool fin;
  25593. EXPECT_EQ(
  25594. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25595. ws::impl::FrameRead::Ok);
  25596. EXPECT_EQ(body, payload);
  25597. }
  25598. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25599. // The header announces the largest payload allowed, and only 3 bytes of it
  25600. // ever arrive.
  25601. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25602. std::string frame;
  25603. frame += static_cast<char>(0x82); // FIN + Binary
  25604. frame += static_cast<char>(127); // 64-bit length follows
  25605. for (int shift = 56; shift >= 0; shift -= 8) {
  25606. frame += static_cast<char>((len >> shift) & 0xff);
  25607. }
  25608. frame += "abc";
  25609. detail::BufferStream strm;
  25610. strm.write(frame.data(), frame.size());
  25611. ws::Opcode opcode;
  25612. std::string payload;
  25613. bool fin;
  25614. EXPECT_EQ(
  25615. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25616. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25617. ws::impl::FrameRead::Fail);
  25618. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25619. }
  25620. TEST(WebSocketTest, QueryStringInHandshake) {
  25621. Server svr;
  25622. std::mutex mtx;
  25623. std::string received_target;
  25624. std::string received_token;
  25625. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25626. {
  25627. std::lock_guard<std::mutex> lock(mtx);
  25628. received_target = req.target;
  25629. if (req.has_param("token")) {
  25630. received_token = req.get_param_value("token");
  25631. }
  25632. }
  25633. std::string msg;
  25634. while (ws.read(msg)) {
  25635. ws.send(msg);
  25636. }
  25637. });
  25638. auto port = svr.bind_to_any_port("localhost");
  25639. std::thread t([&]() { svr.listen_after_bind(); });
  25640. svr.wait_until_ready();
  25641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25642. "/ws?token=ABC&session=123");
  25643. ASSERT_TRUE(client.connect());
  25644. // Round-trip ensures the handler has run and captured the request.
  25645. ASSERT_TRUE(client.send("hello"));
  25646. std::string msg;
  25647. ASSERT_TRUE(client.read(msg));
  25648. EXPECT_EQ("hello", msg);
  25649. client.close();
  25650. {
  25651. std::lock_guard<std::mutex> lock(mtx);
  25652. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25653. EXPECT_EQ("ABC", received_token);
  25654. }
  25655. svr.stop();
  25656. t.join();
  25657. }
  25658. // Run a handshake against a throwaway server and hand the request the server
  25659. // received back to the caller, so tests can assert on the headers the client
  25660. // actually put on the wire.
  25661. static void capture_websocket_handshake_request(
  25662. const Headers &client_headers,
  25663. std::function<void(const Request &, int port)> verify) {
  25664. Server svr;
  25665. std::mutex mtx;
  25666. Request received;
  25667. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25668. {
  25669. std::lock_guard<std::mutex> lock(mtx);
  25670. received = req;
  25671. }
  25672. std::string msg;
  25673. while (ws.read(msg)) {
  25674. ws.send(msg);
  25675. }
  25676. });
  25677. auto port = svr.bind_to_any_port("localhost");
  25678. std::thread t([&]() { svr.listen_after_bind(); });
  25679. auto se = detail::scope_exit([&] {
  25680. svr.stop();
  25681. t.join();
  25682. });
  25683. svr.wait_until_ready();
  25684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25685. client_headers);
  25686. ASSERT_TRUE(client.connect());
  25687. ASSERT_TRUE(client.send("hello"));
  25688. std::string msg;
  25689. ASSERT_TRUE(client.read(msg));
  25690. client.close();
  25691. {
  25692. std::lock_guard<std::mutex> lock(mtx);
  25693. verify(received, port);
  25694. }
  25695. }
  25696. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25697. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25698. // Non-default port must be present in the Host header. Default ports
  25699. // (80/443) are omitted; that logic is covered by
  25700. // MakeHostAndPortStringTest.
  25701. EXPECT_EQ("localhost:" + std::to_string(port),
  25702. req.get_header_value("Host"));
  25703. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25704. req.get_header_value("User-Agent"));
  25705. EXPECT_FALSE(req.has_header("Accept"));
  25706. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25707. EXPECT_FALSE(req.has_header("Content-Length"));
  25708. });
  25709. }
  25710. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25711. capture_websocket_handshake_request(
  25712. {{"Host", "example.com"},
  25713. {"User-Agent", "custom-agent"},
  25714. {"X-Custom", "value"}},
  25715. [](const Request &req, int) {
  25716. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25717. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25718. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25719. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25720. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25721. });
  25722. }
  25723. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25724. capture_websocket_handshake_request(
  25725. {{"Upgrade", "bogus"},
  25726. {"Connection", "close"},
  25727. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25728. {"Sec-WebSocket-Version", "8"}},
  25729. [](const Request &req, int) {
  25730. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25731. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25732. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25733. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25734. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25735. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25736. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25737. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25738. req.get_header_value("Sec-WebSocket-Key"));
  25739. });
  25740. }
  25741. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25742. // A header the client refuses to send must abort the handshake before any
  25743. // part of it reaches the wire; a lone request line would otherwise sit in
  25744. // the peer's buffer as a truncated request.
  25745. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25746. ASSERT_NE(INVALID_SOCKET, srv);
  25747. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25748. sockaddr_in addr{};
  25749. addr.sin_family = AF_INET;
  25750. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25751. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25752. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25753. ASSERT_EQ(0, ::listen(srv, 1));
  25754. sockaddr_in bound{};
  25755. socklen_t bound_len = sizeof(bound);
  25756. ASSERT_EQ(
  25757. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25758. auto port = ntohs(bound.sin_port);
  25759. ssize_t received = -1;
  25760. std::thread t([&] {
  25761. // Bound every blocking call so a regression fails the test with a bad
  25762. // value instead of hanging the suite.
  25763. fd_set rfds;
  25764. FD_ZERO(&rfds);
  25765. FD_SET(srv, &rfds);
  25766. timeval tv{5, 0};
  25767. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25768. 0) {
  25769. return;
  25770. }
  25771. sockaddr_in cli_addr{};
  25772. socklen_t cli_len = sizeof(cli_addr);
  25773. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25774. if (cli == INVALID_SOCKET) { return; }
  25775. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25776. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25777. char buf[4096];
  25778. received = ::recv(cli, buf, sizeof(buf), 0);
  25779. });
  25780. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25781. // connect() has already shut the socket down by the time it returns false,
  25782. // so the peer sees EOF without waiting for the client to be destroyed.
  25783. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25784. {{"X-Bad", "a\r\nInjected: 1"}});
  25785. EXPECT_FALSE(client.connect());
  25786. t.join();
  25787. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25788. EXPECT_EQ(0, received);
  25789. }
  25790. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25791. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25792. // contains "upgrade" as a substring is a different token and must not
  25793. // start a WebSocket handshake.
  25794. auto make_request = [](const std::vector<std::string> &connection_values) {
  25795. Request req;
  25796. req.method = "GET";
  25797. req.headers.emplace("Upgrade", "websocket");
  25798. for (const auto &value : connection_values) {
  25799. req.headers.emplace("Connection", value);
  25800. }
  25801. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25802. req.headers.emplace("Sec-WebSocket-Version", "13");
  25803. return req;
  25804. };
  25805. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25806. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25807. EXPECT_TRUE(
  25808. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25809. EXPECT_TRUE(
  25810. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25811. EXPECT_TRUE(
  25812. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25813. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25814. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25815. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25816. EXPECT_FALSE(
  25817. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25818. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25819. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25820. }
  25821. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25822. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25823. // asks recipients to match each protocol-name case-insensitively, and RFC
  25824. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25825. // client naming websocket alongside another protocol, or on a second field
  25826. // line, is offering websocket; a value that merely contains "websocket" as a
  25827. // substring is a different protocol name and is not.
  25828. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25829. Request req;
  25830. req.method = "GET";
  25831. for (const auto &value : upgrade_values) {
  25832. req.headers.emplace("Upgrade", value);
  25833. }
  25834. req.headers.emplace("Connection", "Upgrade");
  25835. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25836. req.headers.emplace("Sec-WebSocket-Version", "13");
  25837. return req;
  25838. };
  25839. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25840. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25841. EXPECT_TRUE(
  25842. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25843. EXPECT_TRUE(
  25844. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25845. EXPECT_TRUE(
  25846. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25847. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25848. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25849. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25850. EXPECT_FALSE(
  25851. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25852. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25853. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25854. }
  25855. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25856. Server svr;
  25857. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25858. auto port = svr.bind_to_any_port("localhost");
  25859. std::thread t([&]() { svr.listen_after_bind(); });
  25860. auto se = detail::scope_exit([&] {
  25861. svr.stop();
  25862. t.join();
  25863. });
  25864. svr.wait_until_ready();
  25865. Headers headers = {{"Upgrade", "websocket"},
  25866. {"Connection", "notupgrade"},
  25867. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25868. {"Sec-WebSocket-Version", "13"}};
  25869. Client cli("localhost", port);
  25870. auto res = cli.Get("/ws", headers);
  25871. // The route exists only as a WebSocket route, so a request that fails the
  25872. // handshake check falls through to ordinary routing.
  25873. ASSERT_TRUE(res);
  25874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25875. }
  25876. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25877. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25878. // Connection value is the only thing left for the client to reject.
  25879. Server svr;
  25880. svr.Get("/ws", [](const Request &req, Response &res) {
  25881. res.status = StatusCode::SwitchingProtocol_101;
  25882. res.set_header("Upgrade", "websocket");
  25883. res.set_header("Connection", "notupgrade");
  25884. res.set_header("Sec-WebSocket-Accept",
  25885. detail::websocket_accept_key(
  25886. req.get_header_value("Sec-WebSocket-Key")));
  25887. });
  25888. auto port = svr.bind_to_any_port("localhost");
  25889. std::thread t([&]() { svr.listen_after_bind(); });
  25890. auto se = detail::scope_exit([&] {
  25891. svr.stop();
  25892. t.join();
  25893. });
  25894. svr.wait_until_ready();
  25895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25896. auto res = client.connect();
  25897. EXPECT_FALSE(res);
  25898. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25899. EXPECT_FALSE(client.is_open());
  25900. }
  25901. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25902. Server svr;
  25903. svr.Get("/ws", [](const Request &req, Response &res) {
  25904. res.status = StatusCode::SwitchingProtocol_101;
  25905. res.set_header("Upgrade", "websocket");
  25906. res.set_header("Connection", "Upgrade");
  25907. res.set_header("Sec-WebSocket-Accept",
  25908. detail::websocket_accept_key(
  25909. req.get_header_value("Sec-WebSocket-Key")));
  25910. res.set_header("Sec-WebSocket-Protocol", "admin");
  25911. });
  25912. auto port = svr.bind_to_any_port("localhost");
  25913. std::thread t([&]() { svr.listen_after_bind(); });
  25914. auto se = detail::scope_exit([&] {
  25915. svr.stop();
  25916. t.join();
  25917. });
  25918. svr.wait_until_ready();
  25919. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25920. // Server selects a subprotocol the client never offered
  25921. {
  25922. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25923. ws::WebSocketClient client(url, headers);
  25924. auto res = client.connect();
  25925. EXPECT_FALSE(res);
  25926. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25927. EXPECT_FALSE(client.is_open());
  25928. EXPECT_TRUE(client.subprotocol().empty());
  25929. }
  25930. // Client offered none but the server named one anyway
  25931. {
  25932. ws::WebSocketClient client(url);
  25933. auto res = client.connect();
  25934. EXPECT_FALSE(res);
  25935. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25936. EXPECT_FALSE(client.is_open());
  25937. EXPECT_TRUE(client.subprotocol().empty());
  25938. }
  25939. }
  25940. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25941. // The socket path doubles as the URL host, so it must not contain '/'.
  25942. const char *shard = getenv("GTEST_SHARD_INDEX");
  25943. const std::string sock_path =
  25944. shard ? std::string("httplib-ws-") + shard + ".sock"
  25945. : std::string("httplib-ws.sock");
  25946. std::remove(sock_path.c_str());
  25947. Server svr;
  25948. std::mutex mtx;
  25949. std::string received_host;
  25950. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25951. {
  25952. std::lock_guard<std::mutex> lock(mtx);
  25953. received_host = req.get_header_value("Host");
  25954. }
  25955. std::string msg;
  25956. while (ws.read(msg)) {
  25957. ws.send(msg);
  25958. }
  25959. });
  25960. svr.set_address_family(AF_UNIX);
  25961. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25962. auto se = detail::scope_exit([&] {
  25963. svr.stop();
  25964. t.join();
  25965. std::remove(sock_path.c_str());
  25966. });
  25967. svr.wait_until_ready();
  25968. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25969. client.set_address_family(AF_UNIX);
  25970. ASSERT_TRUE(client.connect());
  25971. ASSERT_TRUE(client.send("hello"));
  25972. std::string msg;
  25973. ASSERT_TRUE(client.read(msg));
  25974. client.close();
  25975. {
  25976. std::lock_guard<std::mutex> lock(mtx);
  25977. // There is no host:port for a Unix socket, so the same "localhost"
  25978. // placeholder the HTTP client uses is expected.
  25979. EXPECT_EQ("localhost", received_host);
  25980. }
  25981. }
  25982. // Two threads must never parse WebSocket frames from the same stream.
  25983. // close() used to read the peer's Close reply with its own frame read, so it
  25984. // raced a reader thread that was in the middle of a payload: the payload loop
  25985. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25986. // so bytes taken by close() were replaced with bytes from further along the
  25987. // stream. The message kept its length and silently changed content.
  25988. //
  25989. // The raw peer below sends a frame header plus part of the payload, waits for
  25990. // the handler to call close(), and only then sends the rest. Whichever thread
  25991. // would win the race for those bytes, the message must arrive intact, because
  25992. // close() must not touch the stream while read() owns it.
  25993. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25994. #ifndef _WIN32
  25995. signal(SIGPIPE, SIG_IGN);
  25996. #endif
  25997. const size_t payload_len = 120; // fits the 7-bit length field
  25998. const size_t prefix_len = 8;
  25999. const int attempts = 8;
  26000. std::string expected(payload_len, '\0');
  26001. for (size_t i = 0; i < payload_len; i++) {
  26002. expected[i] = static_cast<char>('a' + i % 26);
  26003. }
  26004. std::atomic<bool> peer_stalled{false};
  26005. std::atomic<bool> handler_done{false};
  26006. std::mutex received_mutex;
  26007. std::vector<std::string> received;
  26008. // Bound every wait, so a regression fails the test instead of hanging the
  26009. // suite.
  26010. auto wait_for = [](const std::atomic<bool> &flag) {
  26011. for (int i = 0; i < 500 && !flag; i++) {
  26012. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26013. }
  26014. };
  26015. Server svr;
  26016. svr.set_websocket_ping_interval(0);
  26017. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26018. std::thread reader([&]() {
  26019. std::string msg;
  26020. while (ws.read(msg)) {
  26021. std::lock_guard<std::mutex> guard(received_mutex);
  26022. received.push_back(msg);
  26023. }
  26024. });
  26025. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26026. // inside a frame when close() runs.
  26027. wait_for(peer_stalled);
  26028. ws.close();
  26029. reader.join();
  26030. handler_done = true;
  26031. });
  26032. auto port = svr.bind_to_any_port("127.0.0.1");
  26033. std::thread t([&]() { svr.listen_after_bind(); });
  26034. auto se = detail::scope_exit([&] {
  26035. svr.stop();
  26036. t.join();
  26037. });
  26038. svr.wait_until_ready();
  26039. auto send_bytes = [](socket_t s, const std::string &data) {
  26040. #ifdef _WIN32
  26041. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26042. #else
  26043. auto n = ::send(s, data.data(), data.size(), 0);
  26044. #endif
  26045. return n == static_cast<decltype(n)>(data.size());
  26046. };
  26047. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26048. // Every length used here fits the 7-bit length field.
  26049. auto masked_header = [](uint8_t first_byte, size_t len) {
  26050. std::string h;
  26051. h += static_cast<char>(first_byte);
  26052. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26053. h.append(4, '\0'); // mask key
  26054. return h;
  26055. };
  26056. for (int attempt = 0; attempt < attempts; attempt++) {
  26057. peer_stalled = false;
  26058. handler_done = false;
  26059. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26060. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26061. auto se_sock = detail::scope_exit([&] {
  26062. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26063. });
  26064. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26065. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26066. sockaddr_in addr{};
  26067. addr.sin_family = AF_INET;
  26068. addr.sin_port = htons(static_cast<uint16_t>(port));
  26069. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26070. ASSERT_EQ(
  26071. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26072. << "attempt " << attempt;
  26073. ASSERT_TRUE(send_bytes(sock,
  26074. "GET /ws HTTP/1.1\r\n"
  26075. "Host: 127.0.0.1\r\n"
  26076. "Upgrade: websocket\r\n"
  26077. "Connection: Upgrade\r\n"
  26078. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26079. "Sec-WebSocket-Version: 13\r\n"
  26080. "\r\n"))
  26081. << "attempt " << attempt;
  26082. std::string response;
  26083. while (response.find("\r\n\r\n") == std::string::npos) {
  26084. char buf[512];
  26085. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26086. if (n <= 0) { break; }
  26087. response.append(buf, static_cast<size_t>(n));
  26088. }
  26089. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26090. << "attempt " << attempt;
  26091. // Send the header of a Binary message but only the first prefix_len bytes
  26092. // of its payload, leaving the reader thread stalled inside the payload.
  26093. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26094. expected.substr(0, prefix_len)))
  26095. << "attempt " << attempt;
  26096. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26097. peer_stalled = true;
  26098. // Let close() send its Close frame and park in its own read before the
  26099. // rest of the payload arrives, so both threads are waiting for it.
  26100. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26101. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26102. close_frame += static_cast<char>(0x03); // status 1000
  26103. close_frame += static_cast<char>(0xE8);
  26104. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26105. << "attempt " << attempt;
  26106. // Closing the peer releases the reader thread even on the buggy path,
  26107. // where it waits for bytes another thread already consumed.
  26108. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26109. detail::close_socket(sock);
  26110. sock = INVALID_SOCKET;
  26111. wait_for(handler_done);
  26112. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26113. }
  26114. std::lock_guard<std::mutex> guard(received_mutex);
  26115. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26116. << "a message in flight when close() ran was dropped";
  26117. for (size_t i = 0; i < received.size(); i++) {
  26118. EXPECT_EQ(expected, received[i]) << "message " << i;
  26119. }
  26120. }
  26121. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26122. // returning the socket, or INVALID_SOCKET.
  26123. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26124. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26125. if (sock == INVALID_SOCKET) { return sock; }
  26126. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26127. sockaddr_in addr{};
  26128. addr.sin_family = AF_INET;
  26129. addr.sin_port = htons(static_cast<uint16_t>(port));
  26130. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26131. std::string req = "GET " + path +
  26132. " HTTP/1.1\r\n"
  26133. "Host: 127.0.0.1\r\n"
  26134. "Upgrade: websocket\r\n"
  26135. "Connection: Upgrade\r\n"
  26136. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26137. "Sec-WebSocket-Version: 13\r\n"
  26138. "\r\n";
  26139. std::string res;
  26140. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26141. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26142. static_cast<ssize_t>(req.size())) {
  26143. char c;
  26144. while (res.find("\r\n\r\n") == std::string::npos &&
  26145. ::recv(sock, &c, 1, 0) == 1) {
  26146. res += c;
  26147. }
  26148. }
  26149. if (res.find(" 101 ") == std::string::npos) {
  26150. detail::close_socket(sock);
  26151. return INVALID_SOCKET;
  26152. }
  26153. return sock;
  26154. }
  26155. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26156. // The payload must fit the 7-bit length field.
  26157. static std::string masked_frame(uint8_t first_byte,
  26158. const std::string &payload) {
  26159. std::string f;
  26160. f += static_cast<char>(first_byte);
  26161. f += static_cast<char>(0x80 | payload.size());
  26162. f.append(4, '\0');
  26163. return f + payload;
  26164. }
  26165. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26166. std::atomic<bool> done{false};
  26167. std::string received;
  26168. Server svr;
  26169. svr.set_websocket_ping_interval(0);
  26170. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26171. std::string msg;
  26172. if (ws.read(msg) == ws::Binary) { received = msg; }
  26173. done = true;
  26174. });
  26175. auto port = svr.bind_to_any_port("127.0.0.1");
  26176. std::thread t([&]() { svr.listen_after_bind(); });
  26177. auto se = detail::scope_exit([&] {
  26178. svr.stop();
  26179. t.join();
  26180. });
  26181. svr.wait_until_ready();
  26182. auto sock = connect_raw_websocket(port, "/ws");
  26183. ASSERT_NE(INVALID_SOCKET, sock);
  26184. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26185. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26186. masked_frame(0x89, "p") + // FIN + Ping
  26187. masked_frame(0x80, "lo"); // FIN + Continuation
  26188. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26189. for (int i = 0; i < 500 && !done; i++) {
  26190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26191. }
  26192. ASSERT_TRUE(done);
  26193. EXPECT_EQ("Hello", received);
  26194. // The Ping between the fragments is answered with a Pong.
  26195. char pong[3];
  26196. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26197. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26198. }
  26199. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26200. #ifndef _WIN32
  26201. signal(SIGPIPE, SIG_IGN);
  26202. #endif
  26203. std::atomic<bool> read_ended{false};
  26204. std::atomic<bool> sending{true};
  26205. Server svr;
  26206. svr.set_websocket_ping_interval(0);
  26207. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26208. std::thread reader([&]() {
  26209. std::string msg;
  26210. while (ws.read(msg)) {}
  26211. read_ended = true;
  26212. });
  26213. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26214. ws.close();
  26215. reader.join();
  26216. });
  26217. auto port = svr.bind_to_any_port("127.0.0.1");
  26218. std::thread t([&]() { svr.listen_after_bind(); });
  26219. auto se = detail::scope_exit([&] {
  26220. svr.stop();
  26221. t.join();
  26222. });
  26223. svr.wait_until_ready();
  26224. auto sock = connect_raw_websocket(port, "/ws");
  26225. ASSERT_NE(INVALID_SOCKET, sock);
  26226. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26227. // A Text message whose empty continuation frames never end
  26228. std::thread sender([&]() {
  26229. auto data = masked_frame(0x01, "");
  26230. while (sending) {
  26231. data += masked_frame(0x00, "");
  26232. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26233. return;
  26234. }
  26235. data.clear();
  26236. }
  26237. });
  26238. for (int i = 0; i < 300 && !read_ended; i++) {
  26239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26240. }
  26241. sending = false;
  26242. sender.join();
  26243. EXPECT_TRUE(read_ended);
  26244. }
  26245. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26246. Server svr;
  26247. svr.set_websocket_ping_interval(-1);
  26248. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26249. std::string msg;
  26250. while (ws.read(msg)) {}
  26251. });
  26252. auto port = svr.bind_to_any_port("127.0.0.1");
  26253. std::thread t([&]() { svr.listen_after_bind(); });
  26254. auto se = detail::scope_exit([&] {
  26255. svr.stop();
  26256. t.join();
  26257. });
  26258. svr.wait_until_ready();
  26259. auto sock = connect_raw_websocket(port, "/ws");
  26260. ASSERT_NE(INVALID_SOCKET, sock);
  26261. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26262. // Nothing comes while the client stays quiet.
  26263. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26264. char c;
  26265. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26266. }
  26267. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26268. // and that has to end a read() already waiting on the peer, on every platform.
  26269. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26270. // The peer sends no pings, and its handler never calls read(), which is
  26271. // where pongs are written.
  26272. std::mutex mutex;
  26273. std::condition_variable cv;
  26274. auto release = false;
  26275. svr.set_websocket_ping_interval(0);
  26276. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26277. std::unique_lock<std::mutex> lock(mutex);
  26278. cv.wait(lock, [&] { return release; });
  26279. });
  26280. auto port = svr.bind_to_any_port(HOST);
  26281. std::thread t([&]() { svr.listen_after_bind(); });
  26282. auto se = detail::scope_exit([&] {
  26283. {
  26284. std::lock_guard<std::mutex> lock(mutex);
  26285. release = true;
  26286. }
  26287. cv.notify_all();
  26288. svr.stop();
  26289. t.join();
  26290. });
  26291. svr.wait_until_ready();
  26292. ws::WebSocketClient client(std::string(scheme) +
  26293. "://localhost:" + std::to_string(port) + "/ws");
  26294. #ifdef CPPHTTPLIB_SSL_ENABLED
  26295. client.enable_server_certificate_verification(false);
  26296. #endif
  26297. // A ping a second, given up on after two go unanswered: about 3s
  26298. client.set_websocket_ping_interval(1);
  26299. client.set_websocket_max_missed_pongs(2);
  26300. // Well past that, so that a read the timeout ends instead stands out
  26301. client.set_read_timeout(10);
  26302. ASSERT_TRUE(client.connect());
  26303. auto start = std::chrono::steady_clock::now();
  26304. std::string msg;
  26305. EXPECT_EQ(ws::Fail, client.read(msg));
  26306. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26307. std::chrono::steady_clock::now() - start)
  26308. .count(),
  26309. 6000);
  26310. EXPECT_FALSE(client.is_open());
  26311. }
  26312. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26313. Server svr;
  26314. check_pong_timeout_ends_read(svr, "ws");
  26315. }
  26316. #ifdef CPPHTTPLIB_SSL_ENABLED
  26317. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26319. ASSERT_TRUE(svr.is_valid());
  26320. check_pong_timeout_ends_read(svr, "wss");
  26321. }
  26322. #endif
  26323. // listen() returns only after every handler has, so Server::stop() has to end
  26324. // a WebSocket handler's read() waiting on a client that stays connected and
  26325. // quiet, whether or not the handler bounded its reads, and the client's
  26326. // connection ends with it.
  26327. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26328. bool bounded) {
  26329. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26330. if (bounded) { ws.set_read_timeout(0, 50000); }
  26331. std::string msg;
  26332. while (ws.read(msg) != ws::Fail) {}
  26333. });
  26334. auto port = svr.bind_to_any_port(HOST);
  26335. std::thread t([&]() { svr.listen_after_bind(); });
  26336. auto se = detail::scope_exit([&] {
  26337. if (t.joinable()) {
  26338. svr.stop();
  26339. t.join();
  26340. }
  26341. });
  26342. svr.wait_until_ready();
  26343. ws::WebSocketClient client(std::string(scheme) +
  26344. "://localhost:" + std::to_string(port) + "/ws");
  26345. #ifdef CPPHTTPLIB_SSL_ENABLED
  26346. client.enable_server_certificate_verification(false);
  26347. #endif
  26348. client.set_read_timeout(2);
  26349. ASSERT_TRUE(client.connect());
  26350. auto stopped = std::async(std::launch::async, [&] {
  26351. svr.stop();
  26352. t.join();
  26353. });
  26354. std::string msg;
  26355. EXPECT_EQ(ws::Fail, client.read(msg));
  26356. EXPECT_FALSE(client.is_open());
  26357. auto in_time =
  26358. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26359. // A handler the stop did not reach ends when the client leaves
  26360. if (!in_time) { client.close(); }
  26361. stopped.wait();
  26362. EXPECT_TRUE(in_time);
  26363. }
  26364. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26365. Server svr;
  26366. check_stop_ends_websocket_read(svr, "ws", false);
  26367. }
  26368. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26369. Server svr;
  26370. check_stop_ends_websocket_read(svr, "ws", true);
  26371. }
  26372. #ifdef CPPHTTPLIB_SSL_ENABLED
  26373. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26375. ASSERT_TRUE(svr.is_valid());
  26376. check_stop_ends_websocket_read(svr, "wss", false);
  26377. }
  26378. #endif
  26379. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26380. // dropped connection, whether the handler waits for a message or for the rest
  26381. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26382. // time out inside the message as well, and the stop ends them too.
  26383. static void check_stop_closes_with_going_away(const std::string &sent,
  26384. bool bounded = false) {
  26385. Server svr;
  26386. svr.set_websocket_ping_interval(0);
  26387. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26388. if (bounded) { ws.set_read_timeout(0, 10000); }
  26389. std::string msg;
  26390. while (ws.read(msg) != ws::Fail) {}
  26391. });
  26392. auto port = svr.bind_to_any_port("127.0.0.1");
  26393. std::thread t([&]() { svr.listen_after_bind(); });
  26394. auto se = detail::scope_exit([&] {
  26395. svr.stop();
  26396. t.join();
  26397. });
  26398. svr.wait_until_ready();
  26399. // Closed before the join above, which a handler the stop did not reach
  26400. // would otherwise hold up.
  26401. auto sock = connect_raw_websocket(port, "/ws");
  26402. ASSERT_NE(INVALID_SOCKET, sock);
  26403. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26404. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26405. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26406. // Let the handler take what was sent and wait for more
  26407. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26408. svr.stop();
  26409. // FIN + Close, its length, then the code: unmasked, from a server
  26410. std::string head;
  26411. char c;
  26412. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26413. head += c;
  26414. }
  26415. const std::string reason = "server stopping";
  26416. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26417. "\x03\xe9",
  26418. head);
  26419. }
  26420. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26421. check_stop_closes_with_going_away("");
  26422. }
  26423. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26424. // A Text frame without FIN: the first fragment of a message
  26425. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26426. }
  26427. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26428. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26429. /*bounded=*/true);
  26430. }
  26431. // A handler that bounds its reads gets control back within its timeout even
  26432. // while a message arrives in pieces, and the message whole once the last has
  26433. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26434. // sent a while after the one before, much longer than the handler's timeout.
  26435. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26436. const std::string &expected) {
  26437. std::atomic<bool> done{false};
  26438. std::string received;
  26439. std::chrono::steady_clock::duration longest{};
  26440. Server svr;
  26441. svr.set_websocket_ping_interval(0);
  26442. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26443. ws.set_read_timeout(0, 10000);
  26444. std::string msg;
  26445. ws::ReadResult r;
  26446. do {
  26447. auto began = std::chrono::steady_clock::now();
  26448. r = ws.read(msg);
  26449. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26450. } while (r == ws::Timeout);
  26451. if (r == ws::Text) { received = msg; }
  26452. done = true;
  26453. });
  26454. auto port = svr.bind_to_any_port("127.0.0.1");
  26455. std::thread t([&]() { svr.listen_after_bind(); });
  26456. auto se = detail::scope_exit([&] {
  26457. svr.stop();
  26458. t.join();
  26459. });
  26460. svr.wait_until_ready();
  26461. auto sock = connect_raw_websocket(port, "/ws");
  26462. ASSERT_NE(INVALID_SOCKET, sock);
  26463. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26464. for (const auto &piece : pieces) {
  26465. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26466. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26467. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26468. }
  26469. for (int i = 0; i < 500 && !done; i++) {
  26470. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26471. }
  26472. ASSERT_TRUE(done);
  26473. EXPECT_EQ(expected, received);
  26474. // Far under the 200 ms between the pieces, however loaded the machine
  26475. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26476. }
  26477. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26478. // The header's first byte, then its second with half the mask key, then
  26479. // the rest: what a frame written in several writes may look like when
  26480. // Nagle's algorithm holds the later ones back for an ACK.
  26481. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26482. check_bounded_read_resumes(
  26483. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26484. }
  26485. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26486. check_bounded_read_resumes(
  26487. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26488. }
  26489. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26490. Server svr;
  26491. svr.set_websocket_ping_interval(0);
  26492. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26493. std::string msg;
  26494. while (ws.read(msg)) {}
  26495. });
  26496. auto port = svr.bind_to_any_port("127.0.0.1");
  26497. std::thread t([&]() { svr.listen_after_bind(); });
  26498. auto se = detail::scope_exit([&] {
  26499. svr.stop();
  26500. t.join();
  26501. });
  26502. svr.wait_until_ready();
  26503. // Each Close payload and the reply it should get: an echo when valid, 1002
  26504. // otherwise.
  26505. std::vector<std::pair<std::string, std::string>> cases = {
  26506. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26507. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26508. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26509. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26510. };
  26511. // Also between the fragments of a message.
  26512. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26513. for (const auto &c : cases) {
  26514. auto sock = connect_raw_websocket(port, "/ws");
  26515. ASSERT_NE(INVALID_SOCKET, sock);
  26516. auto frames = prefix + masked_frame(0x88, c.first);
  26517. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26518. std::string reply;
  26519. char buf[256];
  26520. while (reply.size() < 2 + c.second.size()) {
  26521. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26522. if (n <= 0) { break; }
  26523. reply.append(buf, static_cast<size_t>(n));
  26524. }
  26525. detail::close_socket(sock);
  26526. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26527. c.second,
  26528. reply);
  26529. }
  26530. }
  26531. }
  26532. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26533. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26534. protected:
  26535. void SetUp() override {
  26536. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26537. SERVER_PRIVATE_KEY_FILE);
  26538. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26539. std::string msg;
  26540. ws::ReadResult ret;
  26541. while ((ret = ws.read(msg))) {
  26542. if (ret == ws::Binary) {
  26543. ws.send(msg.data(), msg.size());
  26544. } else {
  26545. ws.send(msg);
  26546. }
  26547. }
  26548. });
  26549. port_ = server_->bind_to_any_port(HOST);
  26550. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26551. server_->wait_until_ready();
  26552. }
  26553. void TearDown() override {
  26554. server_->stop();
  26555. if (server_thread_.joinable()) { server_thread_.join(); }
  26556. }
  26557. std::unique_ptr<SSLServer> server_;
  26558. std::thread server_thread_;
  26559. int port_ = 0;
  26560. };
  26561. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26562. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26563. {
  26564. ws::WebSocketClient client(url);
  26565. client.enable_server_certificate_verification(false);
  26566. auto calls = 0;
  26567. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26568. calls++;
  26569. return false;
  26570. });
  26571. EXPECT_FALSE(client.connect());
  26572. EXPECT_GT(calls, 0);
  26573. }
  26574. {
  26575. ws::WebSocketClient client(url);
  26576. client.enable_server_certificate_verification(false);
  26577. client.set_session_verifier([](tls::session_t) {
  26578. return SSLVerifierResponse::CertificateRejected;
  26579. });
  26580. EXPECT_FALSE(client.connect());
  26581. }
  26582. {
  26583. ws::WebSocketClient client(url);
  26584. client.enable_server_certificate_verification(false);
  26585. client.set_session_verifier([](tls::session_t) {
  26586. return SSLVerifierResponse::CertificateAccepted;
  26587. });
  26588. EXPECT_TRUE(client.connect());
  26589. }
  26590. }
  26591. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26592. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26593. "/ws-echo");
  26594. client.enable_server_certificate_verification(false);
  26595. ASSERT_TRUE(client.connect());
  26596. ASSERT_TRUE(client.is_open());
  26597. ASSERT_TRUE(client.send("Hello WSS"));
  26598. std::string msg;
  26599. EXPECT_EQ(ws::Text, client.read(msg));
  26600. EXPECT_EQ("Hello WSS", msg);
  26601. client.close();
  26602. }
  26603. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26604. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26605. "/ws-echo");
  26606. client.enable_server_certificate_verification(false);
  26607. EXPECT_TRUE(client.connect());
  26608. }
  26609. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26610. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26611. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26612. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26613. // client (without calling close() first) is the only path that runs
  26614. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26615. // bug exactly.
  26616. //
  26617. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26618. // when linked against an instrumented libssl; run under Valgrind to catch it
  26619. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26620. // suite (the freed session otherwise stalls on the close handshake) — this test
  26621. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26622. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26623. {
  26624. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26625. "/ws-echo");
  26626. client.enable_server_certificate_verification(false);
  26627. client.set_read_timeout(2, 0);
  26628. client.set_write_timeout(2, 0);
  26629. ASSERT_TRUE(client.connect());
  26630. ASSERT_TRUE(client.is_open());
  26631. ASSERT_TRUE(client.send("still open"));
  26632. // Intentionally do NOT call client.close(): leaving scope runs
  26633. // shutdown_and_close() with the WebSocket still open, which must send the
  26634. // close frame while the TLS session is still alive.
  26635. }
  26636. }
  26637. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26638. // shutdown_and_close() at the start of connect(), reproducing the same
  26639. // use-after-free within the test body rather than at scope exit. The second
  26640. // connect must succeed and echo, proving the close handshake ran over a live
  26641. // session. See the note above about memory-tool requirements.
  26642. TEST_F(WebSocketSSLIntegrationTest,
  26643. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26644. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26645. "/ws-echo");
  26646. client.enable_server_certificate_verification(false);
  26647. client.set_read_timeout(2, 0);
  26648. client.set_write_timeout(2, 0);
  26649. ASSERT_TRUE(client.connect());
  26650. ASSERT_TRUE(client.is_open());
  26651. ASSERT_TRUE(client.send("still open"));
  26652. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26653. // the still-open connection, which must not touch a freed TLS session.
  26654. ASSERT_TRUE(client.connect());
  26655. ASSERT_TRUE(client.is_open());
  26656. ASSERT_TRUE(client.send("after reconnect"));
  26657. std::string msg;
  26658. EXPECT_EQ(ws::Text, client.read(msg));
  26659. EXPECT_EQ("after reconnect", msg);
  26660. client.close();
  26661. }
  26662. #endif
  26663. #ifdef CPPHTTPLIB_SSL_ENABLED
  26664. class WebSocketSSLCATest : public ::testing::Test {
  26665. protected:
  26666. void SetUp() override {
  26667. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26668. SERVER_PRIVATE_KEY_FILE);
  26669. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26670. std::string msg;
  26671. while (ws.read(msg)) {
  26672. ws.send(msg);
  26673. }
  26674. });
  26675. port_ = server_->bind_to_any_port("127.0.0.1");
  26676. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26677. server_->wait_until_ready();
  26678. }
  26679. void TearDown() override {
  26680. server_->stop();
  26681. if (server_thread_.joinable()) { server_thread_.join(); }
  26682. }
  26683. std::string url() const {
  26684. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26685. }
  26686. std::unique_ptr<SSLServer> server_;
  26687. std::thread server_thread_;
  26688. int port_ = 0;
  26689. };
  26690. // A custom CA loaded as PEM verifies the server with full certificate
  26691. // verification enabled
  26692. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26693. ws::WebSocketClient client(url());
  26694. std::string cert;
  26695. read_file(SERVER_CERT2_FILE, cert);
  26696. client.load_ca_cert_store(cert.c_str(), cert.size());
  26697. ASSERT_TRUE(client.connect());
  26698. ASSERT_TRUE(client.send("hello"));
  26699. std::string msg;
  26700. EXPECT_EQ(ws::Text, client.read(msg));
  26701. EXPECT_EQ("hello", msg);
  26702. client.close();
  26703. }
  26704. // A custom CA that does not cover the server must fail verification (the
  26705. // custom CA is exclusive; system certs are not loaded alongside it)
  26706. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26707. ws::WebSocketClient client(url());
  26708. std::string cert;
  26709. read_file(CLIENT_CA_CERT_FILE, cert);
  26710. client.load_ca_cert_store(cert.c_str(), cert.size());
  26711. auto res = client.connect();
  26712. ASSERT_FALSE(res);
  26713. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26714. EXPECT_EQ(-1, res.status());
  26715. EXPECT_NE(0u, res.ssl_backend_error());
  26716. }
  26717. // The same CA as a file path rather than PEM in memory
  26718. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26719. ws::WebSocketClient client(url());
  26720. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26721. ASSERT_TRUE(client.connect());
  26722. ASSERT_TRUE(client.send("hello"));
  26723. std::string msg;
  26724. EXPECT_EQ(ws::Text, client.read(msg));
  26725. EXPECT_EQ("hello", msg);
  26726. client.close();
  26727. }
  26728. // ...and a CA file that does not cover the server still fails, so it is the
  26729. // path above that decides the outcome
  26730. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26731. ws::WebSocketClient client(url());
  26732. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26733. ASSERT_FALSE(client.connect());
  26734. }
  26735. // Regression test: reconnecting with a native custom CA store used to reuse
  26736. // a store handle the previous TLS context had already freed (use-after-free
  26737. // under the OpenSSL backend). The context now lives as long as the client.
  26738. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26739. ws::WebSocketClient client(url());
  26740. std::string cert;
  26741. read_file(SERVER_CERT2_FILE, cert);
  26742. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26743. ASSERT_TRUE(client.connect());
  26744. client.close();
  26745. ASSERT_TRUE(client.connect());
  26746. ASSERT_TRUE(client.send("again"));
  26747. std::string msg;
  26748. EXPECT_EQ(ws::Text, client.read(msg));
  26749. EXPECT_EQ("again", msg);
  26750. client.close();
  26751. }
  26752. // Regression test: a certificate with a trusted chain but no identity match
  26753. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26754. // verification entirely for IP hosts, so this connection succeeded there.
  26755. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26756. // chain verification while the identity check must still fail.
  26757. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26759. ASSERT_TRUE(svr.is_valid());
  26760. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26761. std::string msg;
  26762. while (ws.read(msg)) {
  26763. ws.send(msg);
  26764. }
  26765. });
  26766. auto port = svr.bind_to_any_port("127.0.0.1");
  26767. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26768. auto se = detail::scope_exit([&] {
  26769. svr.stop();
  26770. t.join();
  26771. });
  26772. svr.wait_until_ready();
  26773. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26774. "/echo");
  26775. std::string cert;
  26776. read_file(SERVER_CERT_FILE, cert);
  26777. client.load_ca_cert_store(cert.c_str(), cert.size());
  26778. ASSERT_FALSE(client.connect());
  26779. }
  26780. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26781. // SNI, so nothing binds the host name to the TLS session. These bind the
  26782. // server to "localhost" instead, the only shape that exercises the SNI and
  26783. // hostname-verification path with certificate verification left enabled.
  26784. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26785. protected:
  26786. void Start(const char *cert_file) {
  26787. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26788. SERVER_PRIVATE_KEY_FILE);
  26789. ASSERT_TRUE(server_->is_valid());
  26790. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26791. std::string msg;
  26792. while (ws.read(msg)) {
  26793. ws.send(msg);
  26794. }
  26795. });
  26796. port_ = server_->bind_to_any_port("localhost");
  26797. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26798. server_->wait_until_ready();
  26799. }
  26800. void TearDown() override {
  26801. if (server_) { server_->stop(); }
  26802. if (server_thread_.joinable()) { server_thread_.join(); }
  26803. }
  26804. std::string url() const {
  26805. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26806. }
  26807. std::unique_ptr<SSLServer> server_;
  26808. std::thread server_thread_;
  26809. int port_ = 0;
  26810. };
  26811. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26812. // out and the connection is usable
  26813. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26814. Start(SERVER_CERT2_FILE);
  26815. ws::WebSocketClient client(url());
  26816. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26817. ASSERT_TRUE(client.connect());
  26818. ASSERT_TRUE(client.send("hello"));
  26819. std::string msg;
  26820. EXPECT_EQ(ws::Text, client.read(msg));
  26821. EXPECT_EQ("hello", msg);
  26822. client.close();
  26823. }
  26824. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26825. // while the identity check must still reject "localhost"
  26826. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26827. Start(SERVER_CERT_FILE);
  26828. ws::WebSocketClient client(url());
  26829. client.set_ca_cert_path(SERVER_CERT_FILE);
  26830. auto res = client.connect();
  26831. ASSERT_FALSE(res);
  26832. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26833. EXPECT_EQ(-1, res.status());
  26834. }
  26835. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26836. // disabled: the chain is still checked, only the identity check is skipped
  26837. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26838. Start(SERVER_CERT_FILE);
  26839. ws::WebSocketClient client(url());
  26840. client.set_ca_cert_path(SERVER_CERT_FILE);
  26841. client.enable_server_hostname_verification(false);
  26842. ASSERT_TRUE(client.connect());
  26843. ASSERT_TRUE(client.send("hello"));
  26844. std::string msg;
  26845. EXPECT_EQ(ws::Text, client.read(msg));
  26846. EXPECT_EQ("hello", msg);
  26847. client.close();
  26848. }
  26849. // A CA that did not sign the server certificate fails the chain, even though
  26850. // the name would match
  26851. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26852. Start(SERVER_CERT2_FILE);
  26853. ws::WebSocketClient client(url());
  26854. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26855. ASSERT_FALSE(client.connect());
  26856. }
  26857. // With verification disabled, neither the chain nor the name is checked
  26858. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26859. Start(SERVER_CERT_FILE);
  26860. ws::WebSocketClient client(url());
  26861. client.enable_server_certificate_verification(false);
  26862. ASSERT_TRUE(client.connect());
  26863. ASSERT_TRUE(client.send("hello"));
  26864. std::string msg;
  26865. EXPECT_EQ(ws::Text, client.read(msg));
  26866. EXPECT_EQ("hello", msg);
  26867. client.close();
  26868. }
  26869. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26870. protected:
  26871. void SetUp() override {
  26872. server_ = httplib::detail::make_unique<SSLServer>(
  26873. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26874. ASSERT_TRUE(server_->is_valid());
  26875. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26876. std::string msg;
  26877. while (ws.read(msg)) {
  26878. ws.send(msg);
  26879. }
  26880. });
  26881. port_ = server_->bind_to_any_port("localhost");
  26882. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26883. server_->wait_until_ready();
  26884. }
  26885. void TearDown() override {
  26886. server_->stop();
  26887. if (server_thread_.joinable()) { server_thread_.join(); }
  26888. }
  26889. std::string url() const {
  26890. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26891. }
  26892. void ConnectWithClientCert(const std::string &client_cert_file,
  26893. const std::string &client_private_key_file,
  26894. const char *private_key_password) {
  26895. std::string cert_pem, key_pem;
  26896. read_file(client_cert_file, cert_pem);
  26897. read_file(client_private_key_file, key_pem);
  26898. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26899. key_pem.c_str(), key_pem.size(),
  26900. private_key_password};
  26901. ConnectWithPem(pem);
  26902. }
  26903. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26904. ws::WebSocketClient client(url(), pem);
  26905. ASSERT_TRUE(client.is_valid());
  26906. client.enable_server_certificate_verification(false);
  26907. ASSERT_TRUE(client.connect());
  26908. ASSERT_TRUE(client.send("hello"));
  26909. std::string msg;
  26910. EXPECT_EQ(ws::Text, client.read(msg));
  26911. EXPECT_EQ("hello", msg);
  26912. client.close();
  26913. }
  26914. std::unique_ptr<SSLServer> server_;
  26915. std::thread server_thread_;
  26916. int port_ = 0;
  26917. };
  26918. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26919. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26920. }
  26921. // Control for the tests above: the fixture's server really does require a
  26922. // client certificate, so it is the PEM the constructor installed that decides
  26923. // the outcome.
  26924. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26925. ws::WebSocketClient client(url());
  26926. ASSERT_TRUE(client.is_valid());
  26927. client.enable_server_certificate_verification(false);
  26928. EXPECT_FALSE(client.connect());
  26929. }
  26930. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26931. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26932. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26933. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26934. }
  26935. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26936. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26937. std::string cert_pem, key_pem;
  26938. read_file(CLIENT_CERT_FILE, cert_pem);
  26939. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26940. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26941. std::vector<char> key(key_pem.begin(), key_pem.end());
  26942. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26943. key.size(), nullptr};
  26944. ConnectWithPem(pem);
  26945. }
  26946. #endif
  26947. #if !defined(_WIN32)
  26948. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26949. auto secret_dir = std::string("./symlink_test_secret");
  26950. auto served_dir = std::string("./symlink_test_served");
  26951. auto secret_file = secret_dir + "/secret.txt";
  26952. auto symlink_path = served_dir + "/escape";
  26953. // Setup: create directories and files
  26954. mkdir(secret_dir.c_str(), 0755);
  26955. mkdir(served_dir.c_str(), 0755);
  26956. {
  26957. std::ofstream ofs(secret_file);
  26958. ofs << "SECRET_DATA";
  26959. }
  26960. // Create symlink using absolute path so it resolves correctly
  26961. #ifdef PATH_MAX
  26962. char abs_secret[PATH_MAX];
  26963. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26964. #else
  26965. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26966. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26967. ASSERT_NE(nullptr, abs_secret);
  26968. #endif
  26969. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26970. auto se = detail::scope_exit([&] {
  26971. unlink(symlink_path.c_str());
  26972. unlink(secret_file.c_str());
  26973. rmdir(served_dir.c_str());
  26974. rmdir(secret_dir.c_str());
  26975. });
  26976. Server svr;
  26977. svr.set_mount_point("/", served_dir);
  26978. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26979. auto se2 = detail::scope_exit([&] {
  26980. svr.stop();
  26981. listen_thread.join();
  26982. });
  26983. svr.wait_until_ready();
  26984. Client cli("localhost", PORT);
  26985. // Symlink pointing outside base dir should be blocked
  26986. auto res = cli.Get("/escape/secret.txt");
  26987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26988. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26989. }
  26990. #else
  26991. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26992. auto secret_dir = std::string("junction_test_secret");
  26993. auto served_dir = std::string("junction_test_served");
  26994. auto secret_file = secret_dir + "\\secret.txt";
  26995. auto junction_path = served_dir + "\\escape";
  26996. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26997. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26998. {
  26999. std::ofstream ofs(secret_file);
  27000. ofs << "SECRET_DATA";
  27001. }
  27002. // A junction needs no privilege to create, unlike a symlink
  27003. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27004. ASSERT_EQ(0, std::system(cmd.c_str()));
  27005. auto se = detail::scope_exit([&] {
  27006. ::RemoveDirectoryA(junction_path.c_str());
  27007. std::remove(secret_file.c_str());
  27008. ::RemoveDirectoryA(served_dir.c_str());
  27009. ::RemoveDirectoryA(secret_dir.c_str());
  27010. });
  27011. Server svr;
  27012. svr.set_mount_point("/", served_dir);
  27013. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27014. auto se2 = detail::scope_exit([&] {
  27015. svr.stop();
  27016. listen_thread.join();
  27017. });
  27018. svr.wait_until_ready();
  27019. Client cli("localhost", PORT);
  27020. // Junction pointing outside base dir should be blocked
  27021. auto res = cli.Get("/escape/secret.txt");
  27022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27023. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27024. }
  27025. #endif
  27026. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27027. // "GET /smuggled" request), reads the first response, and only then sends the
  27028. // embedded request as the body. Returns how many times /smuggled ran.
  27029. //
  27030. // The body is sent AFTER receiving the first response (as in the original
  27031. // PoC) so that the stream_line_reader cannot buffer it together with the
  27032. // headers of the first request.
  27033. static int count_smuggled_requests(const std::string &outer_head,
  27034. std::string &first_response) {
  27035. Server svr;
  27036. svr.set_mount_point("/", "./www");
  27037. std::atomic<int> smuggled_count(0);
  27038. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27039. smuggled_count++;
  27040. res.set_content("oops", "text/plain");
  27041. });
  27042. svr.Post("/post", [&](const Request &req, Response &res) {
  27043. res.set_content(req.body, "text/plain");
  27044. });
  27045. auto port = svr.bind_to_any_port("localhost");
  27046. thread t = thread([&] { svr.listen_after_bind(); });
  27047. auto se = detail::scope_exit([&] {
  27048. svr.stop();
  27049. t.join();
  27050. });
  27051. svr.wait_until_ready();
  27052. auto error = Error::Success;
  27053. auto sock = detail::create_client_socket(
  27054. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27055. /*connection_timeout_sec=*/2, 0,
  27056. /*read_timeout_sec=*/2, 0,
  27057. /*write_timeout_sec=*/2, 0, std::string(), error);
  27058. EXPECT_NE(INVALID_SOCKET, sock);
  27059. if (sock == INVALID_SOCKET) { return -1; }
  27060. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27061. // The "smuggled" request will be sent as the body of the outer request
  27062. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27063. "Host: localhost\r\n"
  27064. "Connection: close\r\n"
  27065. "\r\n";
  27066. auto head = outer_head;
  27067. auto len = std::to_string(smuggled.size());
  27068. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27069. pos = head.find("{len}", pos + len.size())) {
  27070. head.replace(pos, 5, len);
  27071. }
  27072. // Step 1: Send only the outer request headers (no body yet)
  27073. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27074. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27075. // Step 2: Read the first response
  27076. char buf[4096];
  27077. for (;;) {
  27078. auto n = recv(sock, buf, sizeof(buf), 0);
  27079. if (n <= 0) break;
  27080. first_response.append(buf, static_cast<size_t>(n));
  27081. // Stop once we have a complete response (headers + body)
  27082. auto hdr_end = first_response.find("\r\n\r\n");
  27083. if (hdr_end != std::string::npos) {
  27084. // Check for Content-Length to know when the body is complete
  27085. auto cl_pos = first_response.find("Content-Length:");
  27086. if (cl_pos != std::string::npos) {
  27087. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27088. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27089. auto cl = std::stoul(
  27090. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27091. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27092. } else {
  27093. break; // No Content-Length, assume headers-only response
  27094. }
  27095. }
  27096. }
  27097. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27098. // vulnerable server the keep-alive loop reads this as a second request. The
  27099. // server may already have closed the connection, so the result is ignored.
  27100. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27101. // Half-close so that a server which drained the body sees EOF and closes,
  27102. // instead of the read below waiting for the read timeout.
  27103. #ifdef _WIN32
  27104. ::shutdown(sock, SD_SEND);
  27105. #else
  27106. ::shutdown(sock, SHUT_WR);
  27107. #endif
  27108. // Step 4: Read until the server closes the connection
  27109. for (;;) {
  27110. auto n = recv(sock, buf, sizeof(buf), 0);
  27111. if (n <= 0) break;
  27112. }
  27113. return smuggled_count.load();
  27114. }
  27115. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27116. // A GET request with Content-Length to a static file handler must have its
  27117. // body drained before the keep-alive connection is reused. Otherwise the
  27118. // unread body bytes are interpreted as the next HTTP request.
  27119. std::string first_response;
  27120. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27121. "Host: localhost\r\n"
  27122. "Content-Length: {len}\r\n"
  27123. "\r\n",
  27124. first_response));
  27125. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27126. }
  27127. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27128. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27129. // be answered with 400 and the connection closed. Treating it as "no body"
  27130. // leaves the body to be parsed as the next request.
  27131. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27132. const char *targets[] = {
  27133. "GET /file", // handler that never reads the body
  27134. "GET /not-found", // no handler matches (404)
  27135. "POST /post", // handler that reads the body
  27136. };
  27137. for (auto target : targets) {
  27138. for (auto value : values) {
  27139. std::string first_response;
  27140. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27141. " HTTP/1.1\r\n"
  27142. "Host: localhost\r\n"
  27143. "Content-Length: " +
  27144. value + "\r\n\r\n",
  27145. first_response))
  27146. << target << " with Content-Length: " << value;
  27147. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27148. << target << " with Content-Length: " << value;
  27149. }
  27150. }
  27151. }
  27152. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27153. // A 400 for an unparseable request line leaves the rest of the message
  27154. // unread, so the connection must be closed rather than reused.
  27155. std::string first_response;
  27156. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27157. "Host: localhost\r\n"
  27158. "Content-Length: {len}\r\n"
  27159. "\r\n",
  27160. first_response));
  27161. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27162. }
  27163. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27164. // Same as above for a header block that fails to parse.
  27165. std::string first_response;
  27166. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27167. "Host: localhost\r\n"
  27168. "Bad Header\r\n"
  27169. "Content-Length: {len}\r\n"
  27170. "\r\n",
  27171. first_response));
  27172. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27173. }
  27174. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27175. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27176. // server must not read another request on that connection, even when the
  27177. // request had no body to drain.
  27178. std::string first_response;
  27179. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27180. "Host: localhost\r\n"
  27181. "\r\n",
  27182. first_response));
  27183. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27184. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27185. }
  27186. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27187. // A content reader that stops early leaves the stream inside the body.
  27188. // Draining the whole Content-Length from there, or reading the body again,
  27189. // reads into the next request, and whatever follows is parsed as a request
  27190. // of its own.
  27191. Server svr;
  27192. std::atomic<int> smuggled_count(0);
  27193. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27194. svr.Post("/upload", [](const Request &req, Response &res,
  27195. const ContentReader &content_reader) {
  27196. // Stop at the last chunk, so the whole body has been read however it
  27197. // arrives.
  27198. auto length = req.get_header_value_u64("Content-Length");
  27199. size_t total = 0;
  27200. auto consumed = content_reader([&](const char *, size_t n) {
  27201. total += n;
  27202. return total < length;
  27203. });
  27204. EXPECT_FALSE(consumed);
  27205. if (req.has_param("retry")) {
  27206. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27207. }
  27208. // Replace the 400 the aborted read set, which would close the connection.
  27209. res.set_redirect("/done");
  27210. });
  27211. auto port = svr.bind_to_any_port(HOST);
  27212. thread t = thread([&] { svr.listen_after_bind(); });
  27213. auto se = detail::scope_exit([&] {
  27214. svr.stop();
  27215. t.join();
  27216. });
  27217. svr.wait_until_ready();
  27218. // A front end sees the second request as a POST whose body is the GET. The
  27219. // first body is as long as the POST's headers, so draining it again reads
  27220. // exactly those and leaves the GET to be parsed next.
  27221. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27222. "Host: localhost\r\n"
  27223. "\r\n";
  27224. std::string second_head = "POST /post HTTP/1.1\r\n"
  27225. "Host: localhost\r\n"
  27226. "Content-Length: " +
  27227. std::to_string(inner.size()) +
  27228. "\r\n"
  27229. "\r\n";
  27230. for (auto target : {"/upload", "/upload?retry"}) {
  27231. smuggled_count = 0;
  27232. std::string request = "POST " + std::string(target) +
  27233. " HTTP/1.1\r\n"
  27234. "Host: localhost\r\n"
  27235. "Content-Length: " +
  27236. std::to_string(second_head.size()) +
  27237. "\r\n"
  27238. "\r\n" +
  27239. std::string(second_head.size(), 'A') + second_head +
  27240. inner;
  27241. std::string response;
  27242. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27243. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27244. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27245. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27246. EXPECT_EQ(0, smuggled_count.load()) << target;
  27247. }
  27248. }
  27249. // An error response closes the connection anyway, so the body is left unread
  27250. // with a redirect, such as one to a login page.
  27251. static void serve_redirects(Server &svr,
  27252. const std::function<void(int)> &client) {
  27253. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27254. res.set_redirect("/login");
  27255. return Server::HandlerResponse::Handled;
  27256. });
  27257. auto port = svr.bind_to_any_port(HOST);
  27258. ASSERT_GT(port, 0);
  27259. thread t = thread([&] { svr.listen_after_bind(); });
  27260. auto se = detail::scope_exit([&] {
  27261. svr.stop();
  27262. t.join();
  27263. ASSERT_FALSE(svr.is_running());
  27264. });
  27265. svr.wait_until_ready();
  27266. client(port);
  27267. }
  27268. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27269. Server svr;
  27270. serve_redirects(svr, [](int port) {
  27271. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27272. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27273. std::to_string(body.size()) + "\r\n\r\n" + body +
  27274. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27275. std::string resp;
  27276. ASSERT_TRUE(send_request(1, req, &resp, port));
  27277. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27278. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27279. });
  27280. }
  27281. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27282. Server svr;
  27283. svr.set_read_timeout(0, 200000);
  27284. serve_redirects(svr, [](int port) {
  27285. // A byte every 100 ms keeps each read within the read timeout, but not the
  27286. // body as a whole, so the server closes and the bytes sent after that fail.
  27287. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27288. "Content-Length: 10\r\n\r\n"};
  27289. parts.resize(11, "x");
  27290. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27291. });
  27292. }
  27293. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27294. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27295. // must be rejected with 400 Bad Request.
  27296. Server svr;
  27297. svr.Post("/test", [&](const Request &, Response &res) {
  27298. res.set_content("ok", "text/plain");
  27299. });
  27300. thread t = thread([&] { svr.listen(HOST, PORT); });
  27301. auto se = detail::scope_exit([&] {
  27302. svr.stop();
  27303. t.join();
  27304. ASSERT_FALSE(svr.is_running());
  27305. });
  27306. svr.wait_until_ready();
  27307. // Exact "chunked"
  27308. {
  27309. auto req = "POST /test HTTP/1.1\r\n"
  27310. "Host: localhost\r\n"
  27311. "Content-Length: 5\r\n"
  27312. "Transfer-Encoding: chunked\r\n"
  27313. "Connection: close\r\n"
  27314. "\r\n"
  27315. "hello";
  27316. std::string response;
  27317. ASSERT_TRUE(send_request(1, req, &response));
  27318. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27319. response.substr(0, response.find("\r\n")));
  27320. }
  27321. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27322. {
  27323. auto req = "POST /test HTTP/1.1\r\n"
  27324. "Host: localhost\r\n"
  27325. "Content-Length: 5\r\n"
  27326. "Transfer-Encoding: gzip, chunked\r\n"
  27327. "Connection: close\r\n"
  27328. "\r\n"
  27329. "hello";
  27330. std::string response;
  27331. ASSERT_TRUE(send_request(1, req, &response));
  27332. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27333. response.substr(0, response.find("\r\n")));
  27334. }
  27335. }
  27336. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27337. Server svr;
  27338. svr.Post("/test", [&](const Request &, Response &res) {
  27339. res.set_content("ok", "text/plain");
  27340. });
  27341. thread t = thread([&] { svr.listen(HOST, PORT); });
  27342. auto se = detail::scope_exit([&] {
  27343. svr.stop();
  27344. t.join();
  27345. ASSERT_FALSE(svr.is_running());
  27346. });
  27347. svr.wait_until_ready();
  27348. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27349. // length cannot be determined, so the server must answer 400 and close
  27350. // rather than treat the request as bodyless and leave the body in the
  27351. // socket for the next request to pick up.
  27352. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27353. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27354. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27355. std::string response;
  27356. ASSERT_TRUE(send_request(1, req, &response));
  27357. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27358. response.substr(0, response.find("\r\n")))
  27359. << transfer_encoding;
  27360. }
  27361. // RFC 9110 5.3: the codings may also be split across several
  27362. // Transfer-Encoding lines, which combine in the order they were received.
  27363. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27364. // just like the single-line "chunked, gzip" above.
  27365. {
  27366. auto req = "POST /test HTTP/1.1\r\n"
  27367. "Host: localhost\r\n"
  27368. "Transfer-Encoding: chunked\r\n"
  27369. "Transfer-Encoding: gzip\r\n"
  27370. "\r\n"
  27371. "0\r\n\r\n";
  27372. std::string response;
  27373. ASSERT_TRUE(send_request(1, req, &response));
  27374. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27375. response.substr(0, response.find("\r\n")));
  27376. }
  27377. }
  27378. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27379. Server svr;
  27380. svr.Post("/test", [&](const Request &, Response &res) {
  27381. res.set_content("ok", "text/plain");
  27382. });
  27383. auto port = svr.bind_to_any_port(HOST);
  27384. ASSERT_GT(port, 0);
  27385. thread t = thread([&] { svr.listen_after_bind(); });
  27386. auto se = detail::scope_exit([&] {
  27387. svr.stop();
  27388. t.join();
  27389. ASSERT_FALSE(svr.is_running());
  27390. });
  27391. svr.wait_until_ready();
  27392. for (auto transfer_encoding :
  27393. {"Transfer-Encoding: gzip, chunked\r\n",
  27394. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27395. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27396. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27397. transfer_encoding + "\r\n0\r\n\r\n";
  27398. std::string response;
  27399. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27400. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27401. response.substr(0, response.find("\r\n")))
  27402. << transfer_encoding;
  27403. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27404. << transfer_encoding;
  27405. }
  27406. }
  27407. // Regression for issue #2450: a DELETE without Content-Length on a
  27408. // keep-alive connection must not let the post-response drain consume the
  27409. // next request's bytes.
  27410. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27411. Server svr;
  27412. std::atomic<int> delete_count(0);
  27413. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27414. delete_count++;
  27415. res.status = StatusCode::NoContent_204;
  27416. });
  27417. auto port = svr.bind_to_any_port(HOST);
  27418. thread t = thread([&] { svr.listen_after_bind(); });
  27419. auto se = detail::scope_exit([&] {
  27420. svr.stop();
  27421. t.join();
  27422. });
  27423. svr.wait_until_ready();
  27424. auto error = Error::Success;
  27425. auto sock = detail::create_client_socket(
  27426. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27427. /*connection_timeout_sec=*/2, 0,
  27428. /*read_timeout_sec=*/2, 0,
  27429. /*write_timeout_sec=*/2, 0, std::string(), error);
  27430. ASSERT_NE(INVALID_SOCKET, sock);
  27431. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27432. auto send_request_and_read_response = [&](const std::string &req,
  27433. std::string &out) -> bool {
  27434. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27435. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27436. char buf[4096];
  27437. for (;;) {
  27438. auto n = recv(sock, buf, sizeof(buf), 0);
  27439. if (n <= 0) { return !out.empty(); }
  27440. out.append(buf, static_cast<size_t>(n));
  27441. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27442. }
  27443. };
  27444. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27445. "Host: localhost\r\n"
  27446. "\r\n";
  27447. std::string resp1;
  27448. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27449. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27450. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27451. "Host: localhost\r\n"
  27452. "Connection: close\r\n"
  27453. "\r\n";
  27454. std::string resp2;
  27455. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27456. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27457. EXPECT_EQ(2, delete_count.load());
  27458. }
  27459. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27460. Server svr;
  27461. svr.Post("/ingest", [&](const Request &, Response &res,
  27462. const ContentReader &content_reader) {
  27463. auto consumed = content_reader([](const char *, size_t) { return false; });
  27464. EXPECT_FALSE(consumed);
  27465. res.status = StatusCode::Conflict_409;
  27466. res.set_header("Connection", "close");
  27467. });
  27468. auto port = svr.bind_to_any_port(HOST);
  27469. thread t = thread([&] { svr.listen_after_bind(); });
  27470. auto se = detail::scope_exit([&] {
  27471. svr.stop();
  27472. t.join();
  27473. });
  27474. svr.wait_until_ready();
  27475. auto error = Error::Success;
  27476. auto sock = detail::create_client_socket(
  27477. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27478. /*connection_timeout_sec=*/2, 0,
  27479. /*read_timeout_sec=*/1, 0,
  27480. /*write_timeout_sec=*/2, 0, std::string(), error);
  27481. ASSERT_NE(INVALID_SOCKET, sock);
  27482. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27483. std::string request = "POST /ingest HTTP/1.1\r\n"
  27484. "Host: localhost\r\n"
  27485. "Transfer-Encoding: chunked\r\n"
  27486. "\r\n"
  27487. "4\r\n"
  27488. "data\r\n";
  27489. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27490. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27491. std::string response;
  27492. ssize_t received = 0;
  27493. do {
  27494. char buf[4096];
  27495. received = recv(sock, buf, sizeof(buf), 0);
  27496. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27497. } while (received > 0);
  27498. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27499. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27500. EXPECT_EQ(0, received);
  27501. }
  27502. namespace no_proxy_test {
  27503. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27504. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27505. // calling listen().
  27506. class ScopedServer {
  27507. public:
  27508. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27509. ~ScopedServer() {
  27510. svr_.stop();
  27511. if (th_.joinable()) { th_.join(); }
  27512. }
  27513. Server &svr() { return svr_; }
  27514. int port() const { return port_; }
  27515. void listen() {
  27516. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27517. svr_.wait_until_ready();
  27518. }
  27519. private:
  27520. Server svr_;
  27521. std::thread th_;
  27522. int port_ = 0;
  27523. };
  27524. class ProxyAndTargetServers {
  27525. public:
  27526. ProxyAndTargetServers() {
  27527. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27528. proxy_hits_++;
  27529. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27530. res.set_content("via-proxy", "text/plain");
  27531. });
  27532. target_.Get(".*", [this](const Request &req, Response &res) {
  27533. target_hits_++;
  27534. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27535. res.set_content("direct", "text/plain");
  27536. });
  27537. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27538. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27539. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27540. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27541. proxy_mock_.wait_until_ready();
  27542. target_.wait_until_ready();
  27543. }
  27544. ~ProxyAndTargetServers() {
  27545. proxy_mock_.stop();
  27546. target_.stop();
  27547. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27548. if (target_thread_.joinable()) { target_thread_.join(); }
  27549. }
  27550. Server &proxy_mock() { return proxy_mock_; }
  27551. Server &target() { return target_; }
  27552. int proxy_port() const { return proxy_port_; }
  27553. int target_port() const { return target_port_; }
  27554. int proxy_hits() const { return proxy_hits_.load(); }
  27555. int target_hits() const { return target_hits_.load(); }
  27556. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27557. void reset_counters() {
  27558. proxy_hits_ = 0;
  27559. target_hits_ = 0;
  27560. last_had_proxy_authz_ = false;
  27561. }
  27562. private:
  27563. Server proxy_mock_;
  27564. Server target_;
  27565. std::thread proxy_thread_;
  27566. std::thread target_thread_;
  27567. int proxy_port_ = 0;
  27568. int target_port_ = 0;
  27569. std::atomic<int> proxy_hits_{0};
  27570. std::atomic<int> target_hits_{0};
  27571. std::atomic<bool> last_had_proxy_authz_{false};
  27572. };
  27573. inline std::unique_ptr<Client> make_client(const std::string &host,
  27574. ProxyAndTargetServers &s) {
  27575. auto cli = detail::make_unique<Client>(host, s.target_port());
  27576. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27577. cli->set_proxy("127.0.0.1", s.proxy_port());
  27578. return cli;
  27579. }
  27580. } // namespace no_proxy_test
  27581. using no_proxy_test::make_client;
  27582. using no_proxy_test::ProxyAndTargetServers;
  27583. // A stream request carries the credentials a buffered request does
  27584. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27585. no_proxy_test::ScopedServer origin;
  27586. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27587. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27588. });
  27589. origin.listen();
  27590. Client cli("127.0.0.1", origin.port());
  27591. cli.set_basic_auth("user", "pass");
  27592. auto handle = cli.open_stream("GET", "/x");
  27593. ASSERT_TRUE(handle.is_valid());
  27594. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27595. Client bearer("127.0.0.1", origin.port());
  27596. bearer.set_bearer_token_auth("tok");
  27597. auto handle2 = bearer.open_stream("GET", "/x");
  27598. ASSERT_TRUE(handle2.is_valid());
  27599. EXPECT_EQ("Bearer tok", read_all(handle2));
  27600. }
  27601. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27602. // takes its own credentials, as for a buffered request
  27603. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27604. std::string target, authz, proxy_authz;
  27605. no_proxy_test::ScopedServer proxy;
  27606. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27607. target = req.target;
  27608. authz = req.get_header_value("Authorization");
  27609. proxy_authz = req.get_header_value("Proxy-Authorization");
  27610. res.set_content("ok", "text/plain");
  27611. });
  27612. proxy.listen();
  27613. Client cli("origin.example", 8080);
  27614. cli.set_proxy("127.0.0.1", proxy.port());
  27615. cli.set_proxy_basic_auth("puser", "ppass");
  27616. cli.set_basic_auth("user", "pass");
  27617. auto handle = cli.open_stream("GET", "/x");
  27618. ASSERT_TRUE(handle.is_valid());
  27619. EXPECT_EQ("ok", read_all(handle));
  27620. EXPECT_EQ("http://origin.example:8080/x", target);
  27621. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27622. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27623. }
  27624. // In absolute-form the path follows the authority, so a path that does not
  27625. // begin with '/' would make the proxy connect to another host
  27626. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27627. std::vector<std::string> targets;
  27628. no_proxy_test::ScopedServer proxy;
  27629. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27630. targets.push_back(req.target);
  27631. res.set_content("ok", "text/plain");
  27632. });
  27633. proxy.listen();
  27634. Client cli("origin.example", 8080);
  27635. cli.set_proxy("127.0.0.1", proxy.port());
  27636. cli.set_basic_auth("user", "pass");
  27637. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27638. auto res = cli.Get(path);
  27639. EXPECT_FALSE(res) << path;
  27640. auto handle = cli.open_stream("GET", path);
  27641. EXPECT_FALSE(handle.is_valid()) << path;
  27642. }
  27643. EXPECT_TRUE(targets.empty());
  27644. auto res = cli.Get("/x");
  27645. ASSERT_TRUE(res);
  27646. ASSERT_EQ(1u, targets.size());
  27647. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27648. }
  27649. TEST(NoProxyTest, ExactHostnameBypasses) {
  27650. ProxyAndTargetServers s;
  27651. auto cli = make_client("example.com", s);
  27652. cli->set_no_proxy({"example.com"});
  27653. auto res = cli->Get("/");
  27654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27655. EXPECT_EQ(0, s.proxy_hits());
  27656. EXPECT_EQ(1, s.target_hits());
  27657. }
  27658. TEST(NoProxyTest, SubdomainBypasses) {
  27659. ProxyAndTargetServers s;
  27660. auto cli = make_client("foo.example.com", s);
  27661. cli->set_no_proxy({"example.com"});
  27662. auto res = cli->Get("/");
  27663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27664. EXPECT_EQ(0, s.proxy_hits());
  27665. EXPECT_EQ(1, s.target_hits());
  27666. }
  27667. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27668. // Regression guard: "evilexample.com" must not be considered a subdomain
  27669. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27670. // check would let traffic bypass the proxy and leak credentials direct
  27671. // to the attacker host.
  27672. ProxyAndTargetServers s;
  27673. auto cli = make_client("evilexample.com", s);
  27674. cli->set_no_proxy({"example.com"});
  27675. auto res = cli->Get("/");
  27676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27677. EXPECT_GE(s.proxy_hits(), 1);
  27678. EXPECT_EQ(0, s.target_hits());
  27679. }
  27680. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27681. ProxyAndTargetServers s;
  27682. auto cli = make_client("example.com.evil.com", s);
  27683. cli->set_no_proxy({"example.com"});
  27684. auto res = cli->Get("/");
  27685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27686. EXPECT_GE(s.proxy_hits(), 1);
  27687. EXPECT_EQ(0, s.target_hits());
  27688. }
  27689. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27690. ProxyAndTargetServers s;
  27691. auto cli = make_client("example.com", s);
  27692. cli->set_no_proxy({".example.com"});
  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, CaseInsensitiveHostname) {
  27699. ProxyAndTargetServers s;
  27700. auto cli = make_client("Example.COM", s);
  27701. cli->set_no_proxy({"EXAMPLE.com"});
  27702. auto res = cli->Get("/");
  27703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27704. EXPECT_EQ(0, s.proxy_hits());
  27705. EXPECT_EQ(1, s.target_hits());
  27706. }
  27707. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27708. ProxyAndTargetServers s;
  27709. auto cli = make_client("example.com.", s);
  27710. cli->set_no_proxy({"example.com"});
  27711. auto res = cli->Get("/");
  27712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27713. EXPECT_EQ(0, s.proxy_hits());
  27714. EXPECT_EQ(1, s.target_hits());
  27715. }
  27716. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27717. // Trailing dots must be normalized on BOTH sides — host and entry.
  27718. // An implementation that only strips the host-side trailing dot would
  27719. // fail to match host "example.com" against entry "example.com." because
  27720. // a literal substring search would compare 11 chars against 12.
  27721. ProxyAndTargetServers s;
  27722. auto cli = make_client("example.com", s);
  27723. cli->set_no_proxy({"example.com."});
  27724. auto res = cli->Get("/");
  27725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27726. EXPECT_EQ(0, s.proxy_hits());
  27727. EXPECT_EQ(1, s.target_hits());
  27728. }
  27729. TEST(NoProxyTest, WildcardBypassesEverything) {
  27730. ProxyAndTargetServers s;
  27731. auto cli = make_client("anything.invalid.test", s);
  27732. cli->set_no_proxy({"*"});
  27733. auto res = cli->Get("/");
  27734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27735. EXPECT_EQ(0, s.proxy_hits());
  27736. EXPECT_EQ(1, s.target_hits());
  27737. }
  27738. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27739. ProxyAndTargetServers s;
  27740. Client cli("127.0.0.1", s.target_port());
  27741. cli.set_proxy("127.0.0.1", s.proxy_port());
  27742. cli.set_no_proxy({"127.0.0.1"});
  27743. auto res = cli.Get("/");
  27744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27745. EXPECT_EQ(0, s.proxy_hits());
  27746. EXPECT_EQ(1, s.target_hits());
  27747. }
  27748. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27749. ProxyAndTargetServers s;
  27750. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27751. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27752. cli.set_proxy("127.0.0.1", s.proxy_port());
  27753. cli.set_no_proxy({"::1"});
  27754. auto res = cli.Get("/");
  27755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27756. EXPECT_EQ(0, s.proxy_hits());
  27757. EXPECT_EQ(1, s.target_hits());
  27758. }
  27759. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27760. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27761. // must still be recognized as IPv6 for CIDR matching. Implementations
  27762. // that detect IPv6 only when the host begins with '[' would parse the
  27763. // host as a hostname and miss the match.
  27764. ProxyAndTargetServers s;
  27765. Client cli("fe80::1", s.target_port());
  27766. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27767. cli.set_proxy("127.0.0.1", s.proxy_port());
  27768. cli.set_no_proxy({"fe80::/10"});
  27769. auto res = cli.Get("/");
  27770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27771. EXPECT_EQ(0, s.proxy_hits());
  27772. EXPECT_EQ(1, s.target_hits());
  27773. }
  27774. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27775. ProxyAndTargetServers s;
  27776. Client cli("::1", s.target_port());
  27777. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27778. cli.set_proxy("127.0.0.1", s.proxy_port());
  27779. cli.set_no_proxy({"[::1]"});
  27780. auto res = cli.Get("/");
  27781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27782. EXPECT_EQ(0, s.proxy_hits());
  27783. EXPECT_EQ(1, s.target_hits());
  27784. }
  27785. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27786. ProxyAndTargetServers s;
  27787. Client cli("fe80::1", s.target_port());
  27788. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27789. cli.set_proxy("127.0.0.1", s.proxy_port());
  27790. cli.set_no_proxy({"[fe80::]/10"});
  27791. auto res = cli.Get("/");
  27792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27793. EXPECT_EQ(0, s.proxy_hits());
  27794. EXPECT_EQ(1, s.target_hits());
  27795. }
  27796. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27797. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27798. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27799. // tricks via address-family conversion.
  27800. ProxyAndTargetServers s;
  27801. Client cli("::ffff:127.0.0.1", s.target_port());
  27802. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27803. cli.set_proxy("127.0.0.1", s.proxy_port());
  27804. cli.set_no_proxy({"127.0.0.1"});
  27805. auto res = cli.Get("/");
  27806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27807. EXPECT_GE(s.proxy_hits(), 1);
  27808. EXPECT_EQ(0, s.target_hits());
  27809. }
  27810. TEST(NoProxyTest, IPv4CidrMatch) {
  27811. ProxyAndTargetServers s;
  27812. Client cli("127.0.0.1", s.target_port());
  27813. cli.set_proxy("127.0.0.1", s.proxy_port());
  27814. cli.set_no_proxy({"127.0.0.0/8"});
  27815. auto res = cli.Get("/");
  27816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27817. EXPECT_EQ(0, s.proxy_hits());
  27818. EXPECT_EQ(1, s.target_hits());
  27819. }
  27820. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27821. ProxyAndTargetServers s;
  27822. Client cli("127.0.0.1", s.target_port());
  27823. cli.set_proxy("127.0.0.1", s.proxy_port());
  27824. cli.set_no_proxy({"10.0.0.0/8"});
  27825. auto res = cli.Get("/");
  27826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27827. EXPECT_GE(s.proxy_hits(), 1);
  27828. EXPECT_EQ(0, s.target_hits());
  27829. }
  27830. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27831. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27832. // IPv4 target matches.
  27833. ProxyAndTargetServers s;
  27834. Client cli("127.0.0.1", s.target_port());
  27835. cli.set_proxy("127.0.0.1", s.proxy_port());
  27836. cli.set_no_proxy({"0.0.0.0/0"});
  27837. auto res = cli.Get("/");
  27838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27839. EXPECT_EQ(0, s.proxy_hits());
  27840. EXPECT_EQ(1, s.target_hits());
  27841. }
  27842. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27843. ProxyAndTargetServers s;
  27844. Client cli("127.0.0.1", s.target_port());
  27845. cli.set_proxy("127.0.0.1", s.proxy_port());
  27846. cli.set_no_proxy({"127.0.0.1"});
  27847. auto res = cli.Get("/");
  27848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27849. EXPECT_EQ(0, s.proxy_hits());
  27850. EXPECT_EQ(1, s.target_hits());
  27851. }
  27852. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27853. ProxyAndTargetServers s;
  27854. Client cli("127.0.0.1", s.target_port());
  27855. cli.set_proxy("127.0.0.1", s.proxy_port());
  27856. cli.set_no_proxy({"127.0.0.0/33"});
  27857. auto res = cli.Get("/");
  27858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27859. EXPECT_GE(s.proxy_hits(), 1);
  27860. EXPECT_EQ(0, s.target_hits());
  27861. }
  27862. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27863. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27864. ProxyAndTargetServers s;
  27865. Client cli("127.0.0.1", s.target_port());
  27866. cli.set_proxy("127.0.0.1", s.proxy_port());
  27867. cli.set_no_proxy({"127.0.0.1/"});
  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, ProxyAuthorizationSuppressedWhenBypassed) {
  27874. ProxyAndTargetServers s;
  27875. auto cli = make_client("internal.corp", s);
  27876. cli->set_proxy_basic_auth("u", "p");
  27877. cli->set_no_proxy({"internal.corp"});
  27878. auto res = cli->Get("/");
  27879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27880. EXPECT_EQ(1, s.target_hits());
  27881. EXPECT_EQ(0, s.proxy_hits());
  27882. EXPECT_FALSE(s.last_had_proxy_authz())
  27883. << "Proxy-Authorization must not be sent direct to the target";
  27884. }
  27885. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27886. ProxyAndTargetServers s;
  27887. auto cli = make_client("public.example", s);
  27888. cli->set_proxy_basic_auth("u", "p");
  27889. cli->set_no_proxy({"internal.corp"}); // does not match
  27890. auto res = cli->Get("/");
  27891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27892. EXPECT_GE(s.proxy_hits(), 1);
  27893. EXPECT_TRUE(s.last_had_proxy_authz());
  27894. }
  27895. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27896. std::atomic<int> hits{0};
  27897. std::atomic<int> hits_with_authz{0};
  27898. no_proxy_test::ScopedServer proxy_mock;
  27899. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27900. hits++;
  27901. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27902. if (req.target.find("/redir") != std::string::npos) {
  27903. res.set_redirect("http://other.example/landed");
  27904. } else {
  27905. res.set_content("via-proxy", "text/plain");
  27906. }
  27907. });
  27908. proxy_mock.listen();
  27909. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27910. hits = 0;
  27911. hits_with_authz = 0;
  27912. Client cli("public.example", 80);
  27913. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27914. cli.set_proxy_basic_auth(c.first, c.second);
  27915. cli.set_follow_location(true);
  27916. // The redirect to another host goes through the proxy as well
  27917. auto res = cli.Get("/redir");
  27918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27919. EXPECT_EQ(2, hits.load());
  27920. EXPECT_EQ(2, hits_with_authz.load());
  27921. }
  27922. }
  27923. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27924. ProxyAndTargetServers s;
  27925. auto cli = make_client("anything.test", s);
  27926. auto res = cli->Get("/");
  27927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27928. EXPECT_GE(s.proxy_hits(), 1);
  27929. EXPECT_EQ(0, s.target_hits());
  27930. }
  27931. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27932. ProxyAndTargetServers s;
  27933. auto cli = make_client("example.com", s);
  27934. cli->set_no_proxy({"example.com:8080"});
  27935. auto res = cli->Get("/");
  27936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27937. EXPECT_GE(s.proxy_hits(), 1);
  27938. EXPECT_EQ(0, s.target_hits());
  27939. }
  27940. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27941. ProxyAndTargetServers s;
  27942. auto cli = make_client("anything.test", s);
  27943. cli->set_no_proxy({"", " ", "\t"});
  27944. auto res = cli->Get("/");
  27945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27946. EXPECT_GE(s.proxy_hits(), 1);
  27947. EXPECT_EQ(0, s.target_hits());
  27948. }
  27949. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27950. // An entry with leading/trailing whitespace must still match — env-style
  27951. // values are commonly pasted with stray spaces and an implementation
  27952. // that feeds the raw token directly to inet_pton would fail to match
  27953. // valid CIDRs because of the spaces.
  27954. ProxyAndTargetServers s;
  27955. Client cli("127.0.0.1", s.target_port());
  27956. cli.set_proxy("127.0.0.1", s.proxy_port());
  27957. cli.set_no_proxy({" 127.0.0.0/8 "});
  27958. auto res = cli.Get("/");
  27959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27960. EXPECT_EQ(0, s.proxy_hits());
  27961. EXPECT_EQ(1, s.target_hits());
  27962. }
  27963. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27964. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27965. // go direct and must NOT carry Proxy-Authorization.
  27966. std::atomic<int> proxy_hits{0};
  27967. std::atomic<int> target_hits{0};
  27968. std::atomic<bool> target_saw_authz{false};
  27969. no_proxy_test::ScopedServer proxy_mock, target;
  27970. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27971. proxy_hits++;
  27972. res.status = 302;
  27973. res.set_header("Location", "http://127.0.0.1:" +
  27974. std::to_string(target.port()) + "/landed");
  27975. });
  27976. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27977. target_hits++;
  27978. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27979. res.set_content("direct", "text/plain");
  27980. });
  27981. proxy_mock.listen();
  27982. target.listen();
  27983. Client cli("public.example", target.port());
  27984. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27985. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27986. cli.set_proxy_basic_auth("u", "p");
  27987. cli.set_no_proxy({"127.0.0.1"});
  27988. cli.set_follow_location(true);
  27989. auto res = cli.Get("/redir");
  27990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27991. EXPECT_GE(proxy_hits.load(), 1);
  27992. EXPECT_GE(target_hits.load(), 1);
  27993. EXPECT_FALSE(target_saw_authz.load());
  27994. }
  27995. #ifdef CPPHTTPLIB_SSL_ENABLED
  27996. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27997. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27998. // proxy creds would be sent to the (possibly hostile) origin.
  27999. std::atomic<int> target_hits{0};
  28000. std::atomic<bool> target_saw_proxy_authz{false};
  28001. no_proxy_test::ScopedServer target;
  28002. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28003. target_hits++;
  28004. if (req.has_header("Proxy-Authorization")) {
  28005. target_saw_proxy_authz = true;
  28006. }
  28007. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28008. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28009. "nonce=\"abc\", algorithm=MD5");
  28010. });
  28011. target.listen();
  28012. // The proxy address is set to the target's port: the bypass MUST kick in;
  28013. // if it doesn't, the test still routes "via proxy" to the same server and
  28014. // the Proxy-Authorization assertion below catches the leak.
  28015. Client cli("evil.example", target.port());
  28016. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28017. cli.set_proxy("127.0.0.1", target.port());
  28018. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28019. cli.set_no_proxy({"evil.example"});
  28020. auto res = cli.Get("/x");
  28021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28022. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28023. EXPECT_EQ(1, target_hits.load());
  28024. EXPECT_FALSE(target_saw_proxy_authz.load());
  28025. }
  28026. #endif
  28027. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28028. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28029. std::atomic<int> proxy_hits{0};
  28030. std::atomic<int> bypass_hits{0};
  28031. std::atomic<bool> proxy_saw_c_url{false};
  28032. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28033. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28034. proxy_hits++;
  28035. if (req.path.find("/start") != std::string::npos) {
  28036. res.status = 302;
  28037. res.set_header("Location", "http://127.0.0.1:" +
  28038. std::to_string(bypass_server.port()) +
  28039. "/middle");
  28040. return;
  28041. }
  28042. if (req.path.find("/end") != std::string::npos) {
  28043. proxy_saw_c_url = true;
  28044. res.set_content("c-via-proxy", "text/plain");
  28045. return;
  28046. }
  28047. res.set_content("unexpected", "text/plain");
  28048. });
  28049. // public.example's "advertised" port is arbitrary (the request never lands
  28050. // there — it goes through the proxy), but use a dynamic value to stay
  28051. // friendly with sharded parallel runs.
  28052. int public_port = bypass_server.port();
  28053. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28054. bypass_hits++;
  28055. res.status = 302;
  28056. res.set_header("Location", "http://public.example:" +
  28057. std::to_string(public_port) + "/end");
  28058. });
  28059. proxy_mock.listen();
  28060. bypass_server.listen();
  28061. Client cli("public.example", public_port);
  28062. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28063. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28064. cli.set_no_proxy({"127.0.0.1"});
  28065. cli.set_follow_location(true);
  28066. auto res = cli.Get("/start");
  28067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28068. EXPECT_EQ(StatusCode::OK_200, res->status);
  28069. EXPECT_EQ("c-via-proxy", res->body);
  28070. EXPECT_GE(proxy_hits.load(), 2);
  28071. EXPECT_GE(bypass_hits.load(), 1);
  28072. EXPECT_TRUE(proxy_saw_c_url.load());
  28073. }
  28074. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28075. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28076. // request reconnects to the correct endpoint.
  28077. std::atomic<int> proxy_hits{0};
  28078. std::atomic<int> target_hits{0};
  28079. no_proxy_test::ScopedServer proxy_mock, target;
  28080. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28081. proxy_hits++;
  28082. res.set_content("via-proxy", "text/plain");
  28083. });
  28084. target.svr().Get(".*", [&](const Request &, Response &res) {
  28085. target_hits++;
  28086. res.set_content("direct", "text/plain");
  28087. });
  28088. proxy_mock.listen();
  28089. target.listen();
  28090. Client cli("public.example", target.port());
  28091. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28092. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28093. cli.set_keep_alive(true);
  28094. auto res1 = cli.Get("/a");
  28095. ASSERT_TRUE(res1);
  28096. EXPECT_EQ("via-proxy", res1->body);
  28097. EXPECT_EQ(1, proxy_hits.load());
  28098. EXPECT_EQ(0, target_hits.load());
  28099. cli.set_no_proxy({"public.example"});
  28100. auto res2 = cli.Get("/b");
  28101. ASSERT_TRUE(res2);
  28102. EXPECT_EQ("direct", res2->body);
  28103. EXPECT_EQ(1, proxy_hits.load());
  28104. EXPECT_EQ(1, target_hits.load());
  28105. }
  28106. // Forward declarations (see the base64_encode note).
  28107. namespace httplib {
  28108. namespace detail {
  28109. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28110. int shutdown_socket(socket_t sock) noexcept;
  28111. } // namespace detail
  28112. } // namespace httplib
  28113. namespace proxy_tunnel_test {
  28114. const char *const kTunnelEstablished =
  28115. "HTTP/1.1 200 Connection established\r\n\r\n";
  28116. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28117. using ConnectReply = std::function<std::string(const std::string &head)>;
  28118. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28119. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28120. class ScopedConnectProxy {
  28121. public:
  28122. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28123. : forward_port_(forward_port), reply_(std::move(reply)) {
  28124. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28125. if (listen_sock_ == INVALID_SOCKET) { return; }
  28126. auto a = loopback(0);
  28127. auto addr = reinterpret_cast<sockaddr *>(&a);
  28128. socklen_t alen = sizeof(a);
  28129. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28130. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28131. ::listen(listen_sock_, 4) != 0) {
  28132. return;
  28133. }
  28134. port_ = ntohs(a.sin_port);
  28135. th_ = std::thread([this] { run(); });
  28136. }
  28137. ~ScopedConnectProxy() {
  28138. if (th_.joinable()) {
  28139. stop_ = true;
  28140. auto wake = connect_to(port_);
  28141. th_.join();
  28142. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28143. }
  28144. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28145. }
  28146. int port() const { return port_; }
  28147. int connect_hits() const { return connect_hits_.load(); }
  28148. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28149. std::string connect_request() const {
  28150. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28151. return connect_request_;
  28152. }
  28153. private:
  28154. static sockaddr_in loopback(int port) {
  28155. sockaddr_in a{};
  28156. a.sin_family = AF_INET;
  28157. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28158. a.sin_port = htons(static_cast<unsigned short>(port));
  28159. return a;
  28160. }
  28161. static socket_t connect_to(int port) {
  28162. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28163. if (sock == INVALID_SOCKET) { return sock; }
  28164. auto a = loopback(port);
  28165. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28166. detail::close_socket(sock);
  28167. return INVALID_SOCKET;
  28168. }
  28169. return sock;
  28170. }
  28171. static bool send_all(socket_t sock, const char *data, size_t size) {
  28172. while (size > 0) {
  28173. auto n = detail::send_socket(sock, data, size, 0);
  28174. if (n <= 0) { return false; }
  28175. data += n;
  28176. size -= static_cast<size_t>(n);
  28177. }
  28178. return true;
  28179. }
  28180. void run() {
  28181. for (;;) {
  28182. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28183. if (stop_) {
  28184. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28185. return;
  28186. }
  28187. if (client == INVALID_SOCKET) { continue; }
  28188. serve(client);
  28189. detail::close_socket(client);
  28190. }
  28191. }
  28192. void serve(socket_t client) {
  28193. std::string head;
  28194. char buf[2048];
  28195. while (head.find("\r\n\r\n") == std::string::npos) {
  28196. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28197. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28198. if (n <= 0) { return; }
  28199. head.append(buf, static_cast<size_t>(n));
  28200. }
  28201. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28202. connect_hits_++;
  28203. {
  28204. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28205. connect_request_ = head;
  28206. }
  28207. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28208. if (!send_all(client, res.data(), res.size()) ||
  28209. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28210. return;
  28211. }
  28212. auto origin = connect_to(forward_port_);
  28213. if (origin == INVALID_SOCKET) { return; }
  28214. // When either side stops, shut both down so the other pump returns too.
  28215. auto pump = [&](socket_t from, socket_t to) {
  28216. char b[8192];
  28217. for (;;) {
  28218. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28219. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28220. }
  28221. detail::shutdown_socket(client);
  28222. detail::shutdown_socket(origin);
  28223. };
  28224. std::thread up([&] { pump(client, origin); });
  28225. pump(origin, client);
  28226. up.join();
  28227. detail::close_socket(origin);
  28228. }
  28229. int forward_port_;
  28230. ConnectReply reply_;
  28231. socket_t listen_sock_ = INVALID_SOCKET;
  28232. int port_ = 0;
  28233. std::thread th_;
  28234. std::atomic<bool> stop_{false};
  28235. std::atomic<int> connect_hits_{0};
  28236. mutable std::mutex connect_request_mutex_;
  28237. std::string connect_request_;
  28238. };
  28239. } // namespace proxy_tunnel_test
  28240. #ifdef CPPHTTPLIB_SSL_ENABLED
  28241. namespace proxy_tunnel_test {
  28242. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28243. class ScopedSSLServer {
  28244. public:
  28245. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28246. port_ = svr_.bind_to_any_port("127.0.0.1");
  28247. }
  28248. ~ScopedSSLServer() {
  28249. svr_.stop();
  28250. if (th_.joinable()) { th_.join(); }
  28251. }
  28252. SSLServer &svr() { return svr_; }
  28253. int port() const { return port_; }
  28254. void listen() {
  28255. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28256. svr_.wait_until_ready();
  28257. }
  28258. private:
  28259. SSLServer svr_;
  28260. std::thread th_;
  28261. int port_ = 0;
  28262. };
  28263. // Sends one request through the CONNECT proxy to the TLS origin with a
  28264. // credential configured for each hop, and checks that each credential reaches
  28265. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28266. // origin's (every header in origin_headers) on the tunnelled request.
  28267. void CredentialsStayWithTheirHop(
  28268. const std::function<void(SSLClient &)> &set_credentials,
  28269. const std::string &scheme,
  28270. const std::vector<std::string> &origin_headers = {"Authorization"},
  28271. bool stream = false) {
  28272. std::atomic<int> origin_hits{0};
  28273. std::atomic<bool> origin_saw_proxy_authz{false};
  28274. std::atomic<bool> origin_saw_headers{false};
  28275. ScopedSSLServer origin;
  28276. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28277. origin_hits++;
  28278. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28279. origin_saw_headers =
  28280. std::all_of(origin_headers.begin(), origin_headers.end(),
  28281. [&](const std::string &h) { return req.has_header(h); });
  28282. res.set_content("ok", "text/plain");
  28283. });
  28284. origin.listen();
  28285. ScopedConnectProxy proxy(origin.port());
  28286. ASSERT_NE(0, proxy.port());
  28287. // Pinned to 127.0.0.1 for the same reason as the test below.
  28288. SSLClient cli("127.0.0.1", origin.port());
  28289. cli.enable_server_certificate_verification(false);
  28290. cli.set_proxy("127.0.0.1", proxy.port());
  28291. set_credentials(cli);
  28292. if (stream) {
  28293. auto handle = cli.open_stream("GET", "/x");
  28294. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28295. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28296. } else {
  28297. auto res = cli.Get("/x");
  28298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28299. EXPECT_EQ(StatusCode::OK_200, res->status);
  28300. }
  28301. EXPECT_EQ(1, origin_hits.load());
  28302. EXPECT_EQ(1, proxy.connect_hits());
  28303. EXPECT_TRUE(origin_saw_headers.load());
  28304. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28305. << "Proxy-Authorization must not be sent inside the tunnel";
  28306. auto connect_req = proxy.connect_request();
  28307. EXPECT_NE(std::string::npos,
  28308. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28309. for (const auto &h : origin_headers) {
  28310. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28311. << h << " must not be sent to the proxy on CONNECT";
  28312. }
  28313. }
  28314. } // namespace proxy_tunnel_test
  28315. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28316. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28317. [](SSLClient &cli) {
  28318. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28319. cli.set_basic_auth("origin-user", "origin-pass");
  28320. },
  28321. "Basic");
  28322. }
  28323. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28324. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28325. [](SSLClient &cli) {
  28326. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28327. cli.set_basic_auth("origin-user", "origin-pass");
  28328. },
  28329. "Basic", {"Authorization"}, true);
  28330. }
  28331. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28332. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28333. [](SSLClient &cli) {
  28334. cli.set_proxy_bearer_token_auth("proxy-token");
  28335. cli.set_bearer_token_auth("origin-token");
  28336. },
  28337. "Bearer");
  28338. }
  28339. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28340. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28341. [](SSLClient &cli) {
  28342. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28343. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28344. {"Cookie", "sid=origin-session"},
  28345. {"X-Api-Key", "origin-key"}});
  28346. },
  28347. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28348. }
  28349. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28350. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28351. // retry; otherwise proxy creds would be sent to the origin.
  28352. std::atomic<int> origin_hits{0};
  28353. std::atomic<bool> origin_saw_proxy_authz{false};
  28354. proxy_tunnel_test::ScopedSSLServer origin;
  28355. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28356. origin_hits++;
  28357. if (req.has_header("Proxy-Authorization")) {
  28358. origin_saw_proxy_authz = true;
  28359. }
  28360. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28361. res.set_header("Proxy-Authenticate",
  28362. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28363. "algorithm=MD5");
  28364. });
  28365. origin.listen();
  28366. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28367. ASSERT_NE(0, proxy.port());
  28368. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28369. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28370. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28371. // and answer with its own status, making this test flaky.
  28372. SSLClient cli("127.0.0.1", origin.port());
  28373. cli.enable_server_certificate_verification(false);
  28374. cli.set_proxy("127.0.0.1", proxy.port());
  28375. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28376. auto res = cli.Get("/x");
  28377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28378. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28379. EXPECT_EQ(1, origin_hits.load());
  28380. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28381. EXPECT_EQ(1, proxy.connect_hits());
  28382. }
  28383. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28384. std::string origin_sni;
  28385. std::string origin_host;
  28386. proxy_tunnel_test::ScopedSSLServer origin;
  28387. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28388. origin_sni = req.sni();
  28389. origin_host = req.get_header_value("Host");
  28390. res.set_content("ok", "text/plain");
  28391. });
  28392. origin.listen();
  28393. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28394. ASSERT_NE(0, proxy.port());
  28395. SSLClient cli("origin.example", origin.port());
  28396. cli.enable_server_certificate_verification(false);
  28397. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28398. cli.set_proxy("127.0.0.1", proxy.port());
  28399. auto res = cli.Get("/x");
  28400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28401. EXPECT_EQ(StatusCode::OK_200, res->status);
  28402. auto port = std::to_string(origin.port());
  28403. auto target = "127.0.0.1:" + port;
  28404. auto connect_req = proxy.connect_request();
  28405. EXPECT_EQ(1, proxy.connect_hits());
  28406. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28407. EXPECT_NE(std::string::npos,
  28408. connect_req.find("\r\nHost: " + target + "\r\n"));
  28409. EXPECT_EQ("origin.example", origin_sni);
  28410. EXPECT_EQ("origin.example:" + port, origin_host);
  28411. }
  28412. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28413. proxy_tunnel_test::ScopedSSLServer origin;
  28414. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28415. res.set_content("ok", "text/plain");
  28416. });
  28417. origin.listen();
  28418. proxy_tunnel_test::ScopedConnectProxy proxy(
  28419. origin.port(), [](const std::string &head) -> std::string {
  28420. if (head.find(
  28421. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28422. std::string::npos) {
  28423. return proxy_tunnel_test::kTunnelEstablished;
  28424. }
  28425. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28426. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28427. "nonce=\"abc\", algorithm=MD5\r\n"
  28428. "Content-Length: 0\r\n\r\n";
  28429. });
  28430. ASSERT_NE(0, proxy.port());
  28431. SSLClient cli("origin.example", origin.port());
  28432. cli.enable_server_certificate_verification(false);
  28433. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28434. cli.set_proxy("127.0.0.1", proxy.port());
  28435. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28436. auto res = cli.Get("/x");
  28437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28438. EXPECT_EQ(StatusCode::OK_200, res->status);
  28439. // The retried CONNECT is the one the proxy saw last.
  28440. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28441. auto connect_req = proxy.connect_request();
  28442. EXPECT_EQ(2, proxy.connect_hits());
  28443. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28444. EXPECT_NE(std::string::npos,
  28445. connect_req.find("\r\nHost: " + target + "\r\n"));
  28446. }
  28447. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28448. proxy_tunnel_test::ScopedSSLServer origin;
  28449. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28450. res.set_content("ok", "text/plain");
  28451. });
  28452. origin.listen();
  28453. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28454. ASSERT_NE(0, proxy.port());
  28455. SSLClient cli("origin.example", origin.port());
  28456. cli.enable_server_certificate_verification(false);
  28457. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28458. cli.set_proxy("127.0.0.1", proxy.port());
  28459. auto res = cli.Get("/x");
  28460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28461. EXPECT_EQ(StatusCode::OK_200, res->status);
  28462. auto target = "origin.example:" + std::to_string(origin.port());
  28463. auto connect_req = proxy.connect_request();
  28464. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28465. EXPECT_NE(std::string::npos,
  28466. connect_req.find("\r\nHost: " + target + "\r\n"));
  28467. }
  28468. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28469. proxy_tunnel_test::ScopedSSLServer origin;
  28470. auto port = std::to_string(origin.port());
  28471. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28472. res.set_redirect("https://next.example:" + port + "/y");
  28473. });
  28474. origin.svr().Get("/y", [](const Request &, Response &res) {
  28475. res.set_content("ok", "text/plain");
  28476. });
  28477. origin.listen();
  28478. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28479. ASSERT_NE(0, proxy.port());
  28480. SSLClient cli("origin.example", origin.port());
  28481. cli.enable_server_certificate_verification(false);
  28482. cli.set_tunnel_hostname_addr_map(
  28483. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28484. cli.set_proxy("127.0.0.1", proxy.port());
  28485. cli.set_follow_location(true);
  28486. auto res = cli.Get("/x");
  28487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28488. EXPECT_EQ("ok", res->body);
  28489. // The last CONNECT is the redirect client's.
  28490. ASSERT_EQ(2, proxy.connect_hits());
  28491. auto target = "127.0.0.1:" + port;
  28492. auto connect_req = proxy.connect_request();
  28493. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28494. EXPECT_NE(std::string::npos,
  28495. connect_req.find("\r\nHost: " + target + "\r\n"));
  28496. }
  28497. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28498. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28499. std::atomic<int> origin_hits{0};
  28500. proxy_tunnel_test::ScopedSSLServer origin;
  28501. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28502. origin_hits++;
  28503. res.set_content("ok", "text/plain");
  28504. });
  28505. origin.listen();
  28506. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28507. ASSERT_NE(0, proxy.port());
  28508. SSLClient cli("127.0.0.1", origin.port());
  28509. cli.enable_server_certificate_verification(false);
  28510. cli.set_proxy("127.0.0.1", proxy.port());
  28511. cli.set_keep_alive(true);
  28512. cli.set_session_verifier(
  28513. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28514. auto res = cli.Get("/x");
  28515. EXPECT_FALSE(res);
  28516. ASSERT_FALSE(cli.is_socket_open());
  28517. res = cli.Get("/x");
  28518. EXPECT_FALSE(res);
  28519. EXPECT_EQ(2, proxy.connect_hits());
  28520. auto handle = cli.open_stream("GET", "/x");
  28521. EXPECT_FALSE(handle.is_valid());
  28522. EXPECT_EQ(3, proxy.connect_hits());
  28523. EXPECT_EQ(0, origin_hits.load());
  28524. }
  28525. #endif
  28526. namespace proxy_tunnel_test {
  28527. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28528. // anything else gets a 407 with `challenge`.
  28529. ConnectReply require_proxy_auth(const std::string &expected,
  28530. const std::string &challenge) {
  28531. return [=](const std::string &head) -> std::string {
  28532. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28533. std::string::npos) {
  28534. return kTunnelEstablished;
  28535. }
  28536. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28537. "Proxy-Authenticate: " +
  28538. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28539. };
  28540. }
  28541. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28542. // request, then echoes.
  28543. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28544. ws.send(
  28545. "authorization:" + req.get_header_value("Authorization") +
  28546. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28547. std::string msg;
  28548. while (ws.read(msg)) {
  28549. ws.send(msg);
  28550. }
  28551. }
  28552. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28553. class ScopedWebSocketOrigin {
  28554. public:
  28555. ScopedWebSocketOrigin() {
  28556. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28557. server_.listen();
  28558. }
  28559. int port() const { return server_.port(); }
  28560. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28561. std::string url() const {
  28562. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28563. }
  28564. private:
  28565. no_proxy_test::ScopedServer server_;
  28566. };
  28567. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28568. // passed as a constructor header, and checks that each reaches only its hop.
  28569. void WebSocketCredentialsStayWithTheirHop(
  28570. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28571. const std::string &proxy_authz, const std::string &origin_authz) {
  28572. ScopedWebSocketOrigin origin;
  28573. ScopedConnectProxy proxy(
  28574. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28575. ASSERT_NE(0, proxy.port());
  28576. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28577. client.set_proxy("127.0.0.1", proxy.port());
  28578. set_proxy_credentials(client);
  28579. auto res = client.connect();
  28580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28581. std::string msg;
  28582. ASSERT_TRUE(client.read(msg));
  28583. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28584. client.close();
  28585. EXPECT_EQ(1, proxy.connect_hits());
  28586. EXPECT_EQ(std::string::npos,
  28587. proxy.connect_request().find("\r\nAuthorization: "))
  28588. << "origin credentials must not be sent to the proxy";
  28589. }
  28590. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28591. void WebSocketSetterCredentialsStayWithTheirHop(
  28592. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28593. const std::string &proxy_authz, const std::string &origin_authz) {
  28594. ScopedWebSocketOrigin origin;
  28595. ScopedConnectProxy proxy(
  28596. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28597. ASSERT_NE(0, proxy.port());
  28598. ws::WebSocketClient client(origin.url());
  28599. client.set_proxy("127.0.0.1", proxy.port());
  28600. set_credentials(client);
  28601. auto res = client.connect();
  28602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28603. std::string msg;
  28604. ASSERT_TRUE(client.read(msg));
  28605. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28606. client.close();
  28607. EXPECT_EQ(1, proxy.connect_hits());
  28608. EXPECT_EQ(std::string::npos,
  28609. proxy.connect_request().find("\r\nAuthorization: "))
  28610. << "origin credentials must not be sent to the proxy";
  28611. }
  28612. } // namespace proxy_tunnel_test
  28613. namespace {
  28614. // Connects `client` and returns the Authorization header its upgrade
  28615. // request carried, or "<failed>" when the connection could not be opened.
  28616. std::string websocket_authorization(ws::WebSocketClient &client) {
  28617. if (!client.connect()) { return "<failed>"; }
  28618. std::string msg;
  28619. if (!client.read(msg)) { return "<failed>"; }
  28620. client.close();
  28621. auto prefix = std::string("authorization:");
  28622. auto end = msg.find("|proxy-authorization:");
  28623. return msg.substr(prefix.size(), end - prefix.size());
  28624. }
  28625. } // namespace
  28626. TEST(WebSocketClientAuthTest, BasicAuth) {
  28627. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28628. ws::WebSocketClient client(origin.url());
  28629. client.set_basic_auth("user", "pass");
  28630. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28631. websocket_authorization(client));
  28632. }
  28633. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28634. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28635. ws::WebSocketClient client(origin.url());
  28636. client.set_basic_auth("user", "");
  28637. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28638. websocket_authorization(client));
  28639. }
  28640. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28641. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28642. ws::WebSocketClient client(origin.url());
  28643. client.set_bearer_token_auth("token123");
  28644. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28645. }
  28646. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28647. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28648. ws::WebSocketClient client(origin.url());
  28649. client.set_bearer_token_auth("token123");
  28650. client.set_basic_auth("user", "pass");
  28651. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28652. websocket_authorization(client));
  28653. }
  28654. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28655. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28656. ws::WebSocketClient client(origin.url(),
  28657. {{"Authorization", "Bearer from-header"}});
  28658. client.set_bearer_token_auth("from-setter");
  28659. client.set_basic_auth("user", "pass");
  28660. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28661. }
  28662. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28663. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28664. ws::WebSocketClient client(origin.url());
  28665. EXPECT_EQ("", websocket_authorization(client));
  28666. client.set_bearer_token_auth("first");
  28667. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28668. client.set_bearer_token_auth("second");
  28669. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28670. client.set_bearer_token_auth("");
  28671. EXPECT_EQ("", websocket_authorization(client));
  28672. }
  28673. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28674. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28675. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28676. ASSERT_NE(0, proxy.port());
  28677. ws::WebSocketClient client(origin.url());
  28678. client.set_proxy("127.0.0.1", proxy.port());
  28679. auto res = client.connect();
  28680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28681. std::string msg;
  28682. ASSERT_TRUE(client.read(msg));
  28683. ASSERT_TRUE(client.send("hello"));
  28684. ASSERT_TRUE(client.read(msg));
  28685. EXPECT_EQ("hello", msg);
  28686. client.close();
  28687. EXPECT_EQ(1, proxy.connect_hits());
  28688. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28689. auto connect_req = proxy.connect_request();
  28690. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28691. EXPECT_NE(std::string::npos,
  28692. connect_req.find("\r\nHost: " + target + "\r\n"));
  28693. }
  28694. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28695. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28696. [](ws::WebSocketClient &cli) {
  28697. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28698. },
  28699. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28700. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28701. }
  28702. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28703. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28704. [](ws::WebSocketClient &cli) {
  28705. cli.set_proxy_bearer_token_auth("proxy-token");
  28706. },
  28707. "Bearer proxy-token", "Bearer origin-token");
  28708. }
  28709. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28710. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28711. [](ws::WebSocketClient &cli) {
  28712. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28713. cli.set_basic_auth("origin-user", "origin-pass");
  28714. },
  28715. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28716. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28717. }
  28718. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28719. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28720. [](ws::WebSocketClient &cli) {
  28721. cli.set_proxy_bearer_token_auth("proxy-token");
  28722. cli.set_bearer_token_auth("origin-token");
  28723. },
  28724. "Bearer proxy-token", "Bearer origin-token");
  28725. }
  28726. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28727. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28728. proxy_tunnel_test::ScopedConnectProxy proxy(
  28729. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28730. "Basic " + detail::base64_encode("proxy-user:"),
  28731. "Basic realm=\"proxy\""));
  28732. ASSERT_NE(0, proxy.port());
  28733. ws::WebSocketClient client(origin.url());
  28734. client.set_proxy("127.0.0.1", proxy.port());
  28735. client.set_proxy_basic_auth("proxy-user", "");
  28736. auto res = client.connect();
  28737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28738. client.close();
  28739. EXPECT_EQ(1, proxy.connect_hits());
  28740. }
  28741. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28742. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28743. proxy_tunnel_test::ScopedConnectProxy proxy(
  28744. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28745. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28746. ASSERT_NE(0, proxy.port());
  28747. ws::WebSocketClient client(origin.url());
  28748. client.set_proxy("127.0.0.1", proxy.port());
  28749. auto res = client.connect();
  28750. EXPECT_FALSE(res);
  28751. EXPECT_EQ(Error::ProxyConnection, res.error());
  28752. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28753. EXPECT_EQ("Basic realm=\"proxy\"",
  28754. res.get_header_value("Proxy-Authenticate"));
  28755. EXPECT_FALSE(client.is_open());
  28756. }
  28757. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28758. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28759. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28760. ASSERT_NE(0, proxy.port());
  28761. ws::WebSocketClient client(origin.url());
  28762. client.set_proxy("127.0.0.1", proxy.port());
  28763. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28764. client.set_no_proxy({"127.0.0.1"});
  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. << "proxy credentials must not reach a bypassed origin";
  28771. client.close();
  28772. EXPECT_EQ(0, proxy.connect_hits());
  28773. }
  28774. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28775. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28776. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28777. ASSERT_NE(0, proxy.port());
  28778. ws::WebSocketClient client(origin.url());
  28779. client.set_proxy("127.0.0.1", proxy.port());
  28780. ASSERT_TRUE(client.connect());
  28781. ASSERT_TRUE(client.connect());
  28782. client.close();
  28783. EXPECT_EQ(2, proxy.connect_hits());
  28784. }
  28785. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28786. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28787. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28788. ASSERT_NE(0, proxy.port());
  28789. auto port = std::to_string(origin.port());
  28790. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28791. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28792. client.set_proxy("127.0.0.1", proxy.port());
  28793. auto res = client.connect();
  28794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28795. std::string msg;
  28796. ASSERT_TRUE(client.read(msg));
  28797. client.close();
  28798. EXPECT_EQ(1, proxy.connect_hits());
  28799. auto target = "127.0.0.1:" + port;
  28800. auto connect_req = proxy.connect_request();
  28801. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28802. EXPECT_NE(std::string::npos,
  28803. connect_req.find("\r\nHost: " + target + "\r\n"));
  28804. }
  28805. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28806. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28807. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28808. ASSERT_NE(0, proxy.port());
  28809. auto port = std::to_string(origin.port());
  28810. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28811. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28812. client.set_proxy("127.0.0.1", proxy.port());
  28813. auto res = client.connect();
  28814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28815. client.close();
  28816. auto target = "origin.example:" + port;
  28817. auto connect_req = proxy.connect_request();
  28818. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28819. EXPECT_NE(std::string::npos,
  28820. connect_req.find("\r\nHost: " + target + "\r\n"));
  28821. }
  28822. #ifdef CPPHTTPLIB_SSL_ENABLED
  28823. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28824. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28825. proxy_tunnel_test::ScopedConnectProxy proxy(
  28826. origin.port(), [](const std::string &head) -> std::string {
  28827. if (head.find(
  28828. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28829. std::string::npos) {
  28830. return proxy_tunnel_test::kTunnelEstablished;
  28831. }
  28832. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28833. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28834. "nonce=\"abc\", algorithm=MD5\r\n"
  28835. "Content-Length: 0\r\n\r\n";
  28836. });
  28837. ASSERT_NE(0, proxy.port());
  28838. ws::WebSocketClient client(origin.url());
  28839. client.set_proxy("127.0.0.1", proxy.port());
  28840. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28841. auto res = client.connect();
  28842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28843. std::string msg;
  28844. ASSERT_TRUE(client.read(msg));
  28845. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28846. client.close();
  28847. EXPECT_EQ(2, proxy.connect_hits());
  28848. }
  28849. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28850. proxy_tunnel_test::ScopedSSLServer origin;
  28851. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28852. origin.listen();
  28853. proxy_tunnel_test::ScopedConnectProxy proxy(
  28854. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28855. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28856. ASSERT_NE(0, proxy.port());
  28857. ws::WebSocketClient client(
  28858. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28859. client.enable_server_certificate_verification(false);
  28860. client.set_proxy("127.0.0.1", proxy.port());
  28861. client.set_proxy_bearer_token_auth("proxy-token");
  28862. auto res = client.connect();
  28863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28864. std::string msg;
  28865. ASSERT_TRUE(client.read(msg));
  28866. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28867. << "Proxy-Authorization must not be sent inside the tunnel";
  28868. client.close();
  28869. EXPECT_EQ(1, proxy.connect_hits());
  28870. }
  28871. #endif
  28872. // ---------------------------------------------------------------------------
  28873. // Poller
  28874. // ---------------------------------------------------------------------------
  28875. namespace poller_test {
  28876. struct PollerBackend {
  28877. const char *name;
  28878. std::unique_ptr<detail::Poller> (*create)();
  28879. };
  28880. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28881. *os << backend.name;
  28882. }
  28883. // Every backend runs the same contract tests. A new one is added here only.
  28884. std::vector<PollerBackend> poller_backends() {
  28885. return {
  28886. {"poll", &detail::PollPoller::create},
  28887. #ifdef __linux__
  28888. {"epoll", &detail::EpollPoller::create},
  28889. #endif
  28890. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28891. {"kqueue", &detail::KqueuePoller::create},
  28892. #endif
  28893. };
  28894. }
  28895. // A descriptor whose readability the test controls.
  28896. struct TestSocketPair {
  28897. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28898. TestSocketPair() { detail::create_socket_pair(fd); }
  28899. ~TestSocketPair() {
  28900. for (auto s : fd) {
  28901. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28902. }
  28903. }
  28904. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28905. socket_t reader() const { return fd[0]; }
  28906. void make_readable() {
  28907. const char c = 1;
  28908. detail::send_socket(fd[1], &c, 1, 0);
  28909. }
  28910. void close_writer() {
  28911. detail::close_socket(fd[1]);
  28912. fd[1] = INVALID_SOCKET;
  28913. }
  28914. };
  28915. using Tokens = std::vector<detail::Poller::Token>;
  28916. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28917. protected:
  28918. void SetUp() override {
  28919. poller_ = GetParam().create();
  28920. ASSERT_TRUE(poller_ != nullptr);
  28921. }
  28922. Tokens wait_for(int timeout_ms) {
  28923. Tokens ready;
  28924. poller_->wait(timeout_ms, ready);
  28925. std::sort(ready.begin(), ready.end());
  28926. return ready;
  28927. }
  28928. std::unique_ptr<detail::Poller> poller_;
  28929. };
  28930. } // namespace poller_test
  28931. using poller_test::PollerTest;
  28932. using poller_test::TestSocketPair;
  28933. using poller_test::Tokens;
  28934. INSTANTIATE_TEST_SUITE_P(
  28935. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28936. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28937. return std::string(p.param.name);
  28938. });
  28939. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28940. TestSocketPair sp;
  28941. ASSERT_TRUE(sp.ok());
  28942. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28943. EXPECT_EQ(Tokens{}, wait_for(0));
  28944. sp.make_readable();
  28945. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28946. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28947. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28948. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28949. }
  28950. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28951. TestSocketPair sp;
  28952. ASSERT_TRUE(sp.ok());
  28953. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28954. poller_->disarm(sp.reader());
  28955. poller_->disarm(sp.reader()); // disarming twice is harmless
  28956. sp.make_readable();
  28957. EXPECT_EQ(Tokens{}, wait_for(0));
  28958. }
  28959. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28960. TestSocketPair sp;
  28961. ASSERT_TRUE(sp.ok());
  28962. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28963. auto start = std::chrono::steady_clock::now();
  28964. EXPECT_EQ(Tokens{}, wait_for(30));
  28965. auto elapsed = std::chrono::steady_clock::now() - start;
  28966. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28967. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28968. }
  28969. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28970. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28971. for (detail::Poller::Token i = 0; i < 8; i++) {
  28972. sps.emplace_back(new TestSocketPair());
  28973. ASSERT_TRUE(sps.back()->ok());
  28974. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28975. }
  28976. sps[0]->make_readable();
  28977. sps[3]->make_readable();
  28978. sps[7]->make_readable();
  28979. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28980. // The others are still armed, the delivered ones are not.
  28981. sps[1]->make_readable();
  28982. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28983. EXPECT_EQ(Tokens{}, wait_for(0));
  28984. }
  28985. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28986. TestSocketPair s0, s1, s2;
  28987. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28988. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28989. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28990. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28991. // A delivery may move another entry inside the poller.
  28992. s0.make_readable();
  28993. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28994. // The entries left must still be found by descriptor.
  28995. poller_->disarm(s2.reader());
  28996. s1.make_readable();
  28997. s2.make_readable();
  28998. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28999. }
  29000. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29001. TestSocketPair sp;
  29002. ASSERT_TRUE(sp.ok());
  29003. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29004. sp.close_writer();
  29005. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29006. char c;
  29007. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29008. }
  29009. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29010. std::thread waker([&] {
  29011. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29012. poller_->wake();
  29013. });
  29014. Tokens ready;
  29015. auto start = std::chrono::steady_clock::now();
  29016. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29017. waker.join();
  29018. EXPECT_TRUE(ready.empty());
  29019. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29020. }
  29021. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29022. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29023. Tokens ready;
  29024. EXPECT_TRUE(poller_->wait(1000, ready));
  29025. }
  29026. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29027. for (int i = 0; i < 1000; i++) {
  29028. poller_->wake();
  29029. }
  29030. Tokens ready;
  29031. EXPECT_TRUE(poller_->wait(0, ready));
  29032. EXPECT_FALSE(poller_->wait(0, ready));
  29033. poller_->wake();
  29034. EXPECT_TRUE(poller_->wait(0, ready));
  29035. }
  29036. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29037. // Two threads publish changes and wake() after each, as a reactor's workers
  29038. // do. Every change must be seen without a wait() timing out. A lost wake()
  29039. // needs an unlucky interleaving, hence the rounds.
  29040. for (int round = 0; round < 5; round++) {
  29041. SCOPED_TRACE(round);
  29042. const int per_thread = 20000;
  29043. std::atomic<int> posted{0};
  29044. auto post = [&] {
  29045. for (int i = 0; i < per_thread; i++) {
  29046. posted++;
  29047. poller_->wake();
  29048. }
  29049. };
  29050. std::thread t1(post), t2(post);
  29051. auto lost = false;
  29052. Tokens ready;
  29053. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29054. if (!poller_->wait(1000, ready)) {
  29055. lost = true;
  29056. break;
  29057. }
  29058. }
  29059. t1.join();
  29060. t2.join();
  29061. ASSERT_FALSE(lost);
  29062. }
  29063. }
  29064. TEST(PollerFactoryTest, MakePollerWorks) {
  29065. auto poller = detail::make_poller();
  29066. ASSERT_TRUE(poller != nullptr);
  29067. poller->wake();
  29068. std::vector<detail::Poller::Token> ready;
  29069. EXPECT_TRUE(poller->wait(1000, ready));
  29070. }
  29071. // ---------------------------------------------------------------------------
  29072. // Keep-alive parking
  29073. // ---------------------------------------------------------------------------
  29074. namespace parking_test {
  29075. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29076. // runs once the port is bound and listening, before the server accepts.
  29077. struct RunningServer {
  29078. explicit RunningServer(
  29079. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29080. : svr_(svr) {
  29081. port = svr_.bind_to_any_port("127.0.0.1");
  29082. if (before_listen) { before_listen(port); }
  29083. thread = std::thread([this] { svr_.listen_after_bind(); });
  29084. svr_.wait_until_ready();
  29085. }
  29086. ~RunningServer() {
  29087. svr_.stop();
  29088. if (thread.joinable()) { thread.join(); }
  29089. }
  29090. Server &svr_;
  29091. int port = 0;
  29092. std::thread thread;
  29093. };
  29094. struct Sockets {
  29095. std::vector<socket_t> socks;
  29096. ~Sockets() {
  29097. for (auto s : socks) {
  29098. detail::close_socket(s);
  29099. }
  29100. }
  29101. socket_t connect(int port) {
  29102. auto error = Error::Success;
  29103. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29104. false, false, nullptr, 2, 0, 2, 0, 2,
  29105. 0, std::string(), error);
  29106. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29107. return s;
  29108. }
  29109. };
  29110. std::chrono::steady_clock::time_point in_ms(int ms) {
  29111. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29112. }
  29113. bool readable_by(socket_t sock,
  29114. std::chrono::steady_clock::time_point deadline) {
  29115. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29116. deadline - std::chrono::steady_clock::now())
  29117. .count();
  29118. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29119. }
  29120. bool send_get(socket_t sock, const std::string &path = "/") {
  29121. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29122. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29123. static_cast<ssize_t>(req.size());
  29124. }
  29125. // Reads one response whose body is "ok".
  29126. bool receives_ok(socket_t sock, int timeout_ms) {
  29127. auto deadline = in_ms(timeout_ms);
  29128. std::string buf;
  29129. while (readable_by(sock, deadline)) {
  29130. char tmp[1024];
  29131. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29132. if (n <= 0) { return false; }
  29133. buf.append(tmp, static_cast<size_t>(n));
  29134. auto end = buf.find("\r\n\r\n");
  29135. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29136. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29137. buf.compare(end + 4, 2, "ok") == 0;
  29138. }
  29139. }
  29140. return false;
  29141. }
  29142. bool get_ok(socket_t sock, int timeout_ms) {
  29143. return send_get(sock) && receives_ok(sock, timeout_ms);
  29144. }
  29145. // Whether the server closes `sock` by `deadline`.
  29146. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29147. char c;
  29148. return readable_by(sock, deadline) &&
  29149. detail::read_socket(sock, &c, 1, 0) <= 0;
  29150. }
  29151. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29152. auto deadline = in_ms(timeout_ms);
  29153. while (!cond()) {
  29154. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29155. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29156. }
  29157. return true;
  29158. }
  29159. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue,
  29160. bool parking = true) {
  29161. svr.new_task_queue = std::move(new_task_queue);
  29162. svr.set_keep_alive_parking(parking);
  29163. svr.Get("/", [](const Request &, Response &res) {
  29164. res.set_content("ok", "text/plain");
  29165. });
  29166. }
  29167. std::function<TaskQueue *(void)> threads(size_t n) {
  29168. return [n] { return new ThreadPool(n); };
  29169. }
  29170. // Counts what the event loop managed to queue, so that a test can wait for it.
  29171. class CountingTaskQueue final : public TaskQueue {
  29172. public:
  29173. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29174. std::atomic<int> &full)
  29175. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29176. bool enqueue(std::function<void()> fn) override {
  29177. auto queued = pool_.enqueue([this, fn]() {
  29178. fn();
  29179. // Holds the worker back from taking the next job.
  29180. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29181. });
  29182. (queued ? ok_ : full_)++;
  29183. return queued;
  29184. }
  29185. void shutdown() override { pool_.shutdown(); }
  29186. std::atomic<int> pause_after_ms{0};
  29187. private:
  29188. ThreadPool pool_;
  29189. std::atomic<int> &ok_;
  29190. std::atomic<int> &full_;
  29191. };
  29192. // Holds handlers until it opens, or for 3 seconds at most.
  29193. class Gate {
  29194. public:
  29195. void wait() {
  29196. std::unique_lock<std::mutex> lock(m_);
  29197. entered_++;
  29198. cv_.notify_all();
  29199. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29200. }
  29201. void open() {
  29202. std::lock_guard<std::mutex> guard(m_);
  29203. open_ = true;
  29204. cv_.notify_all();
  29205. }
  29206. int entered() {
  29207. std::lock_guard<std::mutex> guard(m_);
  29208. return entered_;
  29209. }
  29210. private:
  29211. std::mutex m_;
  29212. std::condition_variable cv_;
  29213. bool open_ = false;
  29214. int entered_ = 0;
  29215. };
  29216. } // namespace parking_test
  29217. // A connection that sends nothing is closed at the keep-alive timeout, not the
  29218. // read timeout, whether or not it is parked.
  29219. TEST(KeepAliveParkingTest, FirstRequestWaitsForTheKeepAliveTimeout) {
  29220. using namespace parking_test;
  29221. // Both modes at once, since each waits a whole second.
  29222. Server svrs[2];
  29223. std::unique_ptr<RunningServer> running[2];
  29224. Sockets socks; // after `running`, so that the sockets close first
  29225. for (auto i = 0; i < 2; i++) {
  29226. serve_ok(svrs[i], threads(1), /*parking=*/i == 0);
  29227. svrs[i].set_read_timeout(10, 0);
  29228. svrs[i].set_keep_alive_timeout(1);
  29229. running[i].reset(new RunningServer(svrs[i]));
  29230. ASSERT_NE(INVALID_SOCKET, socks.connect(running[i]->port));
  29231. }
  29232. auto early = in_ms(500);
  29233. for (size_t i = 0; i < 2; i++) {
  29234. SCOPED_TRACE(i == 0 ? "parking" : "no parking");
  29235. EXPECT_FALSE(sees_eof(socks.socks[i], early));
  29236. }
  29237. auto late = in_ms(2500);
  29238. for (size_t i = 0; i < 2; i++) {
  29239. SCOPED_TRACE(i == 0 ? "parking" : "no parking");
  29240. EXPECT_TRUE(sees_eof(socks.socks[i], late));
  29241. }
  29242. }
  29243. // Without parking, a request that arrived before stop() is still served when
  29244. // its worker gets to it.
  29245. TEST(KeepAliveParkingTest, RequestBeforeStopIsServedWithoutParking) {
  29246. using namespace parking_test;
  29247. std::atomic<int> ok{0}, full{0};
  29248. Server svr;
  29249. serve_ok(svr, [&] { return new CountingTaskQueue(1, 0, ok, full); }, false);
  29250. Gate gate;
  29251. svr.Get("/gate", [&](const Request &, Response &res) {
  29252. gate.wait();
  29253. res.set_content("ok", "text/plain");
  29254. });
  29255. RunningServer running(svr);
  29256. Sockets socks;
  29257. // Hold the only worker, and queue a connection whose request has arrived.
  29258. auto held = socks.connect(running.port);
  29259. ASSERT_TRUE(send_get(held, "/gate"));
  29260. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29261. auto waiting = socks.connect(running.port);
  29262. ASSERT_TRUE(send_get(waiting));
  29263. ASSERT_TRUE(wait_until([&] { return ok == 2; }, 2000));
  29264. svr.stop();
  29265. gate.open();
  29266. EXPECT_TRUE(receives_ok(held, 2000));
  29267. EXPECT_TRUE(receives_ok(waiting, 2000));
  29268. }
  29269. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29270. using namespace parking_test;
  29271. Server svr;
  29272. serve_ok(svr, threads(1));
  29273. RunningServer running(svr);
  29274. Sockets socks;
  29275. // One kept-alive connection that has been served, and many that have not
  29276. // sent anything yet. None of them may keep the only worker.
  29277. auto served = socks.connect(running.port);
  29278. ASSERT_TRUE(get_ok(served, 2000));
  29279. for (int i = 0; i < 49; i++) {
  29280. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29281. }
  29282. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29283. EXPECT_TRUE(get_ok(served, 1000));
  29284. }
  29285. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29286. using namespace parking_test;
  29287. Server svr;
  29288. serve_ok(svr, threads(1));
  29289. svr.set_keep_alive_timeout(1);
  29290. RunningServer running(svr);
  29291. Sockets socks;
  29292. for (int i = 0; i < 3; i++) {
  29293. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29294. }
  29295. // One worker waiting on each in turn would take about 3 seconds.
  29296. auto deadline = in_ms(2000);
  29297. for (auto s : socks.socks) {
  29298. EXPECT_TRUE(sees_eof(s, deadline));
  29299. }
  29300. }
  29301. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29302. using namespace parking_test;
  29303. std::atomic<int> queued{0}, full{0};
  29304. Server svr;
  29305. // One worker and room for one queued task.
  29306. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29307. Gate gate;
  29308. svr.Get("/block", [&](const Request &, Response &res) {
  29309. gate.wait();
  29310. res.set_content("ok", "text/plain");
  29311. });
  29312. RunningServer running(svr);
  29313. // Before the server stops, so that a failed run does not wait for the
  29314. // handler's timeout.
  29315. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29316. Sockets socks;
  29317. auto a = socks.connect(running.port);
  29318. ASSERT_TRUE(get_ok(a, 2000));
  29319. // B keeps the only worker busy.
  29320. auto b = socks.connect(running.port);
  29321. ASSERT_TRUE(send_get(b, "/block"));
  29322. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29323. // A new connection C fills the queue.
  29324. auto c = socks.connect(running.port);
  29325. ASSERT_TRUE(send_get(c));
  29326. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29327. // A's next request finds the queue full, but A has been served before, so it
  29328. // waits instead of being cut off.
  29329. ASSERT_TRUE(send_get(a));
  29330. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29331. gate.open();
  29332. EXPECT_TRUE(receives_ok(b, 2000));
  29333. EXPECT_TRUE(receives_ok(c, 2000));
  29334. EXPECT_TRUE(receives_ok(a, 2000));
  29335. }
  29336. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29337. using namespace parking_test;
  29338. std::atomic<int> queued{0}, full{0};
  29339. CountingTaskQueue *queue = nullptr;
  29340. Server svr;
  29341. // Two workers and room for one queued task.
  29342. serve_ok(svr,
  29343. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29344. Gate first, second;
  29345. svr.Get("/first", [&](const Request &, Response &res) {
  29346. first.wait();
  29347. res.set_content("ok", "text/plain");
  29348. });
  29349. svr.Get("/second", [&](const Request &, Response &res) {
  29350. second.wait();
  29351. res.set_content("ok", "text/plain");
  29352. });
  29353. RunningServer running(svr);
  29354. auto open_gates = detail::scope_exit([&] {
  29355. first.open();
  29356. second.open();
  29357. });
  29358. Sockets socks;
  29359. auto a = socks.connect(running.port);
  29360. ASSERT_TRUE(get_ok(a, 2000));
  29361. // B and D take both workers, and C fills the queue. One at a time: the
  29362. // queue has room for one job only until a worker takes it.
  29363. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29364. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29365. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29366. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29367. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29368. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29369. // A's next request waits in the backlog.
  29370. ASSERT_TRUE(send_get(a));
  29371. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29372. // B's worker finishes, then takes C off the queue only later, which makes
  29373. // room for A.
  29374. queue->pause_after_ms = 200;
  29375. first.open();
  29376. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29377. queue->pause_after_ms = 0;
  29378. second.open();
  29379. EXPECT_TRUE(receives_ok(a, 2000));
  29380. }
  29381. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29382. using namespace parking_test;
  29383. Server svr;
  29384. serve_ok(svr, threads(1));
  29385. svr.set_keep_alive_timeout(0);
  29386. // The request is on the socket before the server accepts the connection,
  29387. // so it does not race the 10 ms floor. Without the floor the connection is
  29388. // closed unread.
  29389. Sockets socks;
  29390. auto sock = INVALID_SOCKET;
  29391. RunningServer running(svr, [&](int port) {
  29392. sock = socks.connect(port);
  29393. send_get(sock);
  29394. });
  29395. EXPECT_TRUE(receives_ok(sock, 1000));
  29396. }
  29397. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29398. using namespace parking_test;
  29399. for (int round = 0; round < 5; round++) {
  29400. SCOPED_TRACE(round);
  29401. Server svr;
  29402. serve_ok(svr, threads(2));
  29403. RunningServer running(svr);
  29404. Sockets socks;
  29405. for (int i = 0; i < 20; i++) {
  29406. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29407. }
  29408. auto start = std::chrono::steady_clock::now();
  29409. svr.stop();
  29410. running.thread.join();
  29411. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29412. std::chrono::milliseconds(500));
  29413. auto deadline = in_ms(1000);
  29414. for (auto s : socks.socks) {
  29415. EXPECT_TRUE(sees_eof(s, deadline));
  29416. }
  29417. }
  29418. }
  29419. #ifdef CPPHTTPLIB_SSL_ENABLED
  29420. namespace parking_test {
  29421. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29422. // that has opened a connection ahead of time. Freeing the session sends no
  29423. // close_notify, so the connection stays quiet.
  29424. bool handshake_only(socket_t sock) {
  29425. auto ctx = tls::create_client_context();
  29426. tls::set_verify_client(ctx, false);
  29427. auto session = tls::create_session(ctx, sock);
  29428. auto se = detail::scope_exit([&] {
  29429. tls::free_session(session);
  29430. tls::free_context(ctx);
  29431. });
  29432. tls::TlsError err;
  29433. return session &&
  29434. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29435. }
  29436. Client tls_client(int port) {
  29437. Client cli("https://127.0.0.1:" + std::to_string(port));
  29438. cli.enable_server_certificate_verification(false);
  29439. cli.set_keep_alive(true);
  29440. cli.set_connection_timeout(1);
  29441. cli.set_read_timeout(1);
  29442. return cli;
  29443. }
  29444. bool tls_get_ok(Client &cli) {
  29445. auto res = cli.Get("/");
  29446. return res && res->body == "ok";
  29447. }
  29448. } // namespace parking_test
  29449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29450. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29451. struct {
  29452. unsigned long version;
  29453. bool safe;
  29454. } cases[] = {
  29455. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29456. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29457. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29458. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29459. };
  29460. for (const auto &c : cases) {
  29461. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29462. << std::hex << c.version;
  29463. }
  29464. }
  29465. #endif
  29466. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29467. using namespace parking_test;
  29468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29469. ASSERT_TRUE(svr.is_valid());
  29470. serve_ok(svr, threads(1));
  29471. svr.set_read_timeout(1); // so that a failing run does not take long
  29472. RunningServer running(svr);
  29473. Sockets socks;
  29474. // One served connection, some that have not started their handshake, and
  29475. // one that has finished it and gone quiet. None may keep the only worker.
  29476. auto served = tls_client(running.port);
  29477. ASSERT_TRUE(tls_get_ok(served));
  29478. for (int i = 0; i < 10; i++) {
  29479. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29480. }
  29481. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29482. auto other = tls_client(running.port);
  29483. EXPECT_TRUE(tls_get_ok(other));
  29484. EXPECT_TRUE(tls_get_ok(served));
  29485. }
  29486. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29487. using namespace parking_test;
  29488. for (auto parking : {true, false}) {
  29489. SCOPED_TRACE(parking ? "parking" : "no parking");
  29490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29491. ASSERT_TRUE(svr.is_valid());
  29492. serve_ok(svr, threads(1), parking);
  29493. RunningServer running(svr);
  29494. Sockets socks;
  29495. auto plain = socks.connect(running.port);
  29496. ASSERT_TRUE(send_get(plain));
  29497. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29498. EXPECT_NE(0, svr.ssl_last_error());
  29499. }
  29500. }
  29501. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29502. using namespace parking_test;
  29503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29504. ASSERT_TRUE(svr.is_valid());
  29505. serve_ok(svr, threads(2));
  29506. RunningServer running(svr);
  29507. std::vector<Client> clients;
  29508. for (int i = 0; i < 5; i++) {
  29509. clients.push_back(tls_client(running.port));
  29510. ASSERT_TRUE(tls_get_ok(clients.back()));
  29511. }
  29512. auto start = std::chrono::steady_clock::now();
  29513. svr.stop();
  29514. running.thread.join();
  29515. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29516. std::chrono::milliseconds(500));
  29517. }
  29518. #endif