test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err);
  83. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  84. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  85. void shutdown(session_t session, bool graceful);
  86. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  87. namespace impl {
  88. SecTrustSettingsResult
  89. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  90. } // namespace impl
  91. #endif
  92. } // namespace tls
  93. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  94. namespace detail {
  95. bool ssl_free_buffers_is_safe(unsigned long version);
  96. } // namespace detail
  97. #endif
  98. } // namespace httplib
  99. #endif
  100. using namespace std;
  101. using namespace httplib;
  102. const char *HOST = "localhost";
  103. static int get_base_port() {
  104. const char *shard = getenv("GTEST_SHARD_INDEX");
  105. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  106. }
  107. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  108. // New standalone tests MUST use svr.bind_to_any_port() instead.
  109. const int PORT = get_base_port();
  110. const string LONG_QUERY_VALUE = string(25000, '@');
  111. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  112. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  113. const string TOO_LONG_QUERY_URL =
  114. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  115. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  116. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  117. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  118. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  119. return file.name == key;
  120. });
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return *it;
  123. #else
  124. if (it != items.end()) { return *it; }
  125. throw std::runtime_error("invalid multipart form data name error");
  126. #endif
  127. }
  128. static void read_file(const std::string &path, std::string &out) {
  129. std::ifstream fs(path, std::ios_base::binary);
  130. if (!fs) {
  131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  132. return;
  133. #else
  134. throw std::runtime_error("File not found: " + path);
  135. #endif
  136. }
  137. fs.seekg(0, std::ios_base::end);
  138. auto size = fs.tellg();
  139. fs.seekg(0);
  140. out.resize(static_cast<size_t>(size));
  141. fs.read(&out[0], static_cast<std::streamsize>(size));
  142. }
  143. class UnixSocketTest : public ::testing::Test {
  144. protected:
  145. void TearDown() override { std::remove(pathname_.c_str()); }
  146. void client_GET(const std::string &addr) {
  147. httplib::Client cli{addr};
  148. cli.set_address_family(AF_UNIX);
  149. ASSERT_TRUE(cli.is_valid());
  150. const auto &result = cli.Get(pattern_);
  151. ASSERT_TRUE(result) << "error: " << result.error();
  152. const auto &resp = result.value();
  153. EXPECT_EQ(resp.status, StatusCode::OK_200);
  154. EXPECT_EQ(resp.body, content_);
  155. }
  156. static std::string make_sock_path() {
  157. const char *shard = getenv("GTEST_SHARD_INDEX");
  158. return shard ? std::string("./httplib-server-") + shard + ".sock"
  159. : "./httplib-server.sock";
  160. }
  161. const std::string pathname_{make_sock_path()};
  162. const std::string pattern_{"/hi"};
  163. const std::string content_{"Hello World!"};
  164. };
  165. TEST_F(UnixSocketTest, pathname) {
  166. httplib::Server svr;
  167. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  168. res.set_content(content_, "text/plain");
  169. });
  170. std::thread t{[&] {
  171. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  172. }};
  173. auto se = detail::scope_exit([&] {
  174. svr.stop();
  175. t.join();
  176. ASSERT_FALSE(svr.is_running());
  177. });
  178. svr.wait_until_ready();
  179. ASSERT_TRUE(svr.is_running());
  180. client_GET(pathname_);
  181. // ".//x.sock", which is not taken for a URL
  182. client_GET("./" + pathname_.substr(1));
  183. }
  184. #if defined(__linux__) || \
  185. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  186. TEST_F(UnixSocketTest, PeerPid) {
  187. httplib::Server svr;
  188. std::string remote_port_val;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. res.set_content(content_, "text/plain");
  191. remote_port_val = std::to_string(req.remote_port);
  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. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  205. }
  206. #endif
  207. #ifdef __linux__
  208. TEST_F(UnixSocketTest, abstract) {
  209. constexpr char svr_path[]{"\x00httplib-server.sock"};
  210. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  211. httplib::Server svr;
  212. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  213. res.set_content(content_, "text/plain");
  214. });
  215. std::thread t{[&] {
  216. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  217. }};
  218. auto se = detail::scope_exit([&] {
  219. svr.stop();
  220. t.join();
  221. ASSERT_FALSE(svr.is_running());
  222. });
  223. svr.wait_until_ready();
  224. ASSERT_TRUE(svr.is_running());
  225. client_GET(abstract_addr);
  226. }
  227. #endif
  228. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  229. httplib::Server svr;
  230. std::string received_host_header;
  231. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  232. // Capture the Host header sent by the client
  233. auto host_iter = req.headers.find("Host");
  234. if (host_iter != req.headers.end()) {
  235. received_host_header = host_iter->second;
  236. }
  237. res.set_content(content_, "text/plain");
  238. });
  239. std::thread t{[&] {
  240. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  241. }};
  242. auto se = detail::scope_exit([&] {
  243. svr.stop();
  244. t.join();
  245. ASSERT_FALSE(svr.is_running());
  246. });
  247. svr.wait_until_ready();
  248. ASSERT_TRUE(svr.is_running());
  249. // Test that Host header is automatically set to "localhost" for Unix socket
  250. // connections
  251. httplib::Client cli{pathname_};
  252. cli.set_address_family(AF_UNIX);
  253. ASSERT_TRUE(cli.is_valid());
  254. const auto &result = cli.Get(pattern_);
  255. ASSERT_TRUE(result) << "error: " << result.error();
  256. const auto &resp = result.value();
  257. EXPECT_EQ(resp.status, StatusCode::OK_200);
  258. EXPECT_EQ(resp.body, content_);
  259. // Verify that Host header was automatically set to "localhost"
  260. EXPECT_EQ(received_host_header, "localhost");
  261. }
  262. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  263. // Another socket in the working directory, which a Location can name as
  264. // its host
  265. const auto other_path = "other-" + pathname_.substr(2);
  266. httplib::Server svr;
  267. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  268. // An absolute Location naming the Host this client sends
  269. res.set_redirect("http://localhost" + pattern_);
  270. });
  271. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  272. res.set_redirect("http://" + other_path + pattern_);
  273. });
  274. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  275. res.set_redirect("http://mapped.test" + pattern_);
  276. });
  277. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  278. res.set_header("X-Auth", req.get_header_value("Authorization"));
  279. res.set_content(content_, "text/plain");
  280. });
  281. httplib::Server other;
  282. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  283. res.set_content("other", "text/plain");
  284. });
  285. std::thread t{[&] {
  286. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  287. }};
  288. std::thread t2{[&] {
  289. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  290. }};
  291. auto se = detail::scope_exit([&] {
  292. svr.stop();
  293. other.stop();
  294. t.join();
  295. t2.join();
  296. std::remove(other_path.c_str());
  297. });
  298. svr.wait_until_ready();
  299. other.wait_until_ready();
  300. httplib::Client cli{pathname_};
  301. cli.set_address_family(AF_UNIX);
  302. cli.set_follow_location(true);
  303. cli.set_bearer_token_auth("token");
  304. // Another host: the same socket, without the credentials
  305. auto res = cli.Get("/cross");
  306. ASSERT_TRUE(res) << "error: " << res.error();
  307. EXPECT_EQ(StatusCode::OK_200, res->status);
  308. EXPECT_EQ(content_, res->body);
  309. EXPECT_EQ("", res->get_header_value("X-Auth"));
  310. // localhost is this client's own host
  311. res = cli.Get("/redirect");
  312. ASSERT_TRUE(res) << "error: " << res.error();
  313. EXPECT_EQ(StatusCode::OK_200, res->status);
  314. EXPECT_EQ(content_, res->body);
  315. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  316. // A host the caller mapped to a socket goes there
  317. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  318. res = cli.Get("/mapped");
  319. ASSERT_TRUE(res) << "error: " << res.error();
  320. EXPECT_EQ(StatusCode::OK_200, res->status);
  321. EXPECT_EQ("other", res->body);
  322. }
  323. #ifndef _WIN32
  324. TEST(SocketStream, wait_writable_UNIX) {
  325. int fds[2];
  326. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  327. const auto asSocketStream = [&](socket_t fd,
  328. std::function<bool(Stream &)> func) {
  329. return detail::process_client_socket(
  330. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  331. };
  332. asSocketStream(fds[0], [&](Stream &s0) {
  333. EXPECT_EQ(s0.socket(), fds[0]);
  334. EXPECT_TRUE(s0.wait_writable());
  335. EXPECT_TRUE(s0.is_peer_alive());
  336. EXPECT_EQ(0, close(fds[1]));
  337. EXPECT_FALSE(s0.is_peer_alive());
  338. return true;
  339. });
  340. EXPECT_EQ(0, close(fds[0]));
  341. }
  342. TEST(SocketStream, wait_writable_INET) {
  343. sockaddr_in addr;
  344. memset(&addr, 0, sizeof(addr));
  345. addr.sin_family = AF_INET;
  346. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  347. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  348. int disconnected_svr_sock = -1;
  349. std::thread svr{[&] {
  350. const int s = socket(AF_INET, SOCK_STREAM, 0);
  351. ASSERT_LE(0, s);
  352. // PORT + 1 is shared with the SSL redirect tests and with
  353. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  354. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  355. // because that happens on a worker thread the ASSERT does not stop the
  356. // test: it runs on and fails at the disconnected_svr_sock check instead.
  357. default_socket_options(s);
  358. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  359. ASSERT_EQ(0, listen(s, 1));
  360. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  361. ASSERT_EQ(0, close(s));
  362. }};
  363. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  364. std::thread cli{[&] {
  365. const int s = socket(AF_INET, SOCK_STREAM, 0);
  366. ASSERT_LE(0, s);
  367. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  368. ASSERT_EQ(0, close(s));
  369. }};
  370. cli.join();
  371. svr.join();
  372. ASSERT_NE(disconnected_svr_sock, -1);
  373. const auto asSocketStream = [&](socket_t fd,
  374. std::function<bool(Stream &)> func) {
  375. return detail::process_client_socket(
  376. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  377. };
  378. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  379. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  380. // wait_writable() returns true because select_write() only checks if the
  381. // send buffer has space. Peer disconnection is detected later by send().
  382. EXPECT_TRUE(ss.wait_writable());
  383. return true;
  384. });
  385. ASSERT_EQ(0, close(disconnected_svr_sock));
  386. }
  387. #endif // #ifndef _WIN32
  388. TEST(SetSocketOptTest, TcpNoDelay) {
  389. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  390. ASSERT_NE(sock, INVALID_SOCKET);
  391. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  392. int val = 0;
  393. socklen_t len = sizeof(val);
  394. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  395. reinterpret_cast<char *>(&val), &len));
  396. EXPECT_NE(val, 0);
  397. detail::close_socket(sock);
  398. }
  399. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  400. // accept() reports failures through WSAGetLastError() on Windows and through
  401. // errno everywhere else. Asking the wrong one is what made the accept loop
  402. // treat every recoverable failure as fatal on Windows.
  403. struct Classification {
  404. bool resource;
  405. bool transient;
  406. };
  407. auto classify = [](int err) {
  408. #ifdef _WIN32
  409. WSASetLastError(err);
  410. #else
  411. errno = err;
  412. #endif
  413. // Read both before asserting: an assertion may clobber the error slot.
  414. Classification c;
  415. c.resource = detail::is_accept_resource_error();
  416. c.transient = detail::is_accept_transient_error();
  417. return c;
  418. };
  419. #ifdef _WIN32
  420. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  421. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  422. WSAECONNRESET, WSAECONNABORTED};
  423. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  424. #else
  425. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  426. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  427. ECONNABORTED};
  428. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  429. #endif
  430. for (auto err : resource_errors) {
  431. const auto c = classify(err);
  432. EXPECT_TRUE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. for (auto err : transient_errors) {
  436. const auto c = classify(err);
  437. EXPECT_TRUE(c.transient) << "error " << err;
  438. EXPECT_FALSE(c.resource) << "error " << err;
  439. }
  440. for (auto err : fatal_errors) {
  441. const auto c = classify(err);
  442. EXPECT_FALSE(c.resource) << "error " << err;
  443. EXPECT_FALSE(c.transient) << "error " << err;
  444. }
  445. #ifdef _WIN32
  446. WSASetLastError(0);
  447. #else
  448. errno = 0;
  449. #endif
  450. }
  451. TEST(ClientTest, MoveConstructible) {
  452. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  453. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  454. }
  455. TEST(ClientTest, MoveAssignable) {
  456. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  457. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  458. }
  459. #ifdef _WIN32
  460. TEST(StartupTest, WSAStartup) {
  461. WSADATA wsaData;
  462. int ret = WSAStartup(0x0002, &wsaData);
  463. ASSERT_EQ(0, ret);
  464. }
  465. #endif
  466. TEST(DecodePathTest, PercentCharacter) {
  467. EXPECT_EQ(
  468. decode_path_component(
  469. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  470. U8("descrip=Gastos áéíóúñÑ 6"));
  471. }
  472. TEST(DecodePathTest, PercentCharacterNUL) {
  473. string expected;
  474. expected.push_back('x');
  475. expected.push_back('\0');
  476. expected.push_back('x');
  477. EXPECT_EQ(decode_path_component("x%00x"), expected);
  478. }
  479. TEST(DecodePathTest, UnicodeEncoding) {
  480. // %u0041 = 'A' (1-byte UTF-8)
  481. EXPECT_EQ("A", decode_path_component("%u0041"));
  482. // %u00E9 = 'é' (2-byte UTF-8)
  483. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  484. // %u3042 = 'あ' (3-byte UTF-8)
  485. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  486. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  487. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  488. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  489. // neighbours)
  490. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  491. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  492. }
  493. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  494. // A sign or whitespace inside the two-character escape window must not be
  495. // accepted as a valid percent-encoding; the sequence is passed through
  496. // literally, matching decode_uri_component / decode_path_component.
  497. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  498. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  499. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  500. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  501. // Well-formed escapes still decode.
  502. EXPECT_EQ("-", decode_query_component("%2D", false));
  503. EXPECT_EQ("A", decode_query_component("%41", false));
  504. }
  505. TEST(SanitizeFilenameTest, VariousPatterns) {
  506. // Path traversal
  507. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  508. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  509. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  510. // Normal and edge cases
  511. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  512. EXPECT_EQ("filename.txt",
  513. httplib::sanitize_filename("/path/to/filename.txt"));
  514. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  515. EXPECT_EQ("", httplib::sanitize_filename(".."));
  516. EXPECT_EQ("", httplib::sanitize_filename(""));
  517. // Null bytes stripped
  518. EXPECT_EQ("safe.txt",
  519. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  520. // Whitespace-only rejected
  521. EXPECT_EQ("", httplib::sanitize_filename(" "));
  522. }
  523. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  524. // before it is dropped; anywhere else it is an ordinary file name character.
  525. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  526. #ifdef _WIN32
  527. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  528. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  529. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  530. #else
  531. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  532. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  533. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  534. #endif
  535. }
  536. // Forward declaration (see the base64_encode note below): split builds move the
  537. // definition into httplib.cc, so re-declaring it here lets the test link.
  538. namespace httplib {
  539. namespace detail {
  540. bool is_chunked_transfer_encoding(const Headers &headers);
  541. } // namespace detail
  542. } // namespace httplib
  543. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  544. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  545. auto make = [](std::initializer_list<const char *> lines) {
  546. Headers h;
  547. for (auto te : lines) {
  548. if (te) { h.emplace("Transfer-Encoding", te); }
  549. }
  550. return h;
  551. };
  552. // Sole coding, matched case-insensitively.
  553. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  554. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  555. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  556. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  557. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  558. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  560. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  562. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  563. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  564. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  565. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  566. // were received, into one list. Headers preserves that order, so the answer
  567. // is decided by the last coding of the last line and the order the lines
  568. // arrived in is significant.
  569. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  570. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  571. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  572. // The split can fall anywhere in the list.
  573. EXPECT_TRUE(
  574. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  575. EXPECT_FALSE(
  576. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  577. // A trailing line naming no coding leaves the list ending in nothing, so it
  578. // must not inherit the chunked from the line before it.
  579. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  580. }
  581. // Forward declarations (see the base64_encode note below).
  582. namespace httplib {
  583. namespace detail {
  584. bool parse_status_line(const char *line, std::string &version, int &status,
  585. std::string &reason);
  586. std::string file_extension(const std::string &path);
  587. std::string
  588. find_content_type(const std::string &path,
  589. const std::map<std::string, std::string> &user_data,
  590. const std::string &default_content_type);
  591. bool can_compress_content_type(const std::string &content_type);
  592. bool is_prohibited_header_name(const std::string &name);
  593. bool is_valid_path(const std::string &path);
  594. #ifdef CPPHTTPLIB_SSL_ENABLED
  595. bool match_hostname(const std::string &pattern, const std::string &hostname);
  596. #endif
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  600. struct {
  601. const char *line;
  602. const char *version;
  603. int status;
  604. const char *reason;
  605. } cases[] = {
  606. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  607. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  608. // The reason phrase may be empty, or left out along with its space.
  609. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  610. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  611. };
  612. for (const auto &c : cases) {
  613. std::string version;
  614. int status = 0;
  615. std::string reason = "unset";
  616. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  617. << c.line;
  618. EXPECT_EQ(c.version, version);
  619. EXPECT_EQ(c.status, status);
  620. EXPECT_EQ(c.reason, reason);
  621. }
  622. }
  623. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  624. const char *lines[] = {
  625. "HTTP/2 200 OK\r\n",
  626. "HTTP/1.2 200 OK\r\n",
  627. "HTTP/1.1 20 OK\r\n",
  628. "HTTP/1.1 2000 OK\r\n",
  629. "HTTP/1.1 2x0 OK\r\n",
  630. "HTTP/1.1 200 OK\r\n",
  631. "HTTP/1.1 200OK\r\n",
  632. "HTTP/1.1 200 O\rK\r\n",
  633. "HTTP/1.1 200 OK",
  634. "HTTP/1.1 200 OK\r\nX",
  635. "",
  636. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  637. "HTTP/1.1 200 OK\n",
  638. #endif
  639. };
  640. for (auto line : lines) {
  641. std::string version;
  642. int status = 0;
  643. std::string reason;
  644. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  645. << line;
  646. }
  647. }
  648. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  649. // Long enough to overflow the stack when matched with std::regex.
  650. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  651. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  652. std::string version;
  653. int status = 0;
  654. std::string reason;
  655. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  656. EXPECT_EQ(200, status);
  657. EXPECT_EQ(long_reason, reason);
  658. }
  659. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  660. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  661. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  662. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  663. EXPECT_EQ("", detail::file_extension("noext"));
  664. EXPECT_EQ("", detail::file_extension("a."));
  665. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  666. EXPECT_EQ("", detail::file_extension("a.b-c"));
  667. // Long enough to overflow the stack when matched with std::regex.
  668. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  669. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  670. }
  671. #ifdef CPPHTTPLIB_SSL_ENABLED
  672. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  673. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  674. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  675. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  676. // A wildcard needs two labels after it, in the leftmost label only
  677. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  678. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  679. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  680. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  681. EXPECT_FALSE(
  682. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  683. // No name may have an empty label
  684. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  685. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  686. }
  687. #endif
  688. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  689. detail::case_ignore::hash hash;
  690. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  691. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  692. // Long enough to overflow the stack if hashed one call per character.
  693. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  694. }
  695. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  696. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  697. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  698. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  699. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  700. // Same 26-bit hash as html, svg and js.
  701. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  702. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  703. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  704. }
  705. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  706. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  707. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  708. }
  709. }
  710. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  711. // name anywhere else.
  712. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  713. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  714. #ifdef _WIN32
  715. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  716. #else
  717. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  718. #endif
  719. }
  720. }
  721. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  722. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  723. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  724. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  725. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  726. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  727. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  728. // Same 26-bit hash as application/json.
  729. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  730. }
  731. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  732. Request req;
  733. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  734. EXPECT_TRUE(req.is_multipart_form_data());
  735. std::string boundary;
  736. EXPECT_TRUE(detail::parse_multipart_boundary(
  737. req.get_header_value("Content-Type"), boundary));
  738. EXPECT_EQ("x", boundary);
  739. }
  740. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  741. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  742. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  743. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  744. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  745. // Same 26-bit hash as REMOTE_ADDR.
  746. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  747. }
  748. // Forward declaration: in split builds split.py strips `inline` and moves the
  749. // definition into httplib.cc, so detail::base64_encode is not visible from the
  750. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  751. // in both header-only and split builds.
  752. namespace httplib {
  753. namespace detail {
  754. std::string base64_encode(const std::string &in);
  755. } // namespace detail
  756. } // namespace httplib
  757. TEST(Base64EncodeTest, KnownAnswers) {
  758. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  759. // where the accumulator's top bit is already set before the next shift.
  760. EXPECT_EQ("", detail::base64_encode(""));
  761. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  762. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  763. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  764. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  765. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  766. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  767. // High bytes keep the top bit set across several rounds.
  768. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  769. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  770. }
  771. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  772. string unescapedCharacters = "-_.!~*'()";
  773. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  774. }
  775. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  776. string reservedCharacters = ";,/?:@&=+$";
  777. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  778. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  779. }
  780. TEST(ClientQueryOrder, PreserveOrder) {
  781. // This test reproduces Issue #2259: client may reorder query parameters
  782. // when sending a GET request. The expected behavior is that the client
  783. // preserves the original query string order when the caller supplied it
  784. // as part of the path.
  785. Server svr;
  786. svr.Get("/", [&](const Request &req, Response &res) {
  787. // Echo back the raw target so the test can assert ordering
  788. res.set_content(req.target, "text/plain");
  789. });
  790. std::thread t{[&] { svr.listen(HOST, PORT); }};
  791. auto se = detail::scope_exit([&] {
  792. svr.stop();
  793. t.join();
  794. ASSERT_FALSE(svr.is_running());
  795. });
  796. svr.wait_until_ready();
  797. Client cli(HOST, PORT);
  798. ASSERT_TRUE(cli.is_valid());
  799. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  800. auto res = cli.Get(original);
  801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  802. // Expect the echoed target to exactly match the original path (order
  803. // preserved)
  804. EXPECT_EQ(res->body, original);
  805. }
  806. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  807. string chineseCharacters = U8("中国語");
  808. string russianCharacters = U8("дом");
  809. string brazilianCharacters = U8("óculos");
  810. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  811. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  812. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  813. "%D0%B4%D0%BE%D0%BC");
  814. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  815. }
  816. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  817. string unescapedCharacters = "-_.!~*'()";
  818. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  819. }
  820. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  821. string reservedCharacters = ";,/?:@&=+$";
  822. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  823. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  824. }
  825. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  826. string chineseCharacters = U8("中国語");
  827. string russianCharacters = U8("дом");
  828. string brazilianCharacters = U8("óculos");
  829. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  830. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  831. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  832. "%D0%B4%D0%BE%D0%BC");
  833. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  834. }
  835. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  836. // Issue #2082 use case: encoding path component with ampersand
  837. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  838. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  839. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  840. }
  841. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  842. string unescapedCharacters = "-_.!~*'()";
  843. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  844. }
  845. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  846. string reservedCharacters = ";,/?:@&=+$#";
  847. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  848. }
  849. TEST(EncodeUriTest, TestUTF8Characters) {
  850. string chineseCharacters = U8("中国語");
  851. string russianCharacters = U8("дом");
  852. string brazilianCharacters = U8("óculos");
  853. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  854. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  855. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  856. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  857. }
  858. TEST(EncodeUriTest, TestCompleteUri) {
  859. string uri =
  860. "https://example.com/path/to/resource?query=value&param=test#fragment";
  861. EXPECT_EQ(
  862. httplib::encode_uri(uri),
  863. "https://example.com/path/to/resource?query=value&param=test#fragment");
  864. }
  865. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  866. string uri =
  867. "https://example.com/path with spaces/file name.html?q=hello world";
  868. EXPECT_EQ(httplib::encode_uri(uri),
  869. "https://example.com/path%20with%20spaces/"
  870. "file%20name.html?q=hello%20world");
  871. }
  872. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  873. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  875. }
  876. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  877. string unescapedCharacters = "-_.!~*'()";
  878. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  879. }
  880. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  881. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  882. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  883. string encodedBrazilian = "%C3%B3culos";
  884. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  885. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  886. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  887. }
  888. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  889. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  890. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  891. "Piri Tommy Villiers - on & on");
  892. }
  893. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  894. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  895. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  896. }
  897. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  898. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  899. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  900. }
  901. TEST(DecodeUriTest, TestUTF8Characters) {
  902. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  903. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  904. string encodedBrazilian = "%C3%B3culos";
  905. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  906. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  907. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  908. }
  909. TEST(DecodeUriTest, TestCompleteUri) {
  910. string encodedUri = "https://example.com/path%20with%20spaces/"
  911. "file%20name.html?q=hello%20world";
  912. EXPECT_EQ(
  913. httplib::decode_uri(encodedUri),
  914. "https://example.com/path with spaces/file name.html?q=hello world");
  915. }
  916. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  917. string original =
  918. "https://example.com/path with spaces/file name.html?q=hello world";
  919. string encoded = httplib::encode_uri(original);
  920. string decoded = httplib::decode_uri(encoded);
  921. EXPECT_EQ(decoded, original);
  922. }
  923. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  924. // decode_uri is the inverse of encode_uri: an escaped reserved character
  925. // stays encoded so it is not promoted into a real delimiter, while
  926. // non-reserved escapes still decode (like JS decodeURI).
  927. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  928. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  929. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  930. "%3F%3A%40%26%3D%2B%24%2C%3B");
  931. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  932. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  933. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  934. "http://example.com/a%2Fb");
  935. // decode_uri_component still decodes the reserved character.
  936. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  937. }
  938. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  939. string original = "Piri Tommy Villiers - on & on";
  940. string encoded = httplib::encode_uri_component(original);
  941. string decoded = httplib::decode_uri_component(encoded);
  942. EXPECT_EQ(decoded, original);
  943. }
  944. TEST(TrimTests, TrimStringTests) {
  945. EXPECT_EQ("abc", detail::trim_copy("abc"));
  946. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  947. EXPECT_TRUE(detail::trim_copy("").empty());
  948. }
  949. TEST(AsciiTest, LocaleIndependentClassification) {
  950. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  951. // which consult the global C locale: std::isalnum(0xC5) can return true
  952. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  953. // helpers must classify every byte by the ASCII grammar alone.
  954. for (int i = 0; i < 256; i++) {
  955. auto c = static_cast<char>(i);
  956. auto is_digit = i >= '0' && i <= '9';
  957. auto is_upper = i >= 'A' && i <= 'Z';
  958. auto is_lower = i >= 'a' && i <= 'z';
  959. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  960. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  961. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  962. << "byte " << i;
  963. }
  964. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  965. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  966. // Non-ASCII bytes must be percent-encoded, never passed through as
  967. // alphanumeric.
  968. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  969. }
  970. TEST(FromCharsTest, Double) {
  971. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  972. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  973. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  974. auto parse = [](const std::string &s, double &v) {
  975. return detail::from_chars(s.data(), s.data() + s.size(), v);
  976. };
  977. double v = -1.0;
  978. // Representative quality values.
  979. EXPECT_EQ(parse("0", v).ec, std::errc{});
  980. EXPECT_DOUBLE_EQ(v, 0.0);
  981. EXPECT_EQ(parse("1", v).ec, std::errc{});
  982. EXPECT_DOUBLE_EQ(v, 1.0);
  983. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  984. EXPECT_DOUBLE_EQ(v, 0.8);
  985. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 0.001);
  987. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  988. EXPECT_DOUBLE_EQ(v, 1.0);
  989. // A missing integer or fractional part is tolerated.
  990. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.5);
  992. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  993. EXPECT_DOUBLE_EQ(v, 5.0);
  994. // Values outside [0, 1] still parse; the caller range-checks them.
  995. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  996. EXPECT_DOUBLE_EQ(v, 123.456);
  997. // Stops at the first byte that is not part of the number and reports where.
  998. std::string trailing = "0.9, text/html";
  999. auto r = parse(trailing, v);
  1000. EXPECT_EQ(r.ec, std::errc{});
  1001. EXPECT_DOUBLE_EQ(v, 0.9);
  1002. EXPECT_EQ(*r.ptr, ',');
  1003. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1004. // outright, and an 'e'/'E' simply ends the number.
  1005. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1007. std::string exp_input = "1.5e3";
  1008. r = parse(exp_input, v);
  1009. EXPECT_EQ(r.ec, std::errc{});
  1010. EXPECT_DOUBLE_EQ(v, 1.5);
  1011. EXPECT_EQ(*r.ptr, 'e');
  1012. // Invalid inputs.
  1013. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1014. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1015. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1016. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1017. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1018. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1019. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1020. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1021. std::errc{});
  1022. EXPECT_DOUBLE_EQ(v, 0.0);
  1023. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1024. std::errc{});
  1025. EXPECT_GE(v, 0.0);
  1026. EXPECT_LE(v, 1.0);
  1027. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1028. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1029. }
  1030. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1031. // Simple case without quality values
  1032. std::vector<std::string> result1;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html,application/json,text/plain", result1));
  1035. EXPECT_EQ(result1.size(), 3U);
  1036. EXPECT_EQ(result1[0], "text/html");
  1037. EXPECT_EQ(result1[1], "application/json");
  1038. EXPECT_EQ(result1[2], "text/plain");
  1039. // With quality values
  1040. std::vector<std::string> result2;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1043. EXPECT_EQ(result2.size(), 3U);
  1044. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1045. EXPECT_EQ(result2[1], "text/html");
  1046. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1047. }
  1048. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1049. // Mixed with and without quality values
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(
  1052. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1053. EXPECT_EQ(result.size(), 3U);
  1054. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1055. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1056. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1057. }
  1058. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1059. // Empty header
  1060. std::vector<std::string> empty_result;
  1061. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1062. EXPECT_TRUE(empty_result.empty());
  1063. // Single type
  1064. std::vector<std::string> single_result;
  1065. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1066. EXPECT_EQ(single_result.size(), 1U);
  1067. EXPECT_EQ(single_result[0], "application/json");
  1068. // Wildcard types
  1069. std::vector<std::string> wildcard_result;
  1070. EXPECT_TRUE(detail::parse_accept_header(
  1071. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1072. EXPECT_EQ(wildcard_result.size(), 3U);
  1073. EXPECT_EQ(wildcard_result[0], "application/json");
  1074. EXPECT_EQ(wildcard_result[1], "text/*");
  1075. EXPECT_EQ(wildcard_result[2], "*/*");
  1076. }
  1077. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1078. // Common browser Accept header
  1079. std::vector<std::string> browser_result;
  1080. EXPECT_TRUE(
  1081. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1082. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1083. browser_result));
  1084. EXPECT_EQ(browser_result.size(), 6U);
  1085. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1086. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1087. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1088. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1089. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1090. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1091. // API client header
  1092. std::vector<std::string> api_result;
  1093. EXPECT_TRUE(detail::parse_accept_header(
  1094. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1095. api_result));
  1096. EXPECT_EQ(api_result.size(), 3U);
  1097. EXPECT_EQ(api_result[0], "application/json");
  1098. EXPECT_EQ(api_result[1], "application/xml");
  1099. EXPECT_EQ(api_result[2], "text/plain");
  1100. }
  1101. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1102. // Quality value with 3 decimal places
  1103. std::vector<std::string> decimal_result;
  1104. EXPECT_TRUE(detail::parse_accept_header(
  1105. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1106. EXPECT_EQ(decimal_result.size(), 2U);
  1107. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1108. EXPECT_EQ(decimal_result[1], "text/html");
  1109. // Zero quality (should still be included but with lowest priority)
  1110. std::vector<std::string> zero_q_result;
  1111. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1112. zero_q_result));
  1113. EXPECT_EQ(zero_q_result.size(), 2U);
  1114. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1115. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1116. // No spaces around commas
  1117. std::vector<std::string> no_space_result;
  1118. EXPECT_TRUE(detail::parse_accept_header(
  1119. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1120. no_space_result));
  1121. EXPECT_EQ(no_space_result.size(), 3U);
  1122. EXPECT_EQ(no_space_result[0], "text/html");
  1123. EXPECT_EQ(no_space_result[1], "application/json");
  1124. EXPECT_EQ(no_space_result[2], "text/plain");
  1125. }
  1126. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1127. // Quality values always use '.' as the decimal separator, so parsing must
  1128. // not depend on the process locale. An embedding application may have
  1129. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1130. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1131. std::string saved = cur ? cur : "C";
  1132. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1133. "fr_FR.UTF-8"};
  1134. bool switched = false;
  1135. for (const auto loc : comma_locales) {
  1136. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1137. std::localeconv()->decimal_point[0] == ',') {
  1138. switched = true;
  1139. break;
  1140. }
  1141. }
  1142. if (!switched) {
  1143. std::setlocale(LC_NUMERIC, saved.c_str());
  1144. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1145. }
  1146. // The higher-weighted type appears later in the list, so a correct parse
  1147. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1148. // sensitive parse reads both weights as 0 and leaves the original order.
  1149. std::vector<std::string> result;
  1150. EXPECT_TRUE(detail::parse_accept_header(
  1151. "application/json;q=0.1,text/html;q=0.9", result));
  1152. ASSERT_EQ(result.size(), 2U);
  1153. EXPECT_EQ(result[0], "text/html");
  1154. EXPECT_EQ(result[1], "application/json");
  1155. std::setlocale(LC_NUMERIC, saved.c_str());
  1156. }
  1157. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1158. std::vector<std::string> result;
  1159. // Invalid quality value (> 1.0)
  1160. EXPECT_FALSE(
  1161. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1162. // Invalid quality value (< 0.0)
  1163. EXPECT_FALSE(
  1164. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1165. // Invalid quality value (not a number)
  1166. EXPECT_FALSE(detail::parse_accept_header(
  1167. "text/html;q=invalid,application/json", result));
  1168. // A valid numeric prefix does not make the entire quality value valid.
  1169. EXPECT_FALSE(detail::parse_accept_header(
  1170. "text/html;q=0.5junk,application/json", result));
  1171. // Empty quality value
  1172. EXPECT_FALSE(
  1173. detail::parse_accept_header("text/html;q=,application/json", result));
  1174. // Invalid media type format (no slash and not wildcard)
  1175. EXPECT_FALSE(
  1176. detail::parse_accept_header("invalidtype,application/json", result));
  1177. // Valid cases should still work
  1178. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1179. EXPECT_EQ(result.size(), 1U);
  1180. EXPECT_EQ(result[0], "*/*");
  1181. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1182. EXPECT_EQ(result.size(), 1U);
  1183. EXPECT_EQ(result[0], "*");
  1184. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1185. EXPECT_EQ(result.size(), 1U);
  1186. EXPECT_EQ(result[0], "text/*");
  1187. }
  1188. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1189. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1190. // and must not be answered with 400 Bad Request.
  1191. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1192. struct {
  1193. const char *value;
  1194. std::vector<std::string> expected;
  1195. } cases[] = {
  1196. {",application/json", {"application/json"}},
  1197. {"text/html,", {"text/html"}},
  1198. {"text/html,,*/*", {"text/html", "*/*"}},
  1199. // An empty element may be spelled with whitespace in it
  1200. {"text/html, , application/json", {"text/html", "application/json"}},
  1201. // Nothing but empty elements is an empty list, which means the same
  1202. // thing as no Accept header at all
  1203. {",,,", {}},
  1204. // Quality values still apply across ignored empty elements
  1205. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1206. };
  1207. for (const auto &c : cases) {
  1208. std::vector<std::string> result;
  1209. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1210. << "value: " << c.value;
  1211. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1212. }
  1213. // An invalid entry is still rejected when empty elements surround it
  1214. std::vector<std::string> result;
  1215. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1216. }
  1217. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1218. // or ';' inside one does not end the list element or the parameter. Section
  1219. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1220. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1221. struct {
  1222. const char *value;
  1223. std::vector<std::string> expected;
  1224. } cases[] = {
  1225. {"text/html;profile=\"a,b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // A "q=" inside a quoted value is not the weight
  1228. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1229. {"text/html", "application/json"}},
  1230. // The weight after a quoted value still applies
  1231. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1232. {"application/json", "text/html"}},
  1233. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1234. {"application/json", "text/html"}},
  1235. {"text/html;profile=\"a\\\"b\",application/json",
  1236. {"text/html", "application/json"}},
  1237. // An escaped backslash does not escape the '"' after it
  1238. {"text/html;profile=\"a\\\\\",application/json",
  1239. {"text/html", "application/json"}},
  1240. };
  1241. for (const auto &c : cases) {
  1242. std::vector<std::string> result;
  1243. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1244. << "value: " << c.value;
  1245. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1246. }
  1247. }
  1248. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1249. Server svr;
  1250. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1251. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1252. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1253. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1254. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1255. res.set_content("ok", "text/plain");
  1256. });
  1257. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1258. EXPECT_TRUE(false);
  1259. res.set_content("bad request", "text/plain");
  1260. });
  1261. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1262. auto se = detail::scope_exit([&] {
  1263. svr.stop();
  1264. listen_thread.join();
  1265. ASSERT_FALSE(svr.is_running());
  1266. });
  1267. svr.wait_until_ready();
  1268. Client cli("localhost", PORT);
  1269. {
  1270. auto res = cli.Get(
  1271. "/accept_ok",
  1272. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1274. EXPECT_EQ(StatusCode::OK_200, res->status);
  1275. }
  1276. {
  1277. auto res = cli.Get("/accept_bad_request",
  1278. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1281. }
  1282. }
  1283. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1284. Server svr;
  1285. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1286. res.set_content("ok", "text/plain");
  1287. });
  1288. std::atomic<int> start_count{0};
  1289. std::atomic<bool> running_when_called{false};
  1290. svr.set_start_handler([&]() {
  1291. running_when_called = svr.is_running();
  1292. start_count++;
  1293. });
  1294. auto port = svr.bind_to_any_port(HOST);
  1295. std::thread t([&]() { svr.listen_after_bind(); });
  1296. auto se = detail::scope_exit([&] {
  1297. svr.stop();
  1298. t.join();
  1299. ASSERT_FALSE(svr.is_running());
  1300. });
  1301. svr.wait_until_ready();
  1302. // A successful request proves the accept loop is running, which the start
  1303. // handler precedes; so by now the handler must have run exactly once.
  1304. Client cli(HOST, port);
  1305. cli.set_connection_timeout(std::chrono::seconds(5));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1308. EXPECT_EQ(StatusCode::OK_200, res->status);
  1309. EXPECT_EQ(1, start_count.load());
  1310. EXPECT_TRUE(running_when_called.load());
  1311. }
  1312. TEST(DivideTest, DivideStringTests) {
  1313. auto divide = [](const std::string &str, char d) {
  1314. std::string lhs;
  1315. std::string rhs;
  1316. detail::divide(str, d,
  1317. [&](const char *lhs_data, std::size_t lhs_size,
  1318. const char *rhs_data, std::size_t rhs_size) {
  1319. lhs.assign(lhs_data, lhs_size);
  1320. rhs.assign(rhs_data, rhs_size);
  1321. });
  1322. return std::make_pair(std::move(lhs), std::move(rhs));
  1323. };
  1324. {
  1325. const auto res = divide("", '=');
  1326. EXPECT_EQ(res.first, "");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("=", '=');
  1331. EXPECT_EQ(res.first, "");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide(" ", '=');
  1336. EXPECT_EQ(res.first, " ");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("a", '=');
  1341. EXPECT_EQ(res.first, "a");
  1342. EXPECT_EQ(res.second, "");
  1343. }
  1344. {
  1345. const auto res = divide("a=", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "");
  1348. }
  1349. {
  1350. const auto res = divide("=b", '=');
  1351. EXPECT_EQ(res.first, "");
  1352. EXPECT_EQ(res.second, "b");
  1353. }
  1354. {
  1355. const auto res = divide("a=b", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b");
  1358. }
  1359. {
  1360. const auto res = divide("a=b=", '=');
  1361. EXPECT_EQ(res.first, "a");
  1362. EXPECT_EQ(res.second, "b=");
  1363. }
  1364. {
  1365. const auto res = divide("a=b=c", '=');
  1366. EXPECT_EQ(res.first, "a");
  1367. EXPECT_EQ(res.second, "b=c");
  1368. }
  1369. }
  1370. TEST(SplitTest, ParseQueryString) {
  1371. string s = "key1=val1&key2=val2&key3=val3";
  1372. Params dic;
  1373. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1374. [&](const char *b, const char *e) {
  1375. string key, val;
  1376. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1377. if (key.empty()) {
  1378. key.assign(b2, e2);
  1379. } else {
  1380. val.assign(b2, e2);
  1381. }
  1382. });
  1383. dic.emplace(key, val);
  1384. });
  1385. EXPECT_EQ("val1", dic.find("key1")->second);
  1386. EXPECT_EQ("val2", dic.find("key2")->second);
  1387. EXPECT_EQ("val3", dic.find("key3")->second);
  1388. }
  1389. TEST(SplitTest, ParseInvalidQueryTests) {
  1390. {
  1391. string s = " ";
  1392. Params dict;
  1393. detail::parse_query_text(s, dict);
  1394. EXPECT_TRUE(dict.empty());
  1395. }
  1396. {
  1397. string s = " = =";
  1398. Params dict;
  1399. detail::parse_query_text(s, dict);
  1400. EXPECT_TRUE(dict.empty());
  1401. }
  1402. }
  1403. TEST(ParseQueryTest, ParseQueryString) {
  1404. {
  1405. std::string s = "key1=val1&key2=val2&key3=val3";
  1406. Params dic;
  1407. detail::parse_query_text(s, dic);
  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. {
  1413. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1414. Params dic;
  1415. detail::parse_query_text(s, dic);
  1416. EXPECT_EQ("", dic.find("key1")->second);
  1417. EXPECT_EQ("val1", dic.find("key2")->second);
  1418. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1419. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1420. }
  1421. }
  1422. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1423. Params dic;
  1424. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1425. dic.emplace("key1", "val1");
  1426. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1427. dic.emplace("key2", "val2");
  1428. dic.emplace("key3", "val3");
  1429. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1430. }
  1431. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1432. Params params;
  1433. params.emplace("a", "1");
  1434. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1435. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1436. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1437. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1438. // Long enough to overflow the stack when matched with std::regex.
  1439. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1440. EXPECT_EQ("/p?" + long_query + "&a=1",
  1441. append_query_params("/p?" + long_query, params));
  1442. }
  1443. // Joins every entry of a Headers or Params into "key=value " so a whole
  1444. // traversal can be compared in one assertion. Both are instantiations of the
  1445. // same insertion-ordered container, so one helper serves both.
  1446. template <typename Map> static std::string entries_to_string(const Map &m) {
  1447. std::string s;
  1448. for (const auto &entry : m) {
  1449. s += entry.first + "=" + entry.second + " ";
  1450. }
  1451. return s;
  1452. }
  1453. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1454. // Params used to be a std::multimap, which sorted by name and handed the
  1455. // caller's query back alphabetised. A client signing its query string could
  1456. // not reproduce the order it asked for.
  1457. Params dic;
  1458. dic.emplace("zulu", "1");
  1459. dic.emplace("alpha", "2");
  1460. dic.emplace("mike", "3");
  1461. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1462. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1463. }
  1464. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1465. Params dic;
  1466. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1467. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1468. }
  1469. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1470. Request req;
  1471. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1472. req.params);
  1473. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1474. EXPECT_EQ("first", req.get_param_value("tag"));
  1475. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1476. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1477. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1478. EXPECT_EQ("", req.get_param_value("tag", 3));
  1479. }
  1480. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1481. // Params shares its container with Headers, which matches field names
  1482. // case-insensitively. Parameter names must not pick that up.
  1483. Params dic;
  1484. dic.emplace("Key", "upper");
  1485. dic.emplace("key", "lower");
  1486. EXPECT_EQ(2U, dic.size());
  1487. EXPECT_EQ(1U, dic.count("Key"));
  1488. EXPECT_EQ(1U, dic.count("key"));
  1489. EXPECT_EQ("upper", dic.find("Key")->second);
  1490. EXPECT_EQ("lower", dic.find("key")->second);
  1491. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1492. }
  1493. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1494. Server svr;
  1495. std::string order;
  1496. svr.Get("/order", [&](const Request &req, Response &res) {
  1497. order = entries_to_string(req.params);
  1498. res.set_content("ok", "text/plain");
  1499. });
  1500. auto port = svr.bind_to_any_port(HOST);
  1501. thread t = thread([&] { svr.listen_after_bind(); });
  1502. auto se = detail::scope_exit([&] {
  1503. svr.stop();
  1504. t.join();
  1505. ASSERT_FALSE(svr.is_running());
  1506. });
  1507. svr.wait_until_ready();
  1508. Client cli(HOST, port);
  1509. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1510. ASSERT_TRUE(res);
  1511. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1512. }
  1513. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1514. Server svr;
  1515. std::string field_order, file_order;
  1516. svr.Post("/order", [&](const Request &req, Response &res) {
  1517. for (const auto &field : req.form.fields) {
  1518. field_order += field.first + "=" + field.second.content + " ";
  1519. }
  1520. for (const auto &file : req.form.files) {
  1521. file_order += file.first + "=" + file.second.filename + " ";
  1522. }
  1523. res.set_content("ok", "text/plain");
  1524. });
  1525. auto port = svr.bind_to_any_port(HOST);
  1526. thread t = thread([&] { svr.listen_after_bind(); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. t.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. UploadFormDataItems items = {
  1534. {"zulu", "1", "", ""},
  1535. {"alpha", "2", "", ""},
  1536. {"mike", "3", "", ""},
  1537. {"zebra", "z", "z.txt", "text/plain"},
  1538. {"apple", "a", "a.txt", "text/plain"},
  1539. };
  1540. Client cli(HOST, port);
  1541. auto res = cli.Post("/order", items);
  1542. ASSERT_TRUE(res);
  1543. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1544. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1545. }
  1546. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1547. Server svr;
  1548. std::vector<std::string> values;
  1549. std::string first, second, out_of_range, order;
  1550. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1551. values = req.form.get_fields("tag");
  1552. first = req.form.get_field("tag", 0);
  1553. second = req.form.get_field("tag", 1);
  1554. out_of_range = req.form.get_field("tag", 2);
  1555. for (const auto &field : req.form.fields) {
  1556. order += field.first + "=" + field.second.content + " ";
  1557. }
  1558. res.set_content("ok", "text/plain");
  1559. });
  1560. auto port = svr.bind_to_any_port(HOST);
  1561. thread t = thread([&] { svr.listen_after_bind(); });
  1562. auto se = detail::scope_exit([&] {
  1563. svr.stop();
  1564. t.join();
  1565. ASSERT_FALSE(svr.is_running());
  1566. });
  1567. svr.wait_until_ready();
  1568. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1569. // not adjacent in the container.
  1570. UploadFormDataItems items = {
  1571. {"tag", "first", "", ""},
  1572. {"other", "x", "", ""},
  1573. {"tag", "second", "", ""},
  1574. };
  1575. Client cli(HOST, port);
  1576. auto res = cli.Post("/repeated", items);
  1577. ASSERT_TRUE(res);
  1578. ASSERT_EQ(2U, values.size());
  1579. EXPECT_EQ("first", values[0]);
  1580. EXPECT_EQ("second", values[1]);
  1581. EXPECT_EQ("first", first);
  1582. EXPECT_EQ("second", second);
  1583. // std::multimap already kept entries sharing a name in insertion order, so
  1584. // everything above passes without this change too. The whole traversal is
  1585. // what tells the two apart: sorting by name would hoist "other" to the front
  1586. // and the two "tag" parts would end up adjacent.
  1587. EXPECT_EQ("tag=first other=x tag=second ", order);
  1588. // Advancing past the last entry of a name used to run off the container;
  1589. // the container's saturating increment makes it return the default instead.
  1590. EXPECT_EQ("", out_of_range);
  1591. }
  1592. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1593. Server svr;
  1594. std::string file_names;
  1595. svr.Post("/upload", [&](const Request &req, Response &res) {
  1596. for (const auto &file : req.form.files) {
  1597. file_names += file.first + "|" + file.second.filename + " ";
  1598. }
  1599. res.set_content("ok", "text/plain");
  1600. });
  1601. auto port = svr.bind_to_any_port(HOST);
  1602. thread t = thread([&] { svr.listen_after_bind(); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. t.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. // A trailing backslash would otherwise escape the closing quote.
  1610. UploadFormDataItems items = {
  1611. {"dir\\", "x", "a.txt", "text/plain"},
  1612. {"b", "y", "a\\\\b.txt", "text/plain"},
  1613. };
  1614. Client cli(HOST, port);
  1615. auto res = cli.Post("/upload", items);
  1616. ASSERT_TRUE(res);
  1617. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1618. }
  1619. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1620. // Server::read_content() keeps a FormFields::iterator alive across the
  1621. // content callbacks that fill the part it points at. The container is
  1622. // vector-backed, so a later emplace can reallocate and invalidate an older
  1623. // iterator; 64 parts grow the vector through seven reallocations, which
  1624. // checks that every part's content still lands in its own entry.
  1625. const size_t part_count = 64;
  1626. // One formula for both the parts sent and the values expected back, so the
  1627. // two cannot drift apart.
  1628. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1629. auto content_of = [](size_t i) {
  1630. return std::string(64, static_cast<char>('a' + (i % 26)));
  1631. };
  1632. Server svr;
  1633. std::vector<std::pair<std::string, std::string>> received;
  1634. svr.Post("/many", [&](const Request &req, Response &res) {
  1635. for (const auto &field : req.form.fields) {
  1636. received.emplace_back(field.first, field.second.content);
  1637. }
  1638. res.set_content("ok", "text/plain");
  1639. });
  1640. auto port = svr.bind_to_any_port(HOST);
  1641. thread t = thread([&] { svr.listen_after_bind(); });
  1642. auto se = detail::scope_exit([&] {
  1643. svr.stop();
  1644. t.join();
  1645. ASSERT_FALSE(svr.is_running());
  1646. });
  1647. svr.wait_until_ready();
  1648. UploadFormDataItems items;
  1649. for (size_t i = 0; i < part_count; i++) {
  1650. items.push_back({name_of(i), content_of(i), "", ""});
  1651. }
  1652. Client cli(HOST, port);
  1653. auto res = cli.Post("/many", items);
  1654. ASSERT_TRUE(res);
  1655. ASSERT_EQ(part_count, received.size());
  1656. for (size_t i = 0; i < part_count; i++) {
  1657. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1658. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1659. }
  1660. }
  1661. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1662. string content_type = "multipart/form-data; boundary=something";
  1663. string boundary;
  1664. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(boundary, "something");
  1667. }
  1668. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1669. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1670. string boundary;
  1671. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1672. EXPECT_TRUE(ret);
  1673. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1674. }
  1675. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1676. string content_type =
  1677. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1678. string boundary;
  1679. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1680. EXPECT_TRUE(ret);
  1681. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1682. }
  1683. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1684. string content_type =
  1685. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1686. string boundary;
  1687. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1688. EXPECT_TRUE(ret);
  1689. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1690. }
  1691. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1692. const string boundary(70, 'a');
  1693. string content_type = "multipart/form-data; boundary=" + boundary;
  1694. string parsed;
  1695. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1696. EXPECT_TRUE(ret);
  1697. EXPECT_EQ(parsed, boundary);
  1698. }
  1699. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1700. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1701. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1702. string parsed;
  1703. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1704. EXPECT_FALSE(ret);
  1705. }
  1706. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1707. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1708. // is 72 characters on the wire and still valid.
  1709. const string boundary(70, 'a');
  1710. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1711. string parsed;
  1712. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1713. EXPECT_EQ(parsed, boundary);
  1714. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1715. parsed.clear();
  1716. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1719. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1720. // The parameter parser must not treat that '=' as the key/value separator.
  1721. string content_type =
  1722. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1723. "charset=UTF-8";
  1724. string parsed;
  1725. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1726. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1727. }
  1728. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1729. // A ';' inside the quoted-string is part of the value, not a parameter
  1730. // separator, so it must not truncate the boundary.
  1731. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1732. string parsed;
  1733. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1734. EXPECT_EQ(parsed, "a;b");
  1735. }
  1736. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1737. string parsed;
  1738. EXPECT_TRUE(detail::parse_multipart_boundary(
  1739. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1740. EXPECT_EQ("a\\b", parsed);
  1741. EXPECT_TRUE(detail::parse_multipart_boundary(
  1742. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1743. EXPECT_EQ("a\"b", parsed);
  1744. }
  1745. TEST(ParseDispositionParamsTest, QuotedValues) {
  1746. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1747. // ';' and '=' are ordinary characters inside one.
  1748. struct {
  1749. const char *value;
  1750. std::vector<std::pair<const char *, const char *>> expected;
  1751. } cases[] = {
  1752. {"name=\"file1\"; filename=\"a.txt\"",
  1753. {{"name", "file1"}, {"filename", "a.txt"}}},
  1754. // Whitespace around '=' and ';' is still trimmed
  1755. {"name=\"file2\" ;filename = \"a.html\"",
  1756. {{"name", "file2"}, {"filename", "a.html"}}},
  1757. // '=' inside the value used to leave only the text after the last one
  1758. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1759. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1760. {"name=\"x=y\"", {{"name", "x=y"}}},
  1761. // ';' inside the value used to truncate the pair and leave a bogus one
  1762. {"name=\"file3\"; filename=\"a;b.txt\"",
  1763. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1764. // An unquoted value keeps working, and so does filename*
  1765. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1766. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1767. // A parameter with no key is dropped rather than turned into one whose
  1768. // key is the value
  1769. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1770. // An escaped quote does not end the value
  1771. {"name=\"a\\\"; filename=evil.php\"",
  1772. {{"name", "a\"; filename=evil.php"}}},
  1773. // Other backslashes, as in a Windows path, are kept
  1774. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1775. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1776. };
  1777. for (const auto &c : cases) {
  1778. Params params;
  1779. detail::parse_disposition_params(c.value, params);
  1780. for (const auto &kv : c.expected) {
  1781. auto it = params.find(kv.first);
  1782. ASSERT_NE(it, params.end())
  1783. << "value: " << c.value << ", key: " << kv.first;
  1784. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1785. }
  1786. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1787. }
  1788. }
  1789. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1790. Server svr;
  1791. std::string filename;
  1792. std::string content;
  1793. svr.Post("/upload", [&](const Request &req, Response &) {
  1794. const auto &file = req.form.get_file("file");
  1795. filename = file.filename;
  1796. content = file.content;
  1797. });
  1798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1799. auto se = detail::scope_exit([&] {
  1800. svr.stop();
  1801. thread.join();
  1802. ASSERT_FALSE(svr.is_running());
  1803. });
  1804. svr.wait_until_ready();
  1805. std::string body = "--B\r\n"
  1806. "Content-Disposition: form-data; name=\"file\"; "
  1807. "filename=\"a.txt\"\r\n"
  1808. "Content-Type: text/plain\r\n"
  1809. "\r\n"
  1810. "hello\r\n"
  1811. "--B--\r\n";
  1812. Client cli(HOST, PORT);
  1813. auto res = cli.Post(
  1814. "/upload",
  1815. [&](size_t offset, DataSink &sink) {
  1816. if (offset < body.size()) {
  1817. sink.write(&body[offset], 1);
  1818. } else {
  1819. sink.done();
  1820. }
  1821. return true;
  1822. },
  1823. "multipart/form-data; boundary=B");
  1824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1825. EXPECT_EQ(StatusCode::OK_200, res->status);
  1826. EXPECT_EQ("a.txt", filename);
  1827. EXPECT_EQ("hello", content);
  1828. }
  1829. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1830. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1831. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1832. Server svr;
  1833. std::string field_value, file_name, file_filename;
  1834. bool has_field = false, has_file = false;
  1835. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1836. has_field = req.form.has_field("x=y");
  1837. field_value = req.form.get_field("x=y");
  1838. has_file = req.form.has_file("file1");
  1839. const auto &file = req.form.get_file("file1");
  1840. file_name = file.name;
  1841. file_filename = file.filename;
  1842. res.set_content("ok", "text/plain");
  1843. });
  1844. auto port = svr.bind_to_any_port(HOST);
  1845. thread t = thread([&] { svr.listen_after_bind(); });
  1846. auto se = detail::scope_exit([&] {
  1847. svr.stop();
  1848. t.join();
  1849. ASSERT_FALSE(svr.is_running());
  1850. });
  1851. svr.wait_until_ready();
  1852. UploadFormDataItems items = {
  1853. {"x=y", "field-value", "", ""},
  1854. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1855. };
  1856. Client cli(HOST, port);
  1857. auto res = cli.Post("/quoted", items);
  1858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1859. ASSERT_EQ(StatusCode::OK_200, res->status);
  1860. EXPECT_TRUE(has_field);
  1861. EXPECT_EQ("field-value", field_value);
  1862. EXPECT_TRUE(has_file);
  1863. EXPECT_EQ("file1", file_name);
  1864. EXPECT_EQ("a;b=report.pdf", file_filename);
  1865. }
  1866. TEST(GetHeaderValueTest, DefaultValue) {
  1867. Headers headers = {{"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/plain", val);
  1870. }
  1871. TEST(GetHeaderValueTest, DefaultValueInt) {
  1872. Headers headers = {{"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1874. EXPECT_EQ(100ull, val);
  1875. }
  1876. TEST(GetHeaderValueTest, RegularValue) {
  1877. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1878. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1879. EXPECT_STREQ("text/html", val);
  1880. }
  1881. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1882. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1883. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1884. EXPECT_STREQ("text/html", val);
  1885. }
  1886. TEST(GetHeaderValueTest, SetContent) {
  1887. Response res;
  1888. res.set_content("html", "text/html");
  1889. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1890. res.set_content("text", "text/plain");
  1891. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1892. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1893. }
  1894. TEST(GetHeaderValueTest, RegularValueInt) {
  1895. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1896. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1897. EXPECT_EQ(100ull, val);
  1898. }
  1899. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1900. Headers headers = {{"Content-Length", "x"}};
  1901. auto is_invalid_value = false;
  1902. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1903. is_invalid_value);
  1904. EXPECT_EQ(0ull, val);
  1905. EXPECT_TRUE(is_invalid_value);
  1906. }
  1907. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1908. // An all-digit value that overflows size_t must be reported as invalid, not
  1909. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1910. // a large length to a small one on 32-bit builds, leaving the framing length
  1911. // wrong while is_invalid_value stayed false.
  1912. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1913. auto is_invalid_value = false;
  1914. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1915. is_invalid_value);
  1916. EXPECT_TRUE(is_invalid_value);
  1917. // A well-formed length is unaffected.
  1918. Headers ok = {{"Content-Length", "1234"}};
  1919. is_invalid_value = false;
  1920. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1921. is_invalid_value);
  1922. EXPECT_EQ(1234ull, val);
  1923. EXPECT_FALSE(is_invalid_value);
  1924. }
  1925. TEST(GetHeaderValueTest, Range) {
  1926. {
  1927. Headers headers = {make_range_header({{1, -1}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{-1, 1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=-1", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=1-10, 100-", val);
  1945. }
  1946. {
  1947. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1948. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1949. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1950. }
  1951. {
  1952. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1953. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1954. EXPECT_STREQ("bytes=0-0, -1", val);
  1955. }
  1956. }
  1957. TEST(BearerTokenAuthTest, SchemeValidation) {
  1958. // A value shorter than "Bearer " must not throw from the fixed-length
  1959. // substr, and a non-Bearer scheme must not be reported as a token.
  1960. struct {
  1961. const char *value;
  1962. const char *expected;
  1963. } cases[] = {
  1964. {"x", ""},
  1965. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1966. {"Bearer abc123", "abc123"},
  1967. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1968. };
  1969. for (const auto &c : cases) {
  1970. Request req;
  1971. req.set_header("Authorization", c.value);
  1972. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1973. }
  1974. }
  1975. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1976. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1977. // to depend on the standard library (libstdc++ handed back duplicates in
  1978. // reverse insertion order, libc++ in insertion order).
  1979. Request req;
  1980. req.set_header("Accept-Encoding", "gzip");
  1981. req.set_header("Accept-Encoding", "deflate");
  1982. req.set_header("Accept-Encoding", "br");
  1983. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1984. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1985. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1986. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1987. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1988. }
  1989. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1990. Request req;
  1991. req.set_header("X-Test", "only");
  1992. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1993. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1994. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1995. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1996. }
  1997. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1998. Request req;
  1999. req.set_header("X-First", "1");
  2000. req.set_header("X-Test", "2");
  2001. req.params.emplace("first", "1");
  2002. req.params.emplace("test", "2");
  2003. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2004. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2005. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2006. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2007. // The second one is negative when read as a signed value
  2008. const auto max_id = (std::numeric_limits<size_t>::max)();
  2009. for (auto id : {max_id / 2, max_id}) {
  2010. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2011. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2012. EXPECT_EQ("", req.get_param_value("test", id));
  2013. EXPECT_EQ("", req.form.get_field("test", id));
  2014. EXPECT_EQ("", req.form.get_file("test", id).content);
  2015. }
  2016. }
  2017. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2018. Headers headers;
  2019. headers.emplace("Host", "example.com");
  2020. headers.emplace("Accept-Encoding", "gzip");
  2021. headers.emplace("User-Agent", "test");
  2022. headers.emplace("Accept-Encoding", "deflate");
  2023. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2024. "Accept-Encoding=deflate ",
  2025. entries_to_string(headers));
  2026. }
  2027. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2028. Headers headers = {{"Content-Type", "text/html"},
  2029. {"CONTENT-TYPE", "text/xml"}};
  2030. EXPECT_EQ(2U, headers.count("content-type"));
  2031. auto it = headers.find("content-type");
  2032. ASSERT_TRUE(it != headers.end());
  2033. EXPECT_EQ("text/html", it->second);
  2034. }
  2035. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2036. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2037. // drop only those fields and leave everything positioned between them.
  2038. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2039. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2040. auto rng = headers.equal_range("a");
  2041. headers.erase(rng.first, rng.second);
  2042. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2043. }
  2044. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2045. Headers headers = {
  2046. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2047. EXPECT_EQ(3U, headers.erase("A"));
  2048. EXPECT_EQ(0U, headers.count("A"));
  2049. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2050. }
  2051. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2052. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2053. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2054. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2055. }
  2056. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2057. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2058. headers.emplace_front("Host", "example.com");
  2059. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2060. entries_to_string(headers));
  2061. }
  2062. TEST(ParseHeaderValueTest, Range) {
  2063. {
  2064. Ranges ranges;
  2065. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2066. EXPECT_TRUE(ret);
  2067. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2068. }
  2069. {
  2070. Ranges ranges;
  2071. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2072. EXPECT_TRUE(ret);
  2073. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2074. }
  2075. {
  2076. Ranges ranges;
  2077. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2078. EXPECT_TRUE(ret);
  2079. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2080. }
  2081. {
  2082. Ranges ranges;
  2083. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2084. EXPECT_FALSE(ret);
  2085. }
  2086. {
  2087. Ranges ranges;
  2088. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2089. EXPECT_TRUE(ret);
  2090. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2091. }
  2092. {
  2093. Ranges ranges;
  2094. auto ret =
  2095. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2096. EXPECT_TRUE(ret);
  2097. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2098. }
  2099. {
  2100. Ranges ranges;
  2101. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2102. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2103. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2104. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2105. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2106. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2107. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2108. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2109. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2110. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2111. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2112. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2113. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2114. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2115. EXPECT_FALSE(
  2116. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2117. EXPECT_TRUE(ranges.empty());
  2118. }
  2119. {
  2120. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2121. // remainder of the representation, so it stays accepted.
  2122. Ranges ranges;
  2123. auto ret =
  2124. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2125. EXPECT_TRUE(ret);
  2126. ASSERT_EQ(1u, ranges.size());
  2127. EXPECT_EQ(0, ranges[0].first);
  2128. EXPECT_EQ(-1, ranges[0].second);
  2129. }
  2130. // RFC 9110 14.1: range unit names are case-insensitive.
  2131. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2132. Ranges ranges;
  2133. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2134. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2135. }
  2136. }
  2137. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2138. Request req;
  2139. req.set_header("Accept-Encoding", "gzip");
  2140. Response res;
  2141. res.set_header("Content-Type", "text/plain");
  2142. auto ret = detail::encoding_type(req, res);
  2143. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2144. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2145. #else
  2146. EXPECT_TRUE(ret == detail::EncodingType::None);
  2147. #endif
  2148. }
  2149. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2150. Request req;
  2151. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2152. Response res;
  2153. res.set_header("Content-Type", "text/plain");
  2154. auto ret = detail::encoding_type(req, res);
  2155. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2156. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2157. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2158. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2159. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2160. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2161. #else
  2162. EXPECT_TRUE(ret == detail::EncodingType::None);
  2163. #endif
  2164. }
  2165. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2166. Request req;
  2167. req.set_header("Accept-Encoding",
  2168. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2169. Response res;
  2170. res.set_header("Content-Type", "text/plain");
  2171. auto ret = detail::encoding_type(req, res);
  2172. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2173. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2174. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2175. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2176. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2177. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2178. #else
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. #endif
  2181. }
  2182. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2183. // All supported encodings rejected with q=0 should return None
  2184. Request req;
  2185. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2186. Response res;
  2187. res.set_header("Content-Type", "text/plain");
  2188. auto ret = detail::encoding_type(req, res);
  2189. EXPECT_TRUE(ret == detail::EncodingType::None);
  2190. }
  2191. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2192. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2193. Request req;
  2194. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2195. Response res;
  2196. res.set_header("Content-Type", "text/plain");
  2197. auto ret = detail::encoding_type(req, res);
  2198. EXPECT_TRUE(ret == detail::EncodingType::None);
  2199. }
  2200. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2201. Request req;
  2202. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2203. Response res;
  2204. res.set_header("Content-Type", "text/plain");
  2205. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2206. }
  2207. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2208. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2209. Request req;
  2210. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2211. Response res;
  2212. res.set_header("Content-Type", "text/plain");
  2213. auto ret = detail::encoding_type(req, res);
  2214. EXPECT_TRUE(ret == detail::EncodingType::None);
  2215. }
  2216. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2217. // RFC 7231: Accept-Encoding values are case-insensitive
  2218. Request req;
  2219. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2220. Response res;
  2221. res.set_header("Content-Type", "text/plain");
  2222. auto ret = detail::encoding_type(req, res);
  2223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2224. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2225. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2226. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2227. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2228. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2229. #else
  2230. EXPECT_TRUE(ret == detail::EncodingType::None);
  2231. #endif
  2232. }
  2233. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2234. // q value should determine priority, not hardcoded order
  2235. Request req;
  2236. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2237. Response res;
  2238. res.set_header("Content-Type", "text/plain");
  2239. auto ret = detail::encoding_type(req, res);
  2240. // gzip has highest q=1.0, so it should be selected even though
  2241. // br and zstd are also supported
  2242. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2243. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2244. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2245. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2246. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2247. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2248. #else
  2249. EXPECT_TRUE(ret == detail::EncodingType::None);
  2250. #endif
  2251. }
  2252. TEST(BufferStreamTest, read) {
  2253. detail::BufferStream strm1;
  2254. Stream &strm = strm1;
  2255. EXPECT_EQ(5, strm.write("hello"));
  2256. char buf[512];
  2257. EXPECT_EQ(2, strm.read(buf, 2));
  2258. EXPECT_EQ('h', buf[0]);
  2259. EXPECT_EQ('e', buf[1]);
  2260. EXPECT_EQ(2, strm.read(buf, 2));
  2261. EXPECT_EQ('l', buf[0]);
  2262. EXPECT_EQ('l', buf[1]);
  2263. EXPECT_EQ(1, strm.read(buf, 1));
  2264. EXPECT_EQ('o', buf[0]);
  2265. EXPECT_EQ(0, strm.read(buf, 1));
  2266. }
  2267. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2268. auto host = "www.httpwatch.com";
  2269. auto ip = hosted_at(host);
  2270. EXPECT_EQ("23.96.13.243", ip);
  2271. std::vector<std::string> addrs;
  2272. hosted_at(host, addrs);
  2273. EXPECT_EQ(1u, addrs.size());
  2274. }
  2275. #if 0 // It depends on each test environment...
  2276. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2277. auto host = "www.youtube.com";
  2278. std::vector<std::string> addrs;
  2279. hosted_at(host, addrs);
  2280. EXPECT_EQ(20u, addrs.size());
  2281. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2282. EXPECT_TRUE(it != addrs.end());
  2283. }
  2284. #endif
  2285. class ChunkedEncodingTest : public ::testing::Test {
  2286. protected:
  2287. ChunkedEncodingTest()
  2288. : cli_(HOST, PORT)
  2289. #ifdef CPPHTTPLIB_SSL_ENABLED
  2290. ,
  2291. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2292. #endif
  2293. {
  2294. cli_.set_connection_timeout(2);
  2295. #ifdef CPPHTTPLIB_SSL_ENABLED
  2296. cli_.enable_server_certificate_verification(false);
  2297. #endif
  2298. }
  2299. virtual void SetUp() {
  2300. read_file("./image.jpg", image_data_);
  2301. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2302. res.set_content("Hello World!", "text/plain");
  2303. });
  2304. svr_.Get(
  2305. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2306. res.set_chunked_content_provider(
  2307. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2308. size_t remaining = image_data_.size() - offset;
  2309. if (remaining == 0) {
  2310. sink.done();
  2311. } else {
  2312. constexpr size_t CHUNK_SIZE = 1024;
  2313. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2314. sink.write(&image_data_[offset], send_size);
  2315. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2316. }
  2317. return true;
  2318. });
  2319. });
  2320. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2321. svr_.wait_until_ready();
  2322. }
  2323. virtual void TearDown() {
  2324. svr_.stop();
  2325. if (!request_threads_.empty()) {
  2326. std::this_thread::sleep_for(std::chrono::seconds(1));
  2327. for (auto &t : request_threads_) {
  2328. t.join();
  2329. }
  2330. }
  2331. t_.join();
  2332. }
  2333. #ifdef CPPHTTPLIB_SSL_ENABLED
  2334. SSLClient cli_;
  2335. SSLServer svr_;
  2336. #else
  2337. Client cli_;
  2338. Server svr_;
  2339. #endif
  2340. thread t_;
  2341. std::vector<thread> request_threads_;
  2342. std::string image_data_;
  2343. };
  2344. TEST_F(ChunkedEncodingTest, NormalGet) {
  2345. auto res = cli_.Get("/chunked");
  2346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2347. std::string out;
  2348. read_file("./image.jpg", out);
  2349. EXPECT_EQ(StatusCode::OK_200, res->status);
  2350. EXPECT_EQ(out, res->body);
  2351. }
  2352. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2353. std::string body;
  2354. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2355. body.append(data, data_length);
  2356. return true;
  2357. });
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. std::string out;
  2360. read_file("./image.jpg", out);
  2361. EXPECT_EQ(StatusCode::OK_200, res->status);
  2362. EXPECT_EQ(out, body);
  2363. }
  2364. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2365. std::string body;
  2366. auto res = cli_.Get(
  2367. "/chunked",
  2368. [&](const Response &response) {
  2369. EXPECT_EQ(StatusCode::OK_200, response.status);
  2370. return true;
  2371. },
  2372. [&](const char *data, size_t data_length) {
  2373. body.append(data, data_length);
  2374. return true;
  2375. });
  2376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2377. std::string out;
  2378. read_file("./image.jpg", out);
  2379. EXPECT_EQ(StatusCode::OK_200, res->status);
  2380. EXPECT_EQ(out, body);
  2381. }
  2382. TEST(RangeTest, FromHTTPBin_Online) {
  2383. auto host = "httpbingo.org";
  2384. auto path = std::string{"/range/32"};
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. auto port = 443;
  2387. SSLClient cli(host, port);
  2388. #else
  2389. auto port = 80;
  2390. Client cli(host, port);
  2391. #endif
  2392. cli.set_connection_timeout(5);
  2393. {
  2394. auto res = cli.Get(path);
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2397. EXPECT_EQ(StatusCode::OK_200, res->status);
  2398. }
  2399. {
  2400. Headers headers = {make_range_header({{1, -1}})};
  2401. auto res = cli.Get(path, headers);
  2402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2403. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2405. }
  2406. {
  2407. Headers headers = {make_range_header({{1, 10}})};
  2408. auto res = cli.Get(path, headers);
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. EXPECT_EQ("bcdefghijk", res->body);
  2411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2412. }
  2413. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2414. // entire resource, while the original httpbin returned 200. Both are
  2415. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2416. {
  2417. Headers headers = {make_range_header({{0, 31}})};
  2418. auto res = cli.Get(path, headers);
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2421. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2422. res->status == StatusCode::PartialContent_206);
  2423. }
  2424. {
  2425. Headers headers = {make_range_header({{0, -1}})};
  2426. auto res = cli.Get(path, headers);
  2427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2428. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2429. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2430. res->status == StatusCode::PartialContent_206);
  2431. }
  2432. // go-httpbin returns 206 with clamped range for over-range requests,
  2433. // while the original httpbin returned 416. Both behaviors are observed
  2434. // in real servers, so we only verify the request succeeds.
  2435. {
  2436. Headers headers = {make_range_header({{0, 32}})};
  2437. auto res = cli.Get(path, headers);
  2438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2439. }
  2440. }
  2441. TEST(RangeTest, IgnoredForPost) {
  2442. Server svr;
  2443. svr.Post("/", [](const Request &, Response &res) {
  2444. res.set_content("abcdefg", "text/plain");
  2445. });
  2446. auto port = svr.bind_to_any_port(HOST);
  2447. ASSERT_GT(port, 0);
  2448. thread t = thread([&] { svr.listen_after_bind(); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. t.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. Client cli(HOST, port);
  2456. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2457. auto res = cli.Post("/", Headers{{"Range", range}});
  2458. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2459. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2460. EXPECT_EQ("abcdefg", res->body) << range;
  2461. }
  2462. }
  2463. TEST(RangeTest, IgnoredForUnknownUnit) {
  2464. Server svr;
  2465. svr.Get("/", [](const Request &, Response &res) {
  2466. res.set_content("abcdefg", "text/plain");
  2467. });
  2468. auto port = svr.bind_to_any_port(HOST);
  2469. ASSERT_GT(port, 0);
  2470. thread t = thread([&] { svr.listen_after_bind(); });
  2471. auto se = detail::scope_exit([&] {
  2472. svr.stop();
  2473. t.join();
  2474. ASSERT_FALSE(svr.is_running());
  2475. });
  2476. svr.wait_until_ready();
  2477. Client cli(HOST, port);
  2478. for (auto range : {"items=1-2", "none=x"}) {
  2479. auto res = cli.Get("/", Headers{{"Range", range}});
  2480. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2481. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2482. EXPECT_EQ("abcdefg", res->body) << range;
  2483. }
  2484. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2485. ASSERT_TRUE(res) << to_string(res.error());
  2486. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2487. }
  2488. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2489. auto host = "unresolvableaddress.local";
  2490. auto path = std::string{"/"};
  2491. #ifdef CPPHTTPLIB_SSL_ENABLED
  2492. auto port = 443;
  2493. SSLClient cli(host, port);
  2494. #else
  2495. auto port = 80;
  2496. Client cli(host, port);
  2497. #endif
  2498. cli.set_connection_timeout(1);
  2499. {
  2500. auto res = cli.Get(path);
  2501. ASSERT_FALSE(res);
  2502. }
  2503. std::this_thread::sleep_for(std::chrono::seconds(8));
  2504. }
  2505. #if defined(__linux__) && defined(__GLIBC__) && \
  2506. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2507. // Forward declaration: in split builds split.py strips `inline` and moves the
  2508. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2509. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2510. // against the symbol in both header-only and split builds.
  2511. namespace httplib {
  2512. namespace detail {
  2513. int getaddrinfo_with_timeout(const char *node, const char *service,
  2514. const struct addrinfo *hints,
  2515. struct addrinfo **res, time_t timeout_sec);
  2516. } // namespace detail
  2517. } // namespace httplib
  2518. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2519. //
  2520. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2521. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2522. // gai_suspend() call hits the connection timeout the function calls
  2523. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2524. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2525. // still alive and still references the now-destroyed stack frame.
  2526. //
  2527. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2528. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2529. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2530. // and runs them in a container.
  2531. namespace {
  2532. bool should_run_issue_2431_tests() {
  2533. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2534. return v && *v && std::string(v) != "0";
  2535. }
  2536. std::string unique_unresolvable_host(int n) {
  2537. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2538. // glibc still asks the configured nameserver — which is exactly the path
  2539. // we want to exercise. A unique label per call avoids the resolver cache.
  2540. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2541. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2542. std::to_string(n) + ".invalid";
  2543. }
  2544. } // namespace
  2545. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2546. if (!should_run_issue_2431_tests()) {
  2547. GTEST_SKIP()
  2548. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2549. }
  2550. for (int i = 0; i < 8; ++i) {
  2551. struct addrinfo hints;
  2552. memset(&hints, 0, sizeof(hints));
  2553. hints.ai_family = AF_UNSPEC;
  2554. hints.ai_socktype = SOCK_STREAM;
  2555. auto host = unique_unresolvable_host(i);
  2556. struct addrinfo *result = nullptr;
  2557. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2558. &result, /*timeout_sec=*/1);
  2559. if (rc == 0 && result) { freeaddrinfo(result); }
  2560. }
  2561. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2562. // stack region they still believe holds their gaicb.
  2563. std::this_thread::sleep_for(std::chrono::seconds(3));
  2564. }
  2565. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2566. if (!should_run_issue_2431_tests()) {
  2567. GTEST_SKIP()
  2568. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2569. }
  2570. std::atomic<bool> stop{false};
  2571. std::vector<std::thread> threads;
  2572. for (int t = 0; t < 8; ++t) {
  2573. threads.emplace_back([t, &stop] {
  2574. int i = 0;
  2575. while (!stop.load(std::memory_order_relaxed)) {
  2576. struct addrinfo hints;
  2577. memset(&hints, 0, sizeof(hints));
  2578. hints.ai_family = AF_UNSPEC;
  2579. hints.ai_socktype = SOCK_STREAM;
  2580. auto host = unique_unresolvable_host(t * 100000 + i++);
  2581. struct addrinfo *result = nullptr;
  2582. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2583. &result, /*timeout_sec=*/1);
  2584. if (rc == 0 && result) { freeaddrinfo(result); }
  2585. }
  2586. });
  2587. }
  2588. std::this_thread::sleep_for(std::chrono::seconds(8));
  2589. stop.store(true, std::memory_order_relaxed);
  2590. for (auto &th : threads) {
  2591. th.join();
  2592. }
  2593. std::this_thread::sleep_for(std::chrono::seconds(3));
  2594. }
  2595. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2596. if (!should_run_issue_2431_tests()) {
  2597. GTEST_SKIP()
  2598. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2599. }
  2600. std::atomic<bool> stop{false};
  2601. std::vector<std::thread> threads;
  2602. for (int t = 0; t < 8; ++t) {
  2603. threads.emplace_back([t, &stop] {
  2604. int i = 0;
  2605. while (!stop.load(std::memory_order_relaxed)) {
  2606. auto host = unique_unresolvable_host(t * 100000 + i++);
  2607. Client cli(host, 80);
  2608. cli.set_connection_timeout(1, 0);
  2609. cli.set_read_timeout(1, 0);
  2610. cli.set_write_timeout(1, 0);
  2611. (void)cli.Get("/");
  2612. }
  2613. });
  2614. }
  2615. std::this_thread::sleep_for(std::chrono::seconds(8));
  2616. stop.store(true, std::memory_order_relaxed);
  2617. for (auto &th : threads) {
  2618. th.join();
  2619. }
  2620. std::this_thread::sleep_for(std::chrono::seconds(3));
  2621. }
  2622. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2623. TEST(ConnectionErrorTest, InvalidHost) {
  2624. auto host = "-abcde.com";
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. auto port = 443;
  2627. SSLClient cli(host, port);
  2628. #else
  2629. auto port = 80;
  2630. Client cli(host, port);
  2631. #endif
  2632. cli.set_connection_timeout(std::chrono::seconds(2));
  2633. auto res = cli.Get("/");
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Connection, res.error());
  2636. }
  2637. TEST(ConnectionErrorTest, InvalidHost2) {
  2638. auto host = "httpcan.org/";
  2639. #ifdef CPPHTTPLIB_SSL_ENABLED
  2640. SSLClient cli(host);
  2641. #else
  2642. Client cli(host);
  2643. #endif
  2644. cli.set_connection_timeout(std::chrono::seconds(2));
  2645. auto res = cli.Get("/");
  2646. ASSERT_TRUE(!res);
  2647. EXPECT_EQ(Error::Connection, res.error());
  2648. }
  2649. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2650. auto host = "httpcan.org/";
  2651. #ifdef CPPHTTPLIB_SSL_ENABLED
  2652. SSLClient cli(host);
  2653. #else
  2654. Client cli(host);
  2655. #endif
  2656. cli.set_connection_timeout(std::chrono::seconds(2));
  2657. auto res = cli.Get("/");
  2658. ASSERT_TRUE(!res);
  2659. stringstream s;
  2660. s << "error code: " << res.error();
  2661. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2662. }
  2663. TEST(ConnectionErrorTest, InvalidPort) {
  2664. auto host = "localhost";
  2665. auto port = 44380;
  2666. #ifdef CPPHTTPLIB_SSL_ENABLED
  2667. SSLClient cli(host, port);
  2668. #else
  2669. Client cli(host, port);
  2670. #endif
  2671. cli.set_connection_timeout(std::chrono::seconds(2));
  2672. auto res = cli.Get("/");
  2673. ASSERT_TRUE(!res);
  2674. EXPECT_TRUE(Error::Connection == res.error() ||
  2675. Error::ConnectionTimeout == res.error());
  2676. }
  2677. TEST(ConnectionErrorTest, Timeout_Online) {
  2678. auto host = "google.com";
  2679. #ifdef CPPHTTPLIB_SSL_ENABLED
  2680. auto port = 44380;
  2681. SSLClient cli(host, port);
  2682. #else
  2683. auto port = 8080;
  2684. Client cli(host, port);
  2685. #endif
  2686. cli.set_connection_timeout(std::chrono::seconds(2));
  2687. // only probe one address type so that the error reason
  2688. // correlates to the timed-out IPv4, not the unsupported
  2689. // IPv6 connection attempt
  2690. cli.set_address_family(AF_INET);
  2691. auto res = cli.Get("/");
  2692. ASSERT_TRUE(!res);
  2693. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2694. }
  2695. TEST(CancelTest, NoCancel_Online) {
  2696. auto host = "httpbingo.org";
  2697. auto path = std::string{"/range/32"};
  2698. #ifdef CPPHTTPLIB_SSL_ENABLED
  2699. auto port = 443;
  2700. SSLClient cli(host, port);
  2701. #else
  2702. auto port = 80;
  2703. Client cli(host, port);
  2704. #endif
  2705. cli.set_connection_timeout(std::chrono::seconds(5));
  2706. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2708. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2709. EXPECT_EQ(StatusCode::OK_200, res->status);
  2710. }
  2711. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2712. // Use /bytes with a large payload so that the DownloadProgress callback
  2713. // (which only fires for Content-Length responses) is invoked before the
  2714. // entire body is received, giving cancellation a chance to fire.
  2715. auto host = "httpbingo.org";
  2716. auto path = std::string{"/bytes/524288"};
  2717. #ifdef CPPHTTPLIB_SSL_ENABLED
  2718. auto port = 443;
  2719. SSLClient cli(host, port);
  2720. #else
  2721. auto port = 80;
  2722. Client cli(host, port);
  2723. #endif
  2724. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2725. cli.set_connection_timeout(std::chrono::seconds(5));
  2726. ASSERT_TRUE(!res);
  2727. EXPECT_EQ(Error::Canceled, res.error());
  2728. }
  2729. TEST(CancelTest, WithCancelLargePayload_Online) {
  2730. auto host = "httpbingo.org";
  2731. auto path = std::string{"/bytes/524288"};
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. auto port = 443;
  2734. SSLClient cli(host, port);
  2735. #else
  2736. auto port = 80;
  2737. Client cli(host, port);
  2738. #endif
  2739. cli.set_connection_timeout(std::chrono::seconds(5));
  2740. uint32_t count = 0;
  2741. auto res =
  2742. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2743. ASSERT_TRUE(!res);
  2744. EXPECT_EQ(Error::Canceled, res.error());
  2745. }
  2746. TEST(CancelTest, NoCancelPost) {
  2747. Server svr;
  2748. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2749. res.set_content("Hello World!", "text/plain");
  2750. });
  2751. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2752. auto se = detail::scope_exit([&] {
  2753. svr.stop();
  2754. thread.join();
  2755. ASSERT_FALSE(svr.is_running());
  2756. });
  2757. svr.wait_until_ready();
  2758. Client cli(HOST, PORT);
  2759. cli.set_connection_timeout(std::chrono::seconds(5));
  2760. auto res =
  2761. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2762. "application/json", [](uint64_t, uint64_t) { return true; });
  2763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2764. EXPECT_EQ("Hello World!", res->body);
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. }
  2767. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2768. Server svr;
  2769. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2770. res.set_content("Hello World!", "text/plain");
  2771. });
  2772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2773. auto se = detail::scope_exit([&] {
  2774. svr.stop();
  2775. thread.join();
  2776. ASSERT_FALSE(svr.is_running());
  2777. });
  2778. svr.wait_until_ready();
  2779. Client cli(HOST, PORT);
  2780. cli.set_connection_timeout(std::chrono::seconds(5));
  2781. auto res =
  2782. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2783. "application/json", [](uint64_t, uint64_t) { return false; });
  2784. ASSERT_TRUE(!res);
  2785. EXPECT_EQ(Error::Canceled, res.error());
  2786. }
  2787. TEST(CancelTest, WithCancelLargePayloadPost) {
  2788. Server svr;
  2789. svr.set_payload_max_length(200 * 1024 * 1024);
  2790. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2791. res.set_content(LARGE_DATA, "text/plain");
  2792. });
  2793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. thread.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. Client cli(HOST, PORT);
  2801. cli.set_payload_max_length(200 * 1024 * 1024);
  2802. cli.set_connection_timeout(std::chrono::seconds(5));
  2803. auto res =
  2804. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2805. "application/json", [](uint64_t, uint64_t) { return false; });
  2806. ASSERT_TRUE(!res);
  2807. EXPECT_EQ(Error::Canceled, res.error());
  2808. }
  2809. TEST(CancelTest, NoCancelPut) {
  2810. Server svr;
  2811. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2812. res.set_content("Hello World!", "text/plain");
  2813. });
  2814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2815. auto se = detail::scope_exit([&] {
  2816. svr.stop();
  2817. thread.join();
  2818. ASSERT_FALSE(svr.is_running());
  2819. });
  2820. svr.wait_until_ready();
  2821. Client cli(HOST, PORT);
  2822. cli.set_connection_timeout(std::chrono::seconds(5));
  2823. auto res =
  2824. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2825. "application/json", [](uint64_t, uint64_t) { return true; });
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ("Hello World!", res->body);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2831. Server svr;
  2832. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2833. res.set_content("Hello World!", "text/plain");
  2834. });
  2835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2836. auto se = detail::scope_exit([&] {
  2837. svr.stop();
  2838. thread.join();
  2839. ASSERT_FALSE(svr.is_running());
  2840. });
  2841. svr.wait_until_ready();
  2842. Client cli(HOST, PORT);
  2843. cli.set_connection_timeout(std::chrono::seconds(5));
  2844. auto res =
  2845. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2846. "application/json", [](uint64_t, uint64_t) { return false; });
  2847. ASSERT_TRUE(!res);
  2848. EXPECT_EQ(Error::Canceled, res.error());
  2849. }
  2850. TEST(CancelTest, WithCancelLargePayloadPut) {
  2851. Server svr;
  2852. svr.set_payload_max_length(200 * 1024 * 1024);
  2853. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2854. res.set_content(LARGE_DATA, "text/plain");
  2855. });
  2856. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2857. auto se = detail::scope_exit([&] {
  2858. svr.stop();
  2859. thread.join();
  2860. ASSERT_FALSE(svr.is_running());
  2861. });
  2862. svr.wait_until_ready();
  2863. Client cli(HOST, PORT);
  2864. cli.set_payload_max_length(200 * 1024 * 1024);
  2865. cli.set_connection_timeout(std::chrono::seconds(5));
  2866. auto res =
  2867. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2868. "application/json", [](uint64_t, uint64_t) { return false; });
  2869. ASSERT_TRUE(!res);
  2870. EXPECT_EQ(Error::Canceled, res.error());
  2871. }
  2872. TEST(CancelTest, NoCancelPatch) {
  2873. Server svr;
  2874. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2875. res.set_content("Hello World!", "text/plain");
  2876. });
  2877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2878. auto se = detail::scope_exit([&] {
  2879. svr.stop();
  2880. thread.join();
  2881. ASSERT_FALSE(svr.is_running());
  2882. });
  2883. svr.wait_until_ready();
  2884. Client cli(HOST, PORT);
  2885. cli.set_connection_timeout(std::chrono::seconds(5));
  2886. auto res =
  2887. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2888. "application/json", [](uint64_t, uint64_t) { return true; });
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ("Hello World!", res->body);
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. }
  2893. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2894. Server svr;
  2895. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2896. res.set_content("Hello World!", "text/plain");
  2897. });
  2898. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2899. auto se = detail::scope_exit([&] {
  2900. svr.stop();
  2901. thread.join();
  2902. ASSERT_FALSE(svr.is_running());
  2903. });
  2904. svr.wait_until_ready();
  2905. Client cli(HOST, PORT);
  2906. cli.set_connection_timeout(std::chrono::seconds(5));
  2907. auto res =
  2908. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2909. "application/json", [](uint64_t, uint64_t) { return false; });
  2910. ASSERT_TRUE(!res);
  2911. EXPECT_EQ(Error::Canceled, res.error());
  2912. }
  2913. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2914. Server svr;
  2915. svr.set_payload_max_length(200 * 1024 * 1024);
  2916. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2917. res.set_content(LARGE_DATA, "text/plain");
  2918. });
  2919. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2920. auto se = detail::scope_exit([&] {
  2921. svr.stop();
  2922. thread.join();
  2923. ASSERT_FALSE(svr.is_running());
  2924. });
  2925. svr.wait_until_ready();
  2926. Client cli(HOST, PORT);
  2927. cli.set_payload_max_length(200 * 1024 * 1024);
  2928. cli.set_connection_timeout(std::chrono::seconds(5));
  2929. auto res =
  2930. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2931. "application/json", [](uint64_t, uint64_t) { return false; });
  2932. ASSERT_TRUE(!res);
  2933. EXPECT_EQ(Error::Canceled, res.error());
  2934. }
  2935. TEST(CancelTest, NoCancelDelete) {
  2936. Server svr;
  2937. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2938. res.set_content("Hello World!", "text/plain");
  2939. });
  2940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2941. auto se = detail::scope_exit([&] {
  2942. svr.stop();
  2943. thread.join();
  2944. ASSERT_FALSE(svr.is_running());
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, PORT);
  2948. cli.set_connection_timeout(std::chrono::seconds(5));
  2949. auto res =
  2950. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2951. "application/json", [](uint64_t, uint64_t) { return true; });
  2952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2953. EXPECT_EQ("Hello World!", res->body);
  2954. EXPECT_EQ(StatusCode::OK_200, res->status);
  2955. }
  2956. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2957. Server svr;
  2958. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2959. res.set_content("Hello World!", "text/plain");
  2960. });
  2961. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2962. auto se = detail::scope_exit([&] {
  2963. svr.stop();
  2964. thread.join();
  2965. ASSERT_FALSE(svr.is_running());
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, PORT);
  2969. cli.set_connection_timeout(std::chrono::seconds(5));
  2970. auto res =
  2971. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2972. "application/json", [](uint64_t, uint64_t) { return false; });
  2973. ASSERT_TRUE(!res);
  2974. EXPECT_EQ(Error::Canceled, res.error());
  2975. }
  2976. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2977. Server svr;
  2978. svr.set_payload_max_length(200 * 1024 * 1024);
  2979. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2980. res.set_content(LARGE_DATA, "text/plain");
  2981. });
  2982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2983. auto se = detail::scope_exit([&] {
  2984. svr.stop();
  2985. thread.join();
  2986. ASSERT_FALSE(svr.is_running());
  2987. });
  2988. svr.wait_until_ready();
  2989. Client cli(HOST, PORT);
  2990. cli.set_payload_max_length(200 * 1024 * 1024);
  2991. cli.set_connection_timeout(std::chrono::seconds(5));
  2992. auto res =
  2993. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2994. "application/json", [](uint64_t, uint64_t) { return false; });
  2995. ASSERT_TRUE(!res);
  2996. EXPECT_EQ(Error::Canceled, res.error());
  2997. }
  2998. // One stop() from another thread ends a request that waits for the response
  2999. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3000. Server svr;
  3001. std::atomic<bool> received{false};
  3002. std::atomic<bool> done{false};
  3003. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3004. received.store(true);
  3005. while (!done.load()) {
  3006. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3007. }
  3008. res.set_content("Hello World!", "text/plain");
  3009. });
  3010. auto port = svr.bind_to_any_port(HOST);
  3011. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3012. Client cli(HOST, port);
  3013. cli.set_read_timeout(std::chrono::seconds(30));
  3014. std::future<Result> request;
  3015. auto se = detail::scope_exit([&] {
  3016. done.store(true);
  3017. svr.stop();
  3018. thread.join();
  3019. ASSERT_FALSE(svr.is_running());
  3020. });
  3021. svr.wait_until_ready();
  3022. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3023. for (int i = 0; i < 500 && !received.load(); ++i) {
  3024. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3025. }
  3026. ASSERT_TRUE(received.load());
  3027. // Let the client block in the wait for the response
  3028. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3029. auto start = std::chrono::steady_clock::now();
  3030. cli.stop();
  3031. ASSERT_EQ(std::future_status::ready,
  3032. request.wait_for(std::chrono::seconds(5)));
  3033. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3034. auto res = request.get();
  3035. ASSERT_TRUE(!res);
  3036. EXPECT_EQ(Error::Read, res.error());
  3037. }
  3038. // A listener whose backlog completes the TCP connections of clients, and that
  3039. // never answers them
  3040. struct SilentListener {
  3041. socket_t sock = INVALID_SOCKET;
  3042. sockaddr_in addr{};
  3043. int port = 0;
  3044. explicit SilentListener(int backlog = 1) {
  3045. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3046. addr.sin_family = AF_INET;
  3047. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3048. socklen_t len = sizeof(addr);
  3049. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3050. ::listen(sock, backlog) != 0 ||
  3051. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3052. detail::close_socket(sock);
  3053. sock = INVALID_SOCKET;
  3054. }
  3055. port = ntohs(addr.sin_port);
  3056. }
  3057. ~SilentListener() { detail::close_socket(sock); }
  3058. // The next connection, whose reads give up after 5 seconds
  3059. socket_t accept() const {
  3060. auto peer = ::accept(sock, nullptr, nullptr);
  3061. if (peer != INVALID_SOCKET) {
  3062. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3063. }
  3064. return peer;
  3065. }
  3066. };
  3067. static bool receives_a_byte(socket_t peer) {
  3068. char c = 0;
  3069. return detail::read_socket(peer, &c, 1, 0) == 1;
  3070. }
  3071. // Runs op, stops cli once the listener receives the first byte op sends, and
  3072. // expects op to end with error soon after
  3073. template <typename ClientType, typename Op>
  3074. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3075. Op op, Error error = Error::Canceled) {
  3076. auto ended = std::async(std::launch::async, op);
  3077. auto peer = listener.accept();
  3078. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3079. ASSERT_NE(INVALID_SOCKET, peer);
  3080. ASSERT_TRUE(receives_a_byte(peer));
  3081. cli.stop();
  3082. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3083. EXPECT_EQ(error, ended.get());
  3084. }
  3085. // Stops itself from another thread as the connection opens, the last moment a
  3086. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3087. // waits for the connection fails the test instead of hanging it.
  3088. class StoppedAsConnectedClient : public ClientImpl {
  3089. public:
  3090. using ClientImpl::ClientImpl;
  3091. protected:
  3092. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3093. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3094. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3095. stopper_.wait_for(std::chrono::seconds(1));
  3096. return true;
  3097. }
  3098. private:
  3099. std::future<void> stopper_;
  3100. };
  3101. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3102. SilentListener listener;
  3103. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3104. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3105. cli.set_read_timeout(std::chrono::seconds(3));
  3106. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3107. auto peer = listener.accept();
  3108. EXPECT_FALSE(receives_a_byte(peer));
  3109. detail::close_socket(peer);
  3110. auto handle = cli.open_stream("GET", "/");
  3111. EXPECT_FALSE(handle.is_valid());
  3112. EXPECT_EQ(Error::Canceled, handle.error);
  3113. peer = listener.accept();
  3114. EXPECT_FALSE(receives_a_byte(peer));
  3115. detail::close_socket(peer);
  3116. }
  3117. #ifdef __linux__
  3118. // A connect that a listener with a full backlog never completes
  3119. TEST(ClientStopTest, StopEndsAConnect) {
  3120. SilentListener listener(0);
  3121. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3122. std::vector<socket_t> backlog;
  3123. auto close_backlog = detail::scope_exit([&] {
  3124. for (auto sock : backlog) {
  3125. detail::close_socket(sock);
  3126. }
  3127. });
  3128. for (int i = 0; i < 8; i++) {
  3129. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3130. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3131. sizeof(listener.addr));
  3132. backlog.push_back(sock);
  3133. }
  3134. Client cli("127.0.0.1", listener.port);
  3135. cli.set_connection_timeout(std::chrono::seconds(3));
  3136. auto ended =
  3137. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3138. // A stop() before the request starts does not apply to it, so it repeats
  3139. auto status = std::future_status::timeout;
  3140. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3141. cli.stop();
  3142. status = ended.wait_for(std::chrono::milliseconds(10));
  3143. }
  3144. EXPECT_EQ(std::future_status::ready, status);
  3145. EXPECT_EQ(Error::Canceled, ended.get());
  3146. }
  3147. #endif
  3148. // The stream holds the socket while it waits for the head, out of the reach
  3149. // of shutdown()
  3150. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3151. SilentListener listener;
  3152. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3153. Client cli("127.0.0.1", listener.port);
  3154. cli.set_read_timeout(std::chrono::seconds(3));
  3155. expect_stop_ends(
  3156. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3157. Error::Read);
  3158. }
  3159. #ifdef CPPHTTPLIB_SSL_ENABLED
  3160. // A server that never answers the ClientHello
  3161. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3162. SilentListener listener;
  3163. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3164. SSLClient cli("127.0.0.1", listener.port);
  3165. cli.enable_server_certificate_verification(false);
  3166. cli.set_connection_timeout(std::chrono::seconds(3));
  3167. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3168. expect_stop_ends(cli, listener,
  3169. [&] { return cli.open_stream("GET", "/").error; });
  3170. }
  3171. // A proxy that takes the CONNECT and never answers it
  3172. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3173. SilentListener listener;
  3174. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3175. SSLClient cli("example.com", 443);
  3176. cli.set_proxy("127.0.0.1", listener.port);
  3177. cli.set_read_timeout(std::chrono::seconds(3));
  3178. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3179. }
  3180. #endif
  3181. // A read timeout past what the clock reaches waits for the response
  3182. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3183. SilentListener listener;
  3184. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3185. Client cli("127.0.0.1", listener.port);
  3186. cli.set_read_timeout(
  3187. static_cast<time_t>((std::min)(static_cast<long long>(
  3188. (std::numeric_limits<time_t>::max)()),
  3189. 10000000000LL)),
  3190. 0);
  3191. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3192. auto peer = listener.accept();
  3193. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3194. ASSERT_NE(INVALID_SOCKET, peer);
  3195. ASSERT_TRUE(receives_a_byte(peer));
  3196. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3197. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3198. "Connection: close\r\n\r\nok";
  3199. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3200. auto result = res.get();
  3201. ASSERT_TRUE(result);
  3202. EXPECT_EQ("ok", result->body);
  3203. }
  3204. static std::string remove_whitespace(const std::string &input) {
  3205. std::string output;
  3206. output.reserve(input.size());
  3207. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3208. [](unsigned char c) { return !std::isspace(c); });
  3209. return output;
  3210. }
  3211. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3212. auto host = "httpbingo.org";
  3213. auto path = std::string{"/basic-auth/hello/world"};
  3214. #ifdef CPPHTTPLIB_SSL_ENABLED
  3215. auto port = 443;
  3216. SSLClient cli(host, port);
  3217. #else
  3218. auto port = 80;
  3219. Client cli(host, port);
  3220. #endif
  3221. {
  3222. auto res = cli.Get(path);
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3225. }
  3226. {
  3227. auto res = cli.Get(
  3228. path, Headers{make_basic_authentication_header("hello", "world")});
  3229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3230. auto body = remove_whitespace(res->body);
  3231. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3232. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3233. EXPECT_EQ(StatusCode::OK_200, res->status);
  3234. }
  3235. {
  3236. cli.set_basic_auth("hello", "world");
  3237. auto res = cli.Get(path);
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. auto body = remove_whitespace(res->body);
  3240. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3241. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. }
  3244. {
  3245. cli.set_basic_auth("hello", "bad");
  3246. auto res = cli.Get(path);
  3247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3248. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3249. }
  3250. {
  3251. cli.set_basic_auth("bad", "world");
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3255. }
  3256. }
  3257. #ifdef CPPHTTPLIB_SSL_ENABLED
  3258. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3259. auto host = "httpbingo.org";
  3260. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3261. auto paths = std::vector<std::string>{
  3262. "/digest-auth/auth/hello/world/MD5",
  3263. "/digest-auth/auth/hello/world/SHA-256",
  3264. };
  3265. auto port = 443;
  3266. SSLClient cli(host, port);
  3267. {
  3268. auto res = cli.Get(unauth_path);
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3271. }
  3272. {
  3273. cli.set_digest_auth("hello", "world");
  3274. for (const auto &path : paths) {
  3275. auto res = cli.Get(path.c_str());
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. auto body = remove_whitespace(res->body);
  3278. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3279. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. cli.set_digest_auth("hello", "bad");
  3283. for (const auto &path : paths) {
  3284. auto res = cli.Get(path.c_str());
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3287. }
  3288. }
  3289. }
  3290. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3291. // comma-separated list of challenges, and each challenge may itself carry a
  3292. // comma-separated auth-param list, so a server can legally offer Basic
  3293. // before Digest, either as two field lines or packed into one. Runs one 401
  3294. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3295. // value() joins them in receipt order) and checks that the retry carries a
  3296. // well-formed Digest Authorization header naming expected_realm.
  3297. static void
  3298. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3299. const std::string &expected_realm) {
  3300. std::atomic<int> hits{0};
  3301. Server svr;
  3302. svr.Get("/x", [&](const Request &req, Response &res) {
  3303. if (++hits == 1) {
  3304. res.status = StatusCode::Unauthorized_401;
  3305. for (const auto &challenge : challenges) {
  3306. res.set_header("WWW-Authenticate", challenge);
  3307. }
  3308. } else {
  3309. auto authorization = req.get_header_value("Authorization");
  3310. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3311. EXPECT_NE(std::string::npos,
  3312. authorization.find("realm=\"" + expected_realm + "\""));
  3313. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3314. res.set_content("ok", "text/plain");
  3315. }
  3316. });
  3317. auto port = svr.bind_to_any_port(HOST);
  3318. std::thread t([&]() { svr.listen_after_bind(); });
  3319. auto se = detail::scope_exit([&] {
  3320. svr.stop();
  3321. t.join();
  3322. });
  3323. svr.wait_until_ready();
  3324. Client cli(HOST, port);
  3325. cli.set_digest_auth("hello", "world");
  3326. auto res = cli.Get("/x");
  3327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3328. EXPECT_EQ(2, hits.load());
  3329. }
  3330. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3331. static const char *kDigestChallenge =
  3332. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3333. "algorithm=MD5";
  3334. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3335. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3336. "testrealm");
  3337. }
  3338. // Same challenge list with the schemes in the opposite order, to make sure
  3339. // the fix above didn't just special-case "Basic first".
  3340. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3341. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3342. "testrealm");
  3343. }
  3344. // A comma inside a quoted auth-param value must not be mistaken for the
  3345. // separator between two challenges (or two auth-params).
  3346. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3347. run_digest_challenge_list_test(
  3348. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3349. "algorithm=MD5"},
  3350. "test,realm");
  3351. }
  3352. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3353. // the params and leaves out the fragment.
  3354. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3355. Server svr;
  3356. std::string uri, target;
  3357. svr.Get("/a b", [&](const Request &req, Response &res) {
  3358. auto auth = req.get_header_value("Authorization");
  3359. if (auth.empty()) {
  3360. res.status = StatusCode::Unauthorized_401;
  3361. res.set_header("WWW-Authenticate",
  3362. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3363. return;
  3364. }
  3365. auto b = auth.find("uri=\"") + 5;
  3366. uri = auth.substr(b, auth.find('"', b) - b);
  3367. target = req.target;
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. std::thread t([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. t.join();
  3374. });
  3375. svr.wait_until_ready();
  3376. Client cli(HOST, port);
  3377. cli.set_digest_auth("hello", "world");
  3378. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ("/a%20b?x=1", target);
  3381. EXPECT_EQ(target, uri);
  3382. }
  3383. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3384. // make_digest_authentication_header() dereferences both unconditionally, so
  3385. // a server sending a challenge missing either one must not be treated as
  3386. // usable -- doing so used to crash the client with std::out_of_range.
  3387. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3388. Server svr;
  3389. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3390. res.status = StatusCode::Unauthorized_401;
  3391. res.set_header("WWW-Authenticate", challenge);
  3392. });
  3393. auto port = svr.bind_to_any_port(HOST);
  3394. std::thread t([&]() { svr.listen_after_bind(); });
  3395. auto se = detail::scope_exit([&] {
  3396. svr.stop();
  3397. t.join();
  3398. });
  3399. svr.wait_until_ready();
  3400. Client cli(HOST, port);
  3401. cli.set_digest_auth("hello", "world");
  3402. auto res = cli.Get("/x");
  3403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3404. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3405. }
  3406. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3407. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3408. }
  3409. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3410. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3411. }
  3412. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3413. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3414. }
  3415. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3416. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3417. // when storing the values, so the header builder has to re-escape them (and
  3418. // keep algorithm a bare token); otherwise the value breaks out of its
  3419. // quoted-string and injects extra auth-params into the client's Authorization.
  3420. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3421. std::atomic<int> hits{0};
  3422. std::string authorization;
  3423. Server svr;
  3424. svr.Get("/x", [&](const Request &req, Response &res) {
  3425. if (++hits == 1) {
  3426. res.status = StatusCode::Unauthorized_401;
  3427. // On the wire the quotes embedded in the values are backslash-escaped.
  3428. res.set_header("WWW-Authenticate",
  3429. "Digest realm=\"testrealm\", "
  3430. "nonce=\"n\\\"; injected=\\\"x\", "
  3431. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3432. } else {
  3433. authorization = req.get_header_value("Authorization");
  3434. res.set_content("ok", "text/plain");
  3435. }
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. std::thread t([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. t.join();
  3442. });
  3443. svr.wait_until_ready();
  3444. Client cli(HOST, port);
  3445. cli.set_digest_auth("hello", "world");
  3446. auto res = cli.Get("/x");
  3447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3448. EXPECT_EQ(2, hits.load());
  3449. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3450. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3451. // inside its quoted-string rather than starting an "injected" auth-param.
  3452. EXPECT_NE(std::string::npos,
  3453. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3454. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3455. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3456. }
  3457. #endif
  3458. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3459. auto host = "google.com";
  3460. auto another_host = "example.com";
  3461. auto wrong_ip = "0.0.0.0";
  3462. #ifdef CPPHTTPLIB_SSL_ENABLED
  3463. SSLClient cli(host);
  3464. #else
  3465. Client cli(host);
  3466. #endif
  3467. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3468. auto res = cli.Get("/");
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3471. }
  3472. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3473. auto host = "google.com";
  3474. auto wrong_ip = "0.0.0.0";
  3475. #ifdef CPPHTTPLIB_SSL_ENABLED
  3476. SSLClient cli(host);
  3477. #else
  3478. Client cli(host);
  3479. #endif
  3480. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3481. auto res = cli.Get("/");
  3482. ASSERT_TRUE(!res);
  3483. EXPECT_EQ(Error::Connection, res.error());
  3484. }
  3485. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3486. // A mapped value that is not an IP literal must be resolved. "localhost"
  3487. // resolves from the hosts file, so this test needs no external DNS.
  3488. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3489. auto host = "target.invalid";
  3490. Server svr;
  3491. std::string received_host;
  3492. svr.Get("/hi", [&](const Request &req, Response &res) {
  3493. received_host = req.get_header_value("Host");
  3494. res.set_content("Hello World!", "text/plain");
  3495. });
  3496. auto port = svr.bind_to_any_port(HOST);
  3497. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3498. auto se = detail::scope_exit([&] {
  3499. svr.stop();
  3500. thread.join();
  3501. ASSERT_FALSE(svr.is_running());
  3502. });
  3503. svr.wait_until_ready();
  3504. Client cli(host, port);
  3505. cli.set_direct_hostname_addr_map({{host, HOST}});
  3506. auto res = cli.Get("/hi");
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. // The mapping only redirects the connection; the identity stays host_.
  3510. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3511. }
  3512. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3513. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3514. auto host = "target.invalid";
  3515. Server svr;
  3516. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3517. res.set_content("Hello World!", "text/plain");
  3518. });
  3519. auto port = svr.bind_to_any_port("127.0.0.1");
  3520. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3521. auto se = detail::scope_exit([&] {
  3522. svr.stop();
  3523. thread.join();
  3524. ASSERT_FALSE(svr.is_running());
  3525. });
  3526. svr.wait_until_ready();
  3527. Client cli(host, port);
  3528. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3529. auto res = cli.Get("/hi");
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. }
  3533. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3534. // An empty mapped value must leave host_ as the connection target. Without
  3535. // that guard the empty value would become the host argument, getaddrinfo
  3536. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3537. // loopback - silently connecting somewhere the caller never asked for.
  3538. // The server listens on loopback, so such a fallback would succeed and is
  3539. // therefore observable as a failure of this test.
  3540. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3541. Server svr;
  3542. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3543. res.set_content("Hello World!", "text/plain");
  3544. });
  3545. auto port = svr.bind_to_any_port(HOST);
  3546. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3547. auto se = detail::scope_exit([&] {
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. });
  3552. svr.wait_until_ready();
  3553. Client cli(blackhole, port);
  3554. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3555. cli.set_connection_timeout(1);
  3556. auto res = cli.Get("/hi");
  3557. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3558. }
  3559. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3560. auto host = "target.invalid";
  3561. Server svr;
  3562. std::string received_host;
  3563. svr.Get("/hi", [&](const Request &req, Response &res) {
  3564. received_host = req.get_header_value("Host");
  3565. res.set_content("Hello World!", "text/plain");
  3566. });
  3567. auto port = svr.bind_to_any_port("127.0.0.1");
  3568. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3569. auto se = detail::scope_exit([&] {
  3570. svr.stop();
  3571. thread.join();
  3572. ASSERT_FALSE(svr.is_running());
  3573. });
  3574. svr.wait_until_ready();
  3575. Client cli(host, port);
  3576. #pragma GCC diagnostic push
  3577. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3578. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3579. #pragma GCC diagnostic pop
  3580. auto res = cli.Get("/hi");
  3581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3584. }
  3585. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3586. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  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("127.0.0.1");
  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("127.0.0.1", port);
  3600. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3601. cli.set_connection_timeout(1);
  3602. auto res = cli.Get("/hi");
  3603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3604. EXPECT_EQ(StatusCode::OK_200, res->status);
  3605. }
  3606. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3607. auto host = "httpbingo.org";
  3608. auto path = std::string{"/absolute-redirect/3"};
  3609. #ifdef CPPHTTPLIB_SSL_ENABLED
  3610. SSLClient cli(host);
  3611. #else
  3612. Client cli(host);
  3613. #endif
  3614. cli.set_follow_location(true);
  3615. auto res = cli.Get(path);
  3616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. }
  3619. TEST(RedirectTest, Redirect_Online) {
  3620. auto host = "httpbingo.org";
  3621. auto path = std::string{"/redirect/3"};
  3622. #ifdef CPPHTTPLIB_SSL_ENABLED
  3623. SSLClient cli(host);
  3624. #else
  3625. Client cli(host);
  3626. #endif
  3627. cli.set_follow_location(true);
  3628. auto res = cli.Get(path);
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. }
  3632. TEST(RelativeRedirectTest, Redirect_Online) {
  3633. auto host = "httpbingo.org";
  3634. auto path = std::string{"/relative-redirect/3"};
  3635. #ifdef CPPHTTPLIB_SSL_ENABLED
  3636. SSLClient cli(host);
  3637. #else
  3638. Client cli(host);
  3639. #endif
  3640. cli.set_follow_location(true);
  3641. auto res = cli.Get(path);
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. }
  3645. TEST(TooManyRedirectTest, Redirect_Online) {
  3646. auto host = "httpbingo.org";
  3647. auto path = std::string{"/redirect/21"};
  3648. #ifdef CPPHTTPLIB_SSL_ENABLED
  3649. SSLClient cli(host);
  3650. #else
  3651. Client cli(host);
  3652. #endif
  3653. cli.set_follow_location(true);
  3654. auto res = cli.Get(path);
  3655. ASSERT_TRUE(!res);
  3656. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3657. }
  3658. #ifdef CPPHTTPLIB_SSL_ENABLED
  3659. TEST(YahooRedirectTest, Redirect_Online) {
  3660. Client cli("yahoo.com");
  3661. auto res = cli.Get("/");
  3662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3663. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3664. cli.set_follow_location(true);
  3665. res = cli.Get("/");
  3666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3669. }
  3670. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3671. #define REDIR_HOST "httpbingo.org"
  3672. #define REDIR_PATH "/redirect-to"
  3673. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3674. SSLClient cli(REDIR_HOST);
  3675. cli.set_follow_location(true);
  3676. auto res =
  3677. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. }
  3681. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3682. SSLClient cli(REDIR_HOST);
  3683. cli.set_follow_location(true);
  3684. Params params;
  3685. params.emplace("url", "http://example.com");
  3686. params.emplace("status_code", "302");
  3687. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3689. EXPECT_EQ(StatusCode::OK_200, res->status);
  3690. }
  3691. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3692. SSLClient cli(REDIR_HOST);
  3693. cli.set_follow_location(true);
  3694. Params params;
  3695. params.emplace("url", "http://example.com");
  3696. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::OK_200, res->status);
  3699. }
  3700. TEST(UrlWithSpace, Redirect_Online) {
  3701. SSLClient cli("edge.forgecdn.net");
  3702. cli.set_follow_location(true);
  3703. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. EXPECT_EQ(StatusCode::OK_200, res->status);
  3706. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3707. }
  3708. #endif
  3709. #if !defined(_WIN32) && !defined(_WIN64)
  3710. TEST(ReceiveSignals, Signal) {
  3711. auto setupSignalHandlers = []() {
  3712. struct sigaction act;
  3713. sigemptyset(&act.sa_mask);
  3714. act.sa_flags = SA_SIGINFO;
  3715. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3716. switch (sig) {
  3717. case SIGINT:
  3718. default: break;
  3719. }
  3720. };
  3721. ::sigaction(SIGINT, &act, nullptr);
  3722. };
  3723. Server svr;
  3724. int port = 0;
  3725. auto thread = std::thread([&]() {
  3726. setupSignalHandlers();
  3727. port = svr.bind_to_any_port(HOST);
  3728. svr.listen_after_bind();
  3729. });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. ASSERT_TRUE(svr.is_running());
  3737. pthread_kill(thread.native_handle(), SIGINT);
  3738. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3739. ASSERT_TRUE(svr.is_running());
  3740. }
  3741. #endif
  3742. TEST(RedirectToDifferentPort, Redirect) {
  3743. Server svr1;
  3744. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3745. res.set_content("Hello World!", "text/plain");
  3746. });
  3747. int svr1_port = 0;
  3748. auto thread1 = std::thread([&]() {
  3749. svr1_port = svr1.bind_to_any_port(HOST);
  3750. svr1.listen_after_bind();
  3751. });
  3752. Server svr2;
  3753. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3754. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3755. });
  3756. int svr2_port = 0;
  3757. auto thread2 = std::thread([&]() {
  3758. svr2_port = svr2.bind_to_any_port(HOST);
  3759. svr2.listen_after_bind();
  3760. });
  3761. auto se = detail::scope_exit([&] {
  3762. svr2.stop();
  3763. thread2.join();
  3764. svr1.stop();
  3765. thread1.join();
  3766. ASSERT_FALSE(svr2.is_running());
  3767. ASSERT_FALSE(svr1.is_running());
  3768. });
  3769. svr1.wait_until_ready();
  3770. svr2.wait_until_ready();
  3771. Client cli("localhost", svr2_port);
  3772. cli.set_follow_location(true);
  3773. auto res = cli.Get("/2");
  3774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3775. EXPECT_EQ(StatusCode::OK_200, res->status);
  3776. EXPECT_EQ("Hello World!", res->body);
  3777. }
  3778. // GET /redir on one server redirects to /target on another port, so the
  3779. // client follows it with a new client.
  3780. static Result
  3781. GetThroughRedirectToDifferentPort(Server::Handler target,
  3782. const std::function<void(Client &)> &setup,
  3783. const Headers &headers = Headers()) {
  3784. Server target_svr;
  3785. target_svr.Get("/target", target);
  3786. int target_port = 0;
  3787. auto target_thread = std::thread([&]() {
  3788. target_port = target_svr.bind_to_any_port(HOST);
  3789. target_svr.listen_after_bind();
  3790. });
  3791. Server origin_svr;
  3792. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3793. res.set_redirect(
  3794. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3795. });
  3796. int origin_port = 0;
  3797. auto origin_thread = std::thread([&]() {
  3798. origin_port = origin_svr.bind_to_any_port(HOST);
  3799. origin_svr.listen_after_bind();
  3800. });
  3801. auto se = detail::scope_exit([&] {
  3802. origin_svr.stop();
  3803. origin_thread.join();
  3804. target_svr.stop();
  3805. target_thread.join();
  3806. });
  3807. target_svr.wait_until_ready();
  3808. origin_svr.wait_until_ready();
  3809. Client cli("localhost", origin_port);
  3810. cli.set_follow_location(true);
  3811. setup(cli);
  3812. return cli.Get("/redir", headers);
  3813. }
  3814. static void
  3815. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3816. std::string captured_authorization;
  3817. auto result = GetThroughRedirectToDifferentPort(
  3818. [&](const Request &req, Response &res) {
  3819. captured_authorization = req.get_header_value("Authorization");
  3820. res.set_content("OK", "text/plain");
  3821. },
  3822. set_auth);
  3823. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3824. EXPECT_EQ(StatusCode::OK_200, result->status);
  3825. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3826. EXPECT_TRUE(captured_authorization.empty());
  3827. }
  3828. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3829. TestDoNotForwardCredentialsOnRedirect(
  3830. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3831. }
  3832. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3833. TestDoNotForwardCredentialsOnRedirect(
  3834. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3835. }
  3836. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3837. std::string captured_cookie;
  3838. auto result = GetThroughRedirectToDifferentPort(
  3839. [&](const Request &req, Response &res) {
  3840. captured_cookie = req.get_header_value("Cookie");
  3841. res.set_content("OK", "text/plain");
  3842. },
  3843. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3844. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3845. EXPECT_EQ(StatusCode::OK_200, result->status);
  3846. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3847. EXPECT_TRUE(captured_cookie.empty());
  3848. }
  3849. TEST(RedirectToSamePort, ForwardCookie) {
  3850. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3851. // header so that ordinary session flows keep working.
  3852. Server svr;
  3853. std::string captured_cookie;
  3854. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3855. res.set_redirect("/target", 302);
  3856. });
  3857. svr.Get("/target", [&](const Request &req, Response &res) {
  3858. captured_cookie = req.get_header_value("Cookie");
  3859. res.set_content("OK", "text/plain");
  3860. });
  3861. auto port = svr.bind_to_any_port(HOST);
  3862. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3863. auto se = detail::scope_exit([&] {
  3864. svr.stop();
  3865. thread.join();
  3866. ASSERT_FALSE(svr.is_running());
  3867. });
  3868. svr.wait_until_ready();
  3869. Client cli(HOST, port);
  3870. cli.set_follow_location(true);
  3871. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3872. auto res = cli.Get("/redir", headers);
  3873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3874. EXPECT_EQ(StatusCode::OK_200, res->status);
  3875. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3876. }
  3877. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3878. // The Location alone names the next target, on any origin.
  3879. Server target_svr;
  3880. std::string cross_target;
  3881. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3882. cross_target = req.target;
  3883. res.set_content("OK", "text/plain");
  3884. });
  3885. auto target_port = target_svr.bind_to_any_port(HOST);
  3886. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3887. Server origin_svr;
  3888. std::string same_target;
  3889. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3890. res.set_redirect(
  3891. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3892. });
  3893. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3894. res.set_redirect("/landing", 302);
  3895. });
  3896. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3897. same_target = req.target;
  3898. res.set_content("OK", "text/plain");
  3899. });
  3900. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3901. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3902. auto se = detail::scope_exit([&] {
  3903. origin_svr.stop();
  3904. origin_thread.join();
  3905. target_svr.stop();
  3906. target_thread.join();
  3907. });
  3908. target_svr.wait_until_ready();
  3909. origin_svr.wait_until_ready();
  3910. Client cli("localhost", origin_port);
  3911. cli.set_follow_location(true);
  3912. Request req;
  3913. req.method = "GET";
  3914. req.params = {{"api_key", "SECRET"}};
  3915. req.path = "/cross";
  3916. auto res = cli.send(req);
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ("/landing", cross_target);
  3919. req.path = "/same";
  3920. res = cli.send(req);
  3921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3922. EXPECT_EQ("/landing", same_target);
  3923. }
  3924. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3925. std::string authorization;
  3926. std::string trace_id;
  3927. auto result = GetThroughRedirectToDifferentPort(
  3928. [&](const Request &req, Response &res) {
  3929. authorization = req.get_header_value("Authorization");
  3930. trace_id = req.get_header_value("X-Trace-Id");
  3931. res.set_content("OK", "text/plain");
  3932. },
  3933. [](Client &cli) {
  3934. cli.set_default_headers(
  3935. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3936. });
  3937. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3938. EXPECT_EQ(StatusCode::OK_200, result->status);
  3939. // Like a header given with the request, a default one goes along unless it
  3940. // carries credentials (RFC 9110 15.4).
  3941. EXPECT_TRUE(authorization.empty());
  3942. EXPECT_EQ("42", trace_id);
  3943. }
  3944. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3945. auto result = GetThroughRedirectToDifferentPort(
  3946. [](const Request &, Response &res) {
  3947. res.set_content(std::string(2048, 'x'), "text/plain");
  3948. },
  3949. [](Client &cli) { cli.set_payload_max_length(1024); });
  3950. EXPECT_FALSE(result);
  3951. }
  3952. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3953. auto result = GetThroughRedirectToDifferentPort(
  3954. [](const Request &req, Response &res) {
  3955. // Answer after a second, or once the client gives up.
  3956. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3957. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3958. }
  3959. res.set_content("late", "text/plain");
  3960. },
  3961. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3962. ASSERT_FALSE(result);
  3963. EXPECT_EQ(Error::Read, result.error());
  3964. }
  3965. #ifdef CPPHTTPLIB_SSL_ENABLED
  3966. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3967. auto result = GetThroughRedirectToDifferentPort(
  3968. [](const Request &, Response &res) {
  3969. res.status = StatusCode::Unauthorized_401;
  3970. res.set_header("WWW-Authenticate",
  3971. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3972. },
  3973. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3974. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3975. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3976. }
  3977. #endif
  3978. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3979. Server svr;
  3980. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3981. // Port number that overflows int — should not crash
  3982. res.set_redirect("http://localhost:99999999999999999999/target");
  3983. });
  3984. auto port = svr.bind_to_any_port(HOST);
  3985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3986. auto se = detail::scope_exit([&] {
  3987. svr.stop();
  3988. thread.join();
  3989. ASSERT_FALSE(svr.is_running());
  3990. });
  3991. svr.wait_until_ready();
  3992. Client cli(HOST, port);
  3993. cli.set_follow_location(true);
  3994. auto res = cli.Get("/redir");
  3995. // Should fail gracefully, not crash (no valid response due to bad port)
  3996. EXPECT_FALSE(res);
  3997. }
  3998. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3999. Server svr;
  4000. auto port = svr.bind_to_any_port(HOST);
  4001. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4002. // The server's own port followed by junk must not be followed
  4003. res.set_redirect("http://" + std::string(HOST) + ":" +
  4004. std::to_string(port) + "junk/target");
  4005. });
  4006. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4007. res.set_content("target", "text/plain");
  4008. });
  4009. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4010. auto se = detail::scope_exit([&] {
  4011. svr.stop();
  4012. thread.join();
  4013. ASSERT_FALSE(svr.is_running());
  4014. });
  4015. svr.wait_until_ready();
  4016. Client cli(HOST, port);
  4017. cli.set_follow_location(true);
  4018. auto res = cli.Get("/redir");
  4019. EXPECT_FALSE(res);
  4020. }
  4021. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4022. Server target_svr;
  4023. std::atomic<int> target_hits{0};
  4024. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4025. target_hits++;
  4026. res.set_content("target", "text/plain");
  4027. });
  4028. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4029. res.set_content("target", "text/plain");
  4030. });
  4031. int target_port = 0;
  4032. auto target_thread = std::thread([&]() {
  4033. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4034. target_svr.listen_after_bind();
  4035. });
  4036. Server origin_svr;
  4037. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4038. res.set_redirect(req.get_param_value("to"));
  4039. });
  4040. int origin_port = 0;
  4041. auto origin_thread = std::thread([&]() {
  4042. origin_port = origin_svr.bind_to_any_port(HOST);
  4043. origin_svr.listen_after_bind();
  4044. });
  4045. auto se = detail::scope_exit([&] {
  4046. origin_svr.stop();
  4047. origin_thread.join();
  4048. target_svr.stop();
  4049. target_thread.join();
  4050. ASSERT_FALSE(origin_svr.is_running());
  4051. ASSERT_FALSE(target_svr.is_running());
  4052. });
  4053. target_svr.wait_until_ready();
  4054. origin_svr.wait_until_ready();
  4055. auto port = std::to_string(target_port);
  4056. for (const auto &to :
  4057. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4058. Client cli(HOST, origin_port);
  4059. cli.set_follow_location(true);
  4060. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4061. EXPECT_FALSE(res) << to;
  4062. }
  4063. EXPECT_EQ(0, target_hits);
  4064. Client cli(HOST, origin_port);
  4065. cli.set_follow_location(true);
  4066. auto res = cli.Get("/redir?to=" +
  4067. encode_query_component("//127.0.0.1:" + port + "/target"));
  4068. ASSERT_TRUE(res) << to_string(res.error());
  4069. EXPECT_EQ(StatusCode::OK_200, res->status);
  4070. EXPECT_EQ("target", res->body);
  4071. }
  4072. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4073. Server svr;
  4074. std::atomic<bool> followed{false};
  4075. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4076. res.status = StatusCode::NotModified_304;
  4077. res.set_header("Location", "/target");
  4078. });
  4079. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::UseProxy_305;
  4081. res.set_header("Location", "/target");
  4082. });
  4083. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4084. followed = true;
  4085. res.set_content("target", "text/plain");
  4086. });
  4087. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4088. auto se = detail::scope_exit([&] {
  4089. svr.stop();
  4090. th.join();
  4091. ASSERT_FALSE(svr.is_running());
  4092. });
  4093. svr.wait_until_ready();
  4094. Client cli("localhost", PORT);
  4095. cli.set_follow_location(true);
  4096. auto res = cli.Get("/304");
  4097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4098. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4099. res = cli.Get("/305");
  4100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4101. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4102. EXPECT_FALSE(followed);
  4103. }
  4104. TEST(RedirectFromPageWithContent, Redirect) {
  4105. Server svr;
  4106. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4107. res.set_content("___", "text/plain");
  4108. res.set_redirect("/2");
  4109. });
  4110. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4111. res.set_content("Hello World!", "text/plain");
  4112. });
  4113. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4114. auto se = detail::scope_exit([&] {
  4115. svr.stop();
  4116. th.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. svr.wait_until_ready();
  4120. {
  4121. Client cli("localhost", PORT);
  4122. cli.set_follow_location(true);
  4123. std::string body;
  4124. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4125. body.append(data, data_length);
  4126. return true;
  4127. });
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ(StatusCode::OK_200, res->status);
  4130. EXPECT_EQ("Hello World!", body);
  4131. }
  4132. {
  4133. Client cli("localhost", PORT);
  4134. std::string body;
  4135. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4136. body.append(data, data_length);
  4137. return true;
  4138. });
  4139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4140. EXPECT_EQ(StatusCode::Found_302, res->status);
  4141. EXPECT_EQ("___", body);
  4142. }
  4143. }
  4144. // A server can close the connection after a request with "Connection: close"
  4145. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4146. // redirected request must go out on a new connection.
  4147. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4148. #ifndef _WIN32
  4149. signal(SIGPIPE, SIG_IGN);
  4150. #endif
  4151. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4152. default_socket_options(srv);
  4153. sockaddr_in addr{};
  4154. addr.sin_family = AF_INET;
  4155. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4156. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4157. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4158. ASSERT_EQ(0, ::listen(srv, 2));
  4159. auto send_text = [](socket_t sock, const std::string &text) {
  4160. ::send(sock,
  4161. #ifdef _WIN32
  4162. static_cast<const char *>(text.c_str()),
  4163. static_cast<int>(text.size()),
  4164. #else
  4165. text.c_str(), text.size(),
  4166. #endif
  4167. 0);
  4168. };
  4169. auto reused = false;
  4170. auto server_thread = std::thread([&] {
  4171. char buf[4096];
  4172. auto first = ::accept(srv, nullptr, nullptr);
  4173. if (first == INVALID_SOCKET) { return; }
  4174. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4175. ::recv(first, buf, sizeof(buf), 0);
  4176. send_text(
  4177. first,
  4178. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4179. auto next = first;
  4180. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4181. reused = true;
  4182. } else {
  4183. detail::close_socket(first);
  4184. next = ::accept(srv, nullptr, nullptr);
  4185. if (next == INVALID_SOCKET) { return; }
  4186. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4187. ::recv(next, buf, sizeof(buf), 0);
  4188. }
  4189. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4190. "Connection: close\r\n\r\nok");
  4191. detail::close_socket(next);
  4192. });
  4193. Client cli("127.0.0.1", PORT + 2);
  4194. cli.set_follow_location(true);
  4195. cli.set_read_timeout(5, 0);
  4196. auto res = cli.Get("/1");
  4197. server_thread.join();
  4198. detail::close_socket(srv);
  4199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4200. EXPECT_EQ(StatusCode::OK_200, res->status);
  4201. EXPECT_EQ("ok", res->body);
  4202. EXPECT_FALSE(reused);
  4203. }
  4204. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4205. Server svr;
  4206. auto port_str = std::to_string(PORT);
  4207. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4208. auto expected_host = "[::1]:" + port_str;
  4209. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4210. res.set_content("___", "text/plain");
  4211. // res.set_redirect("/2");
  4212. res.set_redirect(redirect_url);
  4213. });
  4214. svr.Get("/2", [&](const Request &req, Response &res) {
  4215. auto host_header = req.headers.find("Host");
  4216. ASSERT_TRUE(host_header != req.headers.end());
  4217. EXPECT_EQ(expected_host, host_header->second);
  4218. res.set_content("Hello World!", "text/plain");
  4219. });
  4220. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4221. auto se = detail::scope_exit([&] {
  4222. svr.stop();
  4223. th.join();
  4224. ASSERT_FALSE(svr.is_running());
  4225. });
  4226. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4227. // actually starts anything, so the condition !svr.is_running() will
  4228. // always remain true, and the loop never stops.
  4229. // This basically counts how many milliseconds have passed since the
  4230. // call to svr.listen(), and if after 5 seconds nothing started yet
  4231. // aborts the test.
  4232. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4233. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4234. ASSERT_LT(milliseconds, 5000U);
  4235. }
  4236. {
  4237. Client cli("::1", PORT);
  4238. cli.set_follow_location(true);
  4239. std::string body;
  4240. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4241. body.append(data, data_length);
  4242. return true;
  4243. });
  4244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4245. EXPECT_EQ(StatusCode::OK_200, res->status);
  4246. EXPECT_EQ("Hello World!", body);
  4247. }
  4248. {
  4249. Client cli("::1", PORT);
  4250. std::string body;
  4251. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4252. body.append(data, data_length);
  4253. return true;
  4254. });
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ(StatusCode::Found_302, res->status);
  4257. EXPECT_EQ("___", body);
  4258. }
  4259. }
  4260. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4261. Server svr;
  4262. svr.Get("/foo", [](const Request &req, Response &res) {
  4263. auto a = req.params.find("a");
  4264. if (a != req.params.end()) {
  4265. res.set_content((*a).second, "text/plain");
  4266. res.status = StatusCode::OK_200;
  4267. } else {
  4268. res.status = StatusCode::BadRequest_400;
  4269. }
  4270. });
  4271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4272. auto se = detail::scope_exit([&] {
  4273. svr.stop();
  4274. thread.join();
  4275. ASSERT_FALSE(svr.is_running());
  4276. });
  4277. svr.wait_until_ready();
  4278. {
  4279. Client cli(HOST, PORT);
  4280. cli.set_path_encode(false);
  4281. auto res = cli.Get("/foo?a=explicitly+encoded");
  4282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. // This expects it back with a space, as the `+` won't have been
  4285. // url-encoded, and server-side the params get decoded turning `+`
  4286. // into spaces.
  4287. EXPECT_EQ("explicitly encoded", res->body);
  4288. }
  4289. }
  4290. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4291. // When path encoding is disabled the client must transmit the supplied
  4292. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4293. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4294. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4295. // than a space (0x20). Assert on the raw wire target to catch this.
  4296. Server svr;
  4297. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4298. svr.Get("/foo", [&](const Request &req, Response &res) {
  4299. EXPECT_EQ(expected_target, req.target);
  4300. res.status = StatusCode::OK_200;
  4301. });
  4302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4303. auto se = detail::scope_exit([&] {
  4304. svr.stop();
  4305. thread.join();
  4306. ASSERT_FALSE(svr.is_running());
  4307. });
  4308. svr.wait_until_ready();
  4309. {
  4310. Client cli(HOST, PORT);
  4311. cli.set_path_encode(false);
  4312. auto res = cli.Get(expected_target.c_str());
  4313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4314. EXPECT_EQ(StatusCode::OK_200, res->status);
  4315. }
  4316. }
  4317. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4318. // `open_stream()` used to skip the path encoding that the buffered send
  4319. // path applies, so the same `path` produced different bytes in the request
  4320. // line depending on which API was used. Assert the two agree.
  4321. Server svr;
  4322. std::string target;
  4323. svr.Get(".*", [&](const Request &req, Response &res) {
  4324. target = req.target;
  4325. res.status = StatusCode::OK_200;
  4326. });
  4327. auto port = svr.bind_to_any_port(HOST);
  4328. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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. struct {
  4336. const char *path;
  4337. const char *expected;
  4338. } cases[] = {
  4339. {"/a b?x=1", "/a%20b?x=1"},
  4340. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4341. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4342. };
  4343. for (const auto &c : cases) {
  4344. Client cli(HOST, port);
  4345. target.clear();
  4346. auto res = cli.Get(c.path);
  4347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4348. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4349. auto buffered_target = target;
  4350. target.clear();
  4351. auto handle = cli.open_stream("GET", c.path);
  4352. EXPECT_TRUE(handle.is_valid())
  4353. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4354. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4355. }
  4356. }
  4357. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4358. // The `set_path_encode(false)` contract — transmit the supplied target
  4359. // verbatim — must hold for the streaming API too.
  4360. Server svr;
  4361. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4362. std::string target;
  4363. svr.Get("/foo", [&](const Request &req, Response &res) {
  4364. target = req.target;
  4365. res.status = StatusCode::OK_200;
  4366. });
  4367. auto port = svr.bind_to_any_port(HOST);
  4368. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4369. auto se = detail::scope_exit([&] {
  4370. svr.stop();
  4371. thread.join();
  4372. ASSERT_FALSE(svr.is_running());
  4373. });
  4374. svr.wait_until_ready();
  4375. {
  4376. Client cli(HOST, port);
  4377. cli.set_path_encode(false);
  4378. auto handle = cli.open_stream("GET", expected_target);
  4379. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4380. EXPECT_EQ(expected_target, target);
  4381. }
  4382. }
  4383. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4384. // With path encoding enabled a CR/LF in the target is percent-encoded
  4385. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4386. // write_request_line still backstops `set_path_encode(false)`, which is
  4387. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4388. Server svr;
  4389. // Captured before routing: the decoded path contains a newline, which a
  4390. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4391. std::string target;
  4392. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4393. target = req.target;
  4394. res.status = StatusCode::OK_200;
  4395. return Server::HandlerResponse::Handled;
  4396. });
  4397. auto port = svr.bind_to_any_port(HOST);
  4398. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4399. auto se = detail::scope_exit([&] {
  4400. svr.stop();
  4401. thread.join();
  4402. ASSERT_FALSE(svr.is_running());
  4403. });
  4404. svr.wait_until_ready();
  4405. {
  4406. Client cli(HOST, port);
  4407. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4408. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4409. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4410. }
  4411. }
  4412. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4413. // Every control character is percent-encoded, not just CR/LF, so the target
  4414. // passes the request-target check in write_request_line.
  4415. Server svr;
  4416. std::string target;
  4417. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4418. target = req.target;
  4419. res.status = StatusCode::OK_200;
  4420. return Server::HandlerResponse::Handled;
  4421. });
  4422. auto port = svr.bind_to_any_port(HOST);
  4423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4424. auto se = detail::scope_exit([&] {
  4425. svr.stop();
  4426. thread.join();
  4427. ASSERT_FALSE(svr.is_running());
  4428. });
  4429. svr.wait_until_ready();
  4430. {
  4431. Client cli(HOST, port);
  4432. auto res = cli.Get("/a\tb\x1b\x7f");
  4433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4434. EXPECT_EQ("/a%09b%1B%7F", target);
  4435. }
  4436. }
  4437. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4438. // Nothing may reach the wire: a raw CR/LF target would split the request
  4439. // line and inject headers.
  4440. Server svr;
  4441. // Pre-routing so that "not called" means nothing reached the server at all,
  4442. // rather than merely failing to match a handler pattern.
  4443. auto handler_called = false;
  4444. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4445. handler_called = true;
  4446. res.status = StatusCode::OK_200;
  4447. return Server::HandlerResponse::Handled;
  4448. });
  4449. auto port = svr.bind_to_any_port(HOST);
  4450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4451. auto se = detail::scope_exit([&] {
  4452. svr.stop();
  4453. thread.join();
  4454. ASSERT_FALSE(svr.is_running());
  4455. });
  4456. svr.wait_until_ready();
  4457. {
  4458. Client cli(HOST, port);
  4459. cli.set_path_encode(false);
  4460. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4461. EXPECT_FALSE(handle.is_valid());
  4462. EXPECT_EQ(Error::Write, handle.error);
  4463. EXPECT_FALSE(handler_called);
  4464. }
  4465. }
  4466. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4467. // Which of the two branches runs is decided by whether the query component
  4468. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4469. // an empty query and must still fall back to building one from
  4470. // `req.params`, while a non-empty query must win over `req.params`.
  4471. Server svr;
  4472. std::string target;
  4473. svr.Get("/foo", [&](const Request &req, Response &res) {
  4474. target = req.target;
  4475. res.status = StatusCode::OK_200;
  4476. });
  4477. auto port = svr.bind_to_any_port(HOST);
  4478. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4479. auto se = detail::scope_exit([&] {
  4480. svr.stop();
  4481. thread.join();
  4482. ASSERT_FALSE(svr.is_running());
  4483. });
  4484. svr.wait_until_ready();
  4485. {
  4486. // Trailing `?` -> empty query component -> `req.params` is used.
  4487. Client cli(HOST, port);
  4488. Request req;
  4489. req.method = "GET";
  4490. req.path = "/foo?";
  4491. req.params.emplace("a", "1");
  4492. target.clear();
  4493. auto res = cli.send(req);
  4494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4495. EXPECT_EQ("/foo?a=1", target);
  4496. }
  4497. {
  4498. // Non-empty query in `req.path` -> `req.params` is not appended.
  4499. Client cli(HOST, port);
  4500. Request req;
  4501. req.method = "GET";
  4502. req.path = "/foo?b=2";
  4503. req.params.emplace("a", "1");
  4504. target.clear();
  4505. auto res = cli.send(req);
  4506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4507. EXPECT_EQ("/foo?b=2", target);
  4508. }
  4509. }
  4510. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4511. Server svr;
  4512. svr.Get("/", [](const Request &req, Response &) {
  4513. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4514. });
  4515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4516. auto se = detail::scope_exit([&] {
  4517. svr.stop();
  4518. thread.join();
  4519. ASSERT_FALSE(svr.is_running());
  4520. });
  4521. svr.wait_until_ready();
  4522. {
  4523. Client cli(HOST, PORT);
  4524. cli.set_path_encode(false);
  4525. auto res = cli.Get("/?something=%0A");
  4526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. }
  4529. }
  4530. TEST(BindServerTest, BindDualStack) {
  4531. Server svr;
  4532. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4533. res.set_content("Hello World!", "text/plain");
  4534. });
  4535. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  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. Client cli("127.0.0.1", PORT);
  4544. auto res = cli.Get("/1");
  4545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("Hello World!", res->body);
  4548. }
  4549. {
  4550. Client cli("::1", PORT);
  4551. auto res = cli.Get("/1");
  4552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("Hello World!", res->body);
  4555. }
  4556. }
  4557. TEST(BindServerTest, BindAndListenSeparately) {
  4558. Server svr;
  4559. int port = svr.bind_to_any_port("0.0.0.0");
  4560. ASSERT_TRUE(svr.is_valid());
  4561. ASSERT_TRUE(port > 0);
  4562. svr.stop();
  4563. }
  4564. // Reports whether anything is still listening on a loopback port. A plain
  4565. // connect() is used instead of a Client request because a socket left bound by
  4566. // mistake accepts the connection into its backlog and never answers, which
  4567. // would hang the test instead of failing it.
  4568. static bool is_loopback_port_accepting(int port) {
  4569. sockaddr_in addr{};
  4570. addr.sin_family = AF_INET;
  4571. addr.sin_port = htons(static_cast<uint16_t>(port));
  4572. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4573. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4574. EXPECT_NE(sock, INVALID_SOCKET);
  4575. if (sock == INVALID_SOCKET) { return false; }
  4576. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4577. static_cast<socklen_t>(sizeof(addr)));
  4578. detail::close_socket(sock);
  4579. return ret == 0;
  4580. }
  4581. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4582. Server svr;
  4583. auto port = svr.bind_to_any_port("127.0.0.1");
  4584. ASSERT_TRUE(port > 0);
  4585. svr.stop();
  4586. // bind_to_any_port() already called listen(2), so until stop() closed the
  4587. // descriptor the port kept accepting connections into the backlog. ASSERT
  4588. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4589. // below blocks forever in the accept loop.
  4590. ASSERT_FALSE(is_loopback_port_accepting(port));
  4591. // Nothing is left to accept on, so listen_after_bind() must report failure
  4592. // instead of returning success without ever serving.
  4593. EXPECT_FALSE(svr.listen_after_bind());
  4594. // The failed listen marks the server decommissioned, so a waiter returns
  4595. // instead of spinning forever.
  4596. svr.wait_until_ready();
  4597. }
  4598. #ifdef CPPHTTPLIB_SSL_ENABLED
  4599. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4601. CLIENT_CA_CERT_DIR);
  4602. int port = svr.bind_to_any_port("0.0.0.0");
  4603. ASSERT_TRUE(svr.is_valid());
  4604. ASSERT_TRUE(port > 0);
  4605. svr.stop();
  4606. }
  4607. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4608. // or a rejected CustomRoute() registration would not stop the server binding.
  4609. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4611. CLIENT_CA_CERT_DIR);
  4612. ASSERT_TRUE(svr.is_valid());
  4613. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4614. EXPECT_FALSE(svr.is_valid());
  4615. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4616. }
  4617. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4618. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4619. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4620. int port = svr.bind_to_any_port("0.0.0.0");
  4621. ASSERT_TRUE(svr.is_valid());
  4622. ASSERT_TRUE(port > 0);
  4623. svr.stop();
  4624. }
  4625. TEST(BindServerTest, UpdateCertsPem) {
  4626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4627. int port = svr.bind_to_any_port("0.0.0.0");
  4628. ASSERT_TRUE(svr.is_valid());
  4629. ASSERT_TRUE(port > 0);
  4630. // Read PEM files
  4631. std::string cert_pem, key_pem, ca_pem;
  4632. read_file(SERVER_CERT_FILE, cert_pem);
  4633. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4634. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4635. // Update server certificates using PEM API
  4636. ASSERT_TRUE(
  4637. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4638. ASSERT_TRUE(svr.is_valid());
  4639. svr.stop();
  4640. }
  4641. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4642. // Start server with client CA (enables client auth)
  4643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4644. ASSERT_TRUE(svr.is_valid());
  4645. bool handler_called = false;
  4646. svr.Get("/test", [&](const Request &req, Response &res) {
  4647. handler_called = true;
  4648. // Verify client certificate is present
  4649. auto cert = req.peer_cert();
  4650. EXPECT_TRUE(static_cast<bool>(cert));
  4651. res.set_content("ok", "text/plain");
  4652. });
  4653. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4654. auto se = detail::scope_exit([&] {
  4655. svr.stop();
  4656. t.join();
  4657. ASSERT_FALSE(svr.is_running());
  4658. });
  4659. svr.wait_until_ready();
  4660. // Read PEM files
  4661. std::string cert_pem, key_pem, ca_pem;
  4662. read_file(SERVER_CERT_FILE, cert_pem);
  4663. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4664. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4665. // Update server certificates and client CA using PEM API while server running
  4666. ASSERT_TRUE(
  4667. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4668. // Connect with client certificate
  4669. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4670. cli.enable_server_certificate_verification(false);
  4671. cli.set_connection_timeout(30);
  4672. auto res = cli.Get("/test");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_TRUE(handler_called);
  4676. EXPECT_EQ("ok", res->body);
  4677. }
  4678. // Puts a CA that did not sign the client's certificate in the old one's place.
  4679. static bool replace_client_ca(SSLServer &svr) {
  4680. std::string cert_pem, key_pem, ca_pem;
  4681. read_file(SERVER_CERT_FILE, cert_pem);
  4682. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4683. read_file(SERVER_CERT2_FILE, ca_pem);
  4684. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4685. ca_pem.c_str());
  4686. }
  4687. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4689. ASSERT_TRUE(svr.is_valid());
  4690. svr.Get("/test", [](const Request &, Response &res) {
  4691. res.set_content("ok", "text/plain");
  4692. });
  4693. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4694. auto se = detail::scope_exit([&] {
  4695. svr.stop();
  4696. t.join();
  4697. ASSERT_FALSE(svr.is_running());
  4698. });
  4699. svr.wait_until_ready();
  4700. auto get = [] {
  4701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4702. cli.enable_server_certificate_verification(false);
  4703. return cli.Get("/test");
  4704. };
  4705. ASSERT_TRUE(get());
  4706. ASSERT_TRUE(replace_client_ca(svr));
  4707. EXPECT_FALSE(get());
  4708. }
  4709. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4710. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4712. ASSERT_TRUE(svr.is_valid());
  4713. tls::set_verify_callback(svr.tls_context(),
  4714. [](const tls::VerifyContext &) -> bool {
  4715. throw std::runtime_error("verify");
  4716. });
  4717. svr.Get("/test", [](const Request &, Response &res) {
  4718. res.set_content("ok", "text/plain");
  4719. });
  4720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4721. auto se = detail::scope_exit([&] {
  4722. svr.stop();
  4723. t.join();
  4724. ASSERT_FALSE(svr.is_running());
  4725. });
  4726. svr.wait_until_ready();
  4727. auto get = [] {
  4728. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4729. cli.enable_server_certificate_verification(false);
  4730. return cli.Get("/test");
  4731. };
  4732. EXPECT_FALSE(get());
  4733. // The handshake is over, so an update does not wait for it.
  4734. std::string cert_pem, key_pem;
  4735. read_file(SERVER_CERT_FILE, cert_pem);
  4736. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4737. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4738. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4739. return v.preverify_ok;
  4740. });
  4741. auto res = get();
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. EXPECT_EQ("ok", res->body);
  4744. }
  4745. #endif
  4746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4747. // Sends each request over a new connection with a client certificate,
  4748. // resuming the session of the one before when there is one.
  4749. class ResumingClient {
  4750. public:
  4751. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4752. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4753. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4754. SSL_FILETYPE_PEM);
  4755. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4756. // callback, not through SSL_get1_session().
  4757. SSL_CTX_set_app_data(ctx_, this);
  4758. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4759. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4760. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4761. auto self = static_cast<ResumingClient *>(
  4762. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4763. SSL_SESSION_free(self->session_);
  4764. self->session_ = session;
  4765. return 1; // Keeps the reference
  4766. });
  4767. }
  4768. ~ResumingClient() {
  4769. SSL_SESSION_free(session_);
  4770. SSL_CTX_free(ctx_);
  4771. }
  4772. // Tells whether the request was answered.
  4773. bool get() {
  4774. auto error = Error::Success;
  4775. auto sock = detail::create_client_socket(
  4776. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4777. /*connection_timeout_sec=*/5, 0,
  4778. /*read_timeout_sec=*/5, 0,
  4779. /*write_timeout_sec=*/5, 0, std::string(), error);
  4780. if (sock == INVALID_SOCKET) { return false; }
  4781. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4782. auto ssl = SSL_new(ctx_);
  4783. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4784. SSL_set_fd(ssl, static_cast<int>(sock));
  4785. if (session_) { SSL_set_session(ssl, session_); }
  4786. if (SSL_connect(ssl) != 1) { return false; }
  4787. reused_ = SSL_session_reused(ssl) == 1;
  4788. // Reading the response also takes in a TLS 1.3 session ticket.
  4789. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4790. "Connection: close\r\n\r\n";
  4791. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4792. std::string res;
  4793. char buf[256];
  4794. int n;
  4795. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4796. res.append(buf, static_cast<size_t>(n));
  4797. }
  4798. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4799. SSL_shutdown(ssl);
  4800. return res.find("200 OK") != std::string::npos;
  4801. }
  4802. // Whether the last connection resumed a session
  4803. bool reused() const { return reused_; }
  4804. private:
  4805. SSL_CTX *ctx_;
  4806. SSL_SESSION *session_ = nullptr;
  4807. bool reused_ = false;
  4808. };
  4809. // A client that resumes its session gets through, but not once the client CA
  4810. // has changed, as a resumed session does not show the certificate again.
  4811. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4813. ASSERT_TRUE(svr.is_valid());
  4814. svr.Get("/test", [](const Request &, Response &res) {
  4815. res.set_content("ok", "text/plain");
  4816. });
  4817. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4818. auto se = detail::scope_exit([&] {
  4819. svr.stop();
  4820. t.join();
  4821. ASSERT_FALSE(svr.is_running());
  4822. });
  4823. svr.wait_until_ready();
  4824. ResumingClient cli;
  4825. ASSERT_TRUE(cli.get());
  4826. ASSERT_TRUE(cli.get());
  4827. EXPECT_TRUE(cli.reused());
  4828. ASSERT_TRUE(replace_client_ca(svr));
  4829. EXPECT_FALSE(cli.get());
  4830. }
  4831. // A resumed session does not show the certificate again, so the server does
  4832. // not resume one with a verify callback to run on it.
  4833. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4835. ASSERT_TRUE(svr.is_valid());
  4836. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4837. return v.preverify_ok;
  4838. });
  4839. svr.Get("/test", [](const Request &, Response &res) {
  4840. res.set_content("ok", "text/plain");
  4841. });
  4842. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4843. auto se = detail::scope_exit([&] {
  4844. svr.stop();
  4845. t.join();
  4846. ASSERT_FALSE(svr.is_running());
  4847. });
  4848. svr.wait_until_ready();
  4849. ResumingClient cli;
  4850. ASSERT_TRUE(cli.get());
  4851. ASSERT_TRUE(cli.get());
  4852. EXPECT_FALSE(cli.reused());
  4853. }
  4854. #endif
  4855. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4856. // wolfSSL shares its session cache between contexts, so a resumed session
  4857. // could carry a client certificate checked against another server's CA, or
  4858. // against a client CA since replaced.
  4859. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4861. ASSERT_TRUE(svr.is_valid());
  4862. // Trusts a CA that did not sign the client's certificate.
  4863. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4864. ASSERT_TRUE(other.is_valid());
  4865. for (auto s : {&svr, &other}) {
  4866. s->Get("/test", [](const Request &, Response &res) {
  4867. res.set_content("ok", "text/plain");
  4868. });
  4869. }
  4870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4871. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4872. auto se = detail::scope_exit([&] {
  4873. other.stop();
  4874. svr.stop();
  4875. t2.join();
  4876. t.join();
  4877. });
  4878. svr.wait_until_ready();
  4879. other.wait_until_ready();
  4880. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4881. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4882. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4883. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4884. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4885. ASSERT_EQ(WOLFSSL_SUCCESS,
  4886. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4887. WOLFSSL_FILETYPE_PEM));
  4888. WOLFSSL_SESSION *session = nullptr;
  4889. auto session_se = detail::scope_exit([&] {
  4890. if (session) { wolfSSL_SESSION_free(session); }
  4891. });
  4892. // A request over a new connection, resuming `session` when there is one and
  4893. // keeping the connection's own in its place. Tells whether it was answered.
  4894. auto get = [&](int port) {
  4895. auto error = Error::Success;
  4896. auto sock = detail::create_client_socket(
  4897. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4898. /*connection_timeout_sec=*/5, 0,
  4899. /*read_timeout_sec=*/5, 0,
  4900. /*write_timeout_sec=*/5, 0, std::string(), error);
  4901. if (sock == INVALID_SOCKET) { return false; }
  4902. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4903. auto ssl = wolfSSL_new(ctx);
  4904. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4905. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4906. if (session) { wolfSSL_set_session(ssl, session); }
  4907. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4908. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4909. "Connection: close\r\n\r\n";
  4910. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4911. std::string res;
  4912. char buf[256];
  4913. int n;
  4914. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4915. res.append(buf, static_cast<size_t>(n));
  4916. }
  4917. wolfSSL_shutdown(ssl);
  4918. if (session) { wolfSSL_SESSION_free(session); }
  4919. session = wolfSSL_get1_session(ssl);
  4920. return res.find("200 OK") != std::string::npos;
  4921. };
  4922. ASSERT_TRUE(get(PORT));
  4923. EXPECT_FALSE(get(PORT + 1));
  4924. ASSERT_TRUE(get(PORT));
  4925. ASSERT_TRUE(replace_client_ca(svr));
  4926. EXPECT_FALSE(get(PORT));
  4927. }
  4928. #endif
  4929. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4931. ASSERT_TRUE(svr.is_valid());
  4932. svr.Get("/test", [](const Request &, Response &res) {
  4933. res.set_content("ok", "text/plain");
  4934. });
  4935. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4936. auto se = detail::scope_exit([&] {
  4937. svr.stop();
  4938. t.join();
  4939. ASSERT_FALSE(svr.is_running());
  4940. });
  4941. svr.wait_until_ready();
  4942. // A connection that sends no ClientHello keeps its handshake in progress,
  4943. // once the server has had a moment to start it.
  4944. auto error = Error::Success;
  4945. auto sock = detail::create_client_socket(
  4946. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4947. /*connection_timeout_sec=*/5, 0,
  4948. /*read_timeout_sec=*/5, 0,
  4949. /*write_timeout_sec=*/5, 0, std::string(), error);
  4950. ASSERT_NE(INVALID_SOCKET, sock);
  4951. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4952. std::string cert_pem, key_pem;
  4953. read_file(SERVER_CERT_FILE, cert_pem);
  4954. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4955. auto update = std::async(std::launch::async, [&]() {
  4956. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4957. });
  4958. EXPECT_EQ(std::future_status::timeout,
  4959. update.wait_for(std::chrono::milliseconds(200)));
  4960. detail::close_socket(sock);
  4961. EXPECT_TRUE(update.get());
  4962. SSLClient cli(HOST, PORT);
  4963. cli.enable_server_certificate_verification(false);
  4964. auto res = cli.Get("/test");
  4965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4966. EXPECT_EQ(StatusCode::OK_200, res->status);
  4967. }
  4968. #endif
  4969. TEST(ErrorHandlerTest, ContentLength) {
  4970. Server svr;
  4971. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4972. res.status = StatusCode::OK_200;
  4973. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4974. "text/html"); // <= Content-Length still 13
  4975. });
  4976. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4977. res.set_content("Hello World!\n", "text/plain");
  4978. res.status = 524;
  4979. });
  4980. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4981. auto se = detail::scope_exit([&] {
  4982. svr.stop();
  4983. thread.join();
  4984. ASSERT_FALSE(svr.is_running());
  4985. });
  4986. svr.wait_until_ready();
  4987. {
  4988. Client cli(HOST, PORT);
  4989. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4993. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4994. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4995. }
  4996. }
  4997. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4998. TEST(ExceptionTest, WithoutExceptionHandler) {
  4999. Server svr;
  5000. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5001. throw std::runtime_error("exception...");
  5002. });
  5003. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5004. throw std::runtime_error("exception\r\n...");
  5005. });
  5006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5007. auto se = detail::scope_exit([&] {
  5008. svr.stop();
  5009. listen_thread.join();
  5010. ASSERT_FALSE(svr.is_running());
  5011. });
  5012. svr.wait_until_ready();
  5013. Client cli("localhost", PORT);
  5014. {
  5015. auto res = cli.Get("/exception");
  5016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5017. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5018. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5019. }
  5020. {
  5021. auto res = cli.Get("/unknown");
  5022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5023. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5024. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5025. }
  5026. }
  5027. TEST(ExceptionTest, WithExceptionHandler) {
  5028. Server svr;
  5029. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5030. std::exception_ptr ep) {
  5031. EXPECT_FALSE(ep == nullptr);
  5032. try {
  5033. std::rethrow_exception(ep);
  5034. } catch (std::exception &e) {
  5035. EXPECT_EQ("abc", std::string(e.what()));
  5036. } catch (...) {}
  5037. res.status = StatusCode::InternalServerError_500;
  5038. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5039. "text/html"); // <= Content-Length still 13 at this point
  5040. });
  5041. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5042. res.set_content("Hello World!\n", "text/plain");
  5043. throw std::runtime_error("abc");
  5044. });
  5045. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5046. auto se = detail::scope_exit([&] {
  5047. svr.stop();
  5048. thread.join();
  5049. ASSERT_FALSE(svr.is_running());
  5050. });
  5051. svr.wait_until_ready();
  5052. for (size_t i = 0; i < 10; i++) {
  5053. Client cli(HOST, PORT);
  5054. for (size_t j = 0; j < 100; j++) {
  5055. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5058. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5059. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5060. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5061. }
  5062. cli.set_keep_alive(true);
  5063. for (size_t j = 0; j < 100; j++) {
  5064. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5066. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5067. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5068. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5069. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5070. }
  5071. }
  5072. }
  5073. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5074. Server svr;
  5075. svr.set_exception_handler(
  5076. [](const Request &, Response &res, std::exception_ptr) {
  5077. res.set_content("oops", "text/plain");
  5078. });
  5079. svr.Get("/throw", [](const Request &, Response &) {
  5080. throw std::runtime_error("throw");
  5081. });
  5082. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5083. res.status = StatusCode::Created_201;
  5084. throw std::runtime_error("created-then-throw");
  5085. });
  5086. auto port = svr.bind_to_any_port(HOST);
  5087. ASSERT_GT(port, 0);
  5088. thread t = thread([&] { svr.listen_after_bind(); });
  5089. auto se = detail::scope_exit([&] {
  5090. svr.stop();
  5091. t.join();
  5092. ASSERT_FALSE(svr.is_running());
  5093. });
  5094. svr.wait_until_ready();
  5095. Client cli(HOST, port);
  5096. for (auto path : {"/throw", "/created-then-throw"}) {
  5097. auto res = cli.Get(path);
  5098. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5099. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5100. }
  5101. }
  5102. TEST(ExceptionTest, AndErrorHandler) {
  5103. Server svr;
  5104. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5105. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5106. });
  5107. svr.set_exception_handler(
  5108. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5109. EXPECT_FALSE(ep == nullptr);
  5110. try {
  5111. std::rethrow_exception(ep);
  5112. } catch (std::exception &e) {
  5113. res.set_content(e.what(), "text/html");
  5114. } catch (...) {}
  5115. res.status = StatusCode::InternalServerError_500;
  5116. });
  5117. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5118. throw std::runtime_error("EXCEPTION");
  5119. });
  5120. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5121. res.set_content("ERROR", "text/html");
  5122. res.status = StatusCode::InternalServerError_500;
  5123. });
  5124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5125. auto se = detail::scope_exit([&] {
  5126. svr.stop();
  5127. thread.join();
  5128. ASSERT_FALSE(svr.is_running());
  5129. });
  5130. svr.wait_until_ready();
  5131. Client cli(HOST, PORT);
  5132. {
  5133. auto res = cli.Get("/exception");
  5134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5135. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5136. EXPECT_EQ("EXCEPTION", res->body);
  5137. }
  5138. {
  5139. auto res = cli.Get("/error");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5142. EXPECT_EQ("ERROR", res->body);
  5143. }
  5144. {
  5145. auto res = cli.Get("/invalid");
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5148. EXPECT_EQ("NOT_FOUND", res->body);
  5149. }
  5150. }
  5151. #endif
  5152. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5153. // An exception from a user callback outside process_request()'s try/catch
  5154. // used to unwind into the task queue - which does not catch - and terminate
  5155. // the process. Each test below runs the server on a single worker thread: a
  5156. // guard that catches the exception but still loses the thread would otherwise
  5157. // be hidden by a spare worker serving the follow-up request. Note that a
  5158. // regression here aborts the whole test binary rather than failing one test.
  5159. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5160. Server svr;
  5161. svr.new_task_queue = [] { return new ThreadPool(1); };
  5162. std::atomic<int> reported{0};
  5163. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5164. if (err == Error::UserCallbackException) { reported++; }
  5165. });
  5166. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5167. res.set_content_provider(
  5168. 1024, "text/plain",
  5169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5170. sink.write("hello", 5);
  5171. throw std::runtime_error("from the content provider");
  5172. });
  5173. });
  5174. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5175. res.set_content("ok", "text/plain");
  5176. });
  5177. auto port = svr.bind_to_any_port(HOST);
  5178. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5179. auto se = detail::scope_exit([&] {
  5180. svr.stop();
  5181. listen_thread.join();
  5182. ASSERT_FALSE(svr.is_running());
  5183. });
  5184. svr.wait_until_ready();
  5185. {
  5186. Client cli(HOST, port);
  5187. cli.set_read_timeout(5, 0);
  5188. EXPECT_FALSE(cli.Get("/throw"));
  5189. }
  5190. EXPECT_TRUE(svr.is_running());
  5191. EXPECT_EQ(1, reported.load());
  5192. // A request on a fresh connection is still served.
  5193. {
  5194. Client cli(HOST, port);
  5195. auto res = cli.Get("/ok");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. EXPECT_EQ("ok", res->body);
  5199. }
  5200. }
  5201. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5202. Server svr;
  5203. svr.new_task_queue = [] { return new ThreadPool(1); };
  5204. std::atomic<bool> should_throw{true};
  5205. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5206. res.set_content("hi", "text/plain");
  5207. });
  5208. svr.set_post_routing_handler(
  5209. [&](const Request & /*req*/, Response & /*res*/) {
  5210. if (should_throw) {
  5211. throw std::runtime_error("from the post-routing handler");
  5212. }
  5213. });
  5214. auto port = svr.bind_to_any_port(HOST);
  5215. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5216. auto se = detail::scope_exit([&] {
  5217. svr.stop();
  5218. listen_thread.join();
  5219. ASSERT_FALSE(svr.is_running());
  5220. });
  5221. svr.wait_until_ready();
  5222. {
  5223. Client cli(HOST, port);
  5224. cli.set_read_timeout(5, 0);
  5225. EXPECT_FALSE(cli.Get("/hi"));
  5226. }
  5227. EXPECT_TRUE(svr.is_running());
  5228. should_throw = false;
  5229. {
  5230. Client cli(HOST, port);
  5231. auto res = cli.Get("/hi");
  5232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5233. EXPECT_EQ(StatusCode::OK_200, res->status);
  5234. EXPECT_EQ("hi", res->body);
  5235. }
  5236. }
  5237. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5238. // The guard reports the caught exception through the error logger, which is
  5239. // a user callback too. A logger that throws has to be contained as well, or
  5240. // the process would terminate from inside the catch.
  5241. Server svr;
  5242. svr.new_task_queue = [] { return new ThreadPool(1); };
  5243. std::atomic<int> reported{0};
  5244. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5245. if (err == Error::UserCallbackException) {
  5246. reported++;
  5247. throw std::runtime_error("from the error logger");
  5248. }
  5249. });
  5250. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5251. res.set_content_provider(
  5252. 1024, "text/plain",
  5253. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5254. sink.write("hello", 5);
  5255. throw std::runtime_error("from the content provider");
  5256. });
  5257. });
  5258. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5259. res.set_content("ok", "text/plain");
  5260. });
  5261. auto port = svr.bind_to_any_port(HOST);
  5262. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5263. auto se = detail::scope_exit([&] {
  5264. svr.stop();
  5265. listen_thread.join();
  5266. ASSERT_FALSE(svr.is_running());
  5267. });
  5268. svr.wait_until_ready();
  5269. {
  5270. Client cli(HOST, port);
  5271. cli.set_read_timeout(5, 0);
  5272. EXPECT_FALSE(cli.Get("/throw"));
  5273. }
  5274. EXPECT_TRUE(svr.is_running());
  5275. EXPECT_EQ(1, reported.load());
  5276. {
  5277. Client cli(HOST, port);
  5278. auto res = cli.Get("/ok");
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. EXPECT_EQ("ok", res->body);
  5282. }
  5283. }
  5284. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5285. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5286. // so the exception unwinds through the ws::WebSocket object on its way to
  5287. // the guard. None of the HTTP cases above cross that.
  5288. Server svr;
  5289. svr.new_task_queue = [] { return new ThreadPool(1); };
  5290. std::atomic<int> reported{0};
  5291. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5292. if (err == Error::UserCallbackException) { reported++; }
  5293. });
  5294. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5295. throw std::runtime_error("from the WebSocket handler");
  5296. });
  5297. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5298. res.set_content("ok", "text/plain");
  5299. });
  5300. auto port = svr.bind_to_any_port(HOST);
  5301. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5302. auto se = detail::scope_exit([&] {
  5303. svr.stop();
  5304. listen_thread.join();
  5305. ASSERT_FALSE(svr.is_running());
  5306. });
  5307. svr.wait_until_ready();
  5308. {
  5309. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5310. "/ws");
  5311. auto res = client.connect();
  5312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5313. // The server dropped the connection instead of dying.
  5314. std::string msg;
  5315. EXPECT_FALSE(client.read(msg));
  5316. client.close();
  5317. }
  5318. EXPECT_TRUE(svr.is_running());
  5319. EXPECT_EQ(1, reported.load());
  5320. {
  5321. Client cli(HOST, port);
  5322. auto res = cli.Get("/ok");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. EXPECT_EQ(StatusCode::OK_200, res->status);
  5325. EXPECT_EQ("ok", res->body);
  5326. }
  5327. }
  5328. #ifdef CPPHTTPLIB_SSL_ENABLED
  5329. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5330. // SSLServer::process_and_close_socket() is a separate overload with its own
  5331. // guard, so it is exercised on its own.
  5332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5333. ASSERT_TRUE(svr.is_valid());
  5334. svr.new_task_queue = [] { return new ThreadPool(1); };
  5335. std::atomic<int> reported{0};
  5336. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5337. if (err == Error::UserCallbackException) { reported++; }
  5338. });
  5339. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5340. res.set_content_provider(
  5341. 1024, "text/plain",
  5342. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5343. sink.write("hello", 5);
  5344. throw std::runtime_error("from the content provider");
  5345. });
  5346. });
  5347. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5348. res.set_content("ok", "text/plain");
  5349. });
  5350. auto port = svr.bind_to_any_port(HOST);
  5351. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5352. auto se = detail::scope_exit([&] {
  5353. svr.stop();
  5354. listen_thread.join();
  5355. ASSERT_FALSE(svr.is_running());
  5356. });
  5357. svr.wait_until_ready();
  5358. {
  5359. SSLClient cli(HOST, port);
  5360. cli.enable_server_certificate_verification(false);
  5361. cli.set_read_timeout(5, 0);
  5362. EXPECT_FALSE(cli.Get("/throw"));
  5363. }
  5364. EXPECT_TRUE(svr.is_running());
  5365. EXPECT_EQ(1, reported.load());
  5366. {
  5367. SSLClient cli(HOST, port);
  5368. cli.enable_server_certificate_verification(false);
  5369. auto res = cli.Get("/ok");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ(StatusCode::OK_200, res->status);
  5372. EXPECT_EQ("ok", res->body);
  5373. }
  5374. }
  5375. #endif
  5376. #endif
  5377. TEST(NoContentTest, ContentLength) {
  5378. Server svr;
  5379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5380. res.status = StatusCode::NoContent_204;
  5381. });
  5382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5383. auto se = detail::scope_exit([&] {
  5384. svr.stop();
  5385. thread.join();
  5386. ASSERT_FALSE(svr.is_running());
  5387. });
  5388. svr.wait_until_ready();
  5389. {
  5390. Client cli(HOST, PORT);
  5391. auto res = cli.Get("/hi");
  5392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5393. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5394. // RFC 9110 8.6: none in a 204 response
  5395. EXPECT_FALSE(res->has_header("Content-Length"));
  5396. }
  5397. }
  5398. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5399. Server svr;
  5400. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5401. res.set_header("Content-Length", "5");
  5402. res.set_content("hello world", "text/plain");
  5403. });
  5404. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5405. // A body that reads as the last chunk, were it taken as chunked
  5406. res.set_header("Transfer-Encoding", "chunked");
  5407. res.set_content("0\r\n\r\n", "text/plain");
  5408. });
  5409. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5410. res.set_header("Content-Length", "2");
  5411. res.set_content_provider(5, "text/plain",
  5412. [](size_t offset, size_t length, DataSink &sink) {
  5413. sink.write(&"hello"[offset], length);
  5414. return true;
  5415. });
  5416. });
  5417. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5418. res.set_header("Content-Length", "1234");
  5419. });
  5420. thread t = thread([&] { svr.listen(HOST, PORT); });
  5421. auto se = detail::scope_exit([&] {
  5422. svr.stop();
  5423. t.join();
  5424. ASSERT_FALSE(svr.is_running());
  5425. });
  5426. svr.wait_until_ready();
  5427. Client cli(HOST, PORT);
  5428. cli.set_read_timeout(1, 0);
  5429. auto expect_body = [&](const Result &res, const std::string &body) {
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. EXPECT_EQ(body, res->body);
  5432. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5433. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5434. };
  5435. Headers identity{{"Accept-Encoding", ""}};
  5436. expect_body(cli.Get("/body", identity), "hello world");
  5437. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5438. expect_body(cli.Get("/body",
  5439. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5440. "he");
  5441. expect_body(cli.Get("/provider", identity), "hello");
  5442. expect_body(cli.Get("/empty", identity), "");
  5443. // A HEAD response may give the length of the body a GET would get.
  5444. auto res = cli.Head("/empty");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5447. }
  5448. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5449. Server svr;
  5450. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5451. res.set_content("short", "text/plain");
  5452. });
  5453. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5454. res.body += " with a footer";
  5455. res.set_header("Transfer-Encoding", "chunked");
  5456. });
  5457. thread t = thread([&] { svr.listen(HOST, PORT); });
  5458. auto se = detail::scope_exit([&] {
  5459. svr.stop();
  5460. t.join();
  5461. ASSERT_FALSE(svr.is_running());
  5462. });
  5463. svr.wait_until_ready();
  5464. Client cli(HOST, PORT);
  5465. cli.set_read_timeout(1, 0);
  5466. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ("short with a footer", res->body);
  5469. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5470. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5471. }
  5472. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5473. Server svr;
  5474. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5475. res.set_header("Content-Length", "3");
  5476. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5477. sink.write("abc", 3);
  5478. sink.done();
  5479. return true;
  5480. });
  5481. });
  5482. thread t = thread([&] { svr.listen(HOST, PORT); });
  5483. auto se = detail::scope_exit([&] {
  5484. svr.stop();
  5485. t.join();
  5486. ASSERT_FALSE(svr.is_running());
  5487. });
  5488. svr.wait_until_ready();
  5489. Client cli(HOST, PORT);
  5490. cli.set_keep_alive(true);
  5491. auto res = cli.Get("/");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ("abc", res->body);
  5494. EXPECT_FALSE(res->has_header("Content-Length"));
  5495. EXPECT_EQ("close", res->get_header_value("Connection"));
  5496. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5497. // No body to delimit
  5498. auto head = cli.Head("/");
  5499. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5500. EXPECT_FALSE(head->has_header("Connection"));
  5501. }
  5502. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5503. #ifdef CPPHTTPLIB_SSL_ENABLED
  5504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5505. ASSERT_TRUE(svr.is_valid());
  5506. #else
  5507. Server svr;
  5508. #endif
  5509. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5510. if (req.path == "/routing_handler") {
  5511. res.set_header("PRE_ROUTING", "on");
  5512. res.set_content("Routing Handler", "text/plain");
  5513. return httplib::Server::HandlerResponse::Handled;
  5514. }
  5515. return httplib::Server::HandlerResponse::Unhandled;
  5516. });
  5517. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5518. res.set_content("Error", "text/html");
  5519. });
  5520. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5521. if (req.path == "/routing_handler") {
  5522. res.set_header("POST_ROUTING", "on");
  5523. }
  5524. });
  5525. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5526. res.set_content("Hello World!\n", "text/plain");
  5527. });
  5528. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5529. auto se = detail::scope_exit([&] {
  5530. svr.stop();
  5531. thread.join();
  5532. ASSERT_FALSE(svr.is_running());
  5533. });
  5534. svr.wait_until_ready();
  5535. {
  5536. #ifdef CPPHTTPLIB_SSL_ENABLED
  5537. SSLClient cli(HOST, PORT);
  5538. cli.enable_server_certificate_verification(false);
  5539. #else
  5540. Client cli(HOST, PORT);
  5541. #endif
  5542. auto res = cli.Get("/routing_handler");
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ(StatusCode::OK_200, res->status);
  5545. EXPECT_EQ("Routing Handler", res->body);
  5546. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5547. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5548. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5549. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5550. }
  5551. {
  5552. #ifdef CPPHTTPLIB_SSL_ENABLED
  5553. SSLClient cli(HOST, PORT);
  5554. cli.enable_server_certificate_verification(false);
  5555. #else
  5556. Client cli(HOST, PORT);
  5557. #endif
  5558. auto res = cli.Get("/hi");
  5559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. EXPECT_EQ("Hello World!\n", res->body);
  5562. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5563. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5564. }
  5565. {
  5566. #ifdef CPPHTTPLIB_SSL_ENABLED
  5567. SSLClient cli(HOST, PORT);
  5568. cli.enable_server_certificate_verification(false);
  5569. #else
  5570. Client cli(HOST, PORT);
  5571. #endif
  5572. auto res = cli.Get("/aaa");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5575. EXPECT_EQ("Error", res->body);
  5576. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5577. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5578. }
  5579. }
  5580. TEST(RequestHandlerTest, PreRequestHandler) {
  5581. auto route_path = "/user/:user";
  5582. Server svr;
  5583. svr.Get("/hi", [](const Request &, Response &res) {
  5584. res.set_content("hi", "text/plain");
  5585. });
  5586. svr.Get(route_path, [](const Request &req, Response &res) {
  5587. res.set_content(req.path_params.at("user"), "text/plain");
  5588. });
  5589. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5590. if (req.matched_route == route_path) {
  5591. auto user = req.path_params.at("user");
  5592. if (user != "john") {
  5593. res.status = StatusCode::Forbidden_403;
  5594. res.set_content("error", "text/html");
  5595. return Server::HandlerResponse::Handled;
  5596. }
  5597. }
  5598. return Server::HandlerResponse::Unhandled;
  5599. });
  5600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5601. auto se = detail::scope_exit([&] {
  5602. svr.stop();
  5603. thread.join();
  5604. ASSERT_FALSE(svr.is_running());
  5605. });
  5606. svr.wait_until_ready();
  5607. Client cli(HOST, PORT);
  5608. {
  5609. auto res = cli.Get("/hi");
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ("hi", res->body);
  5613. }
  5614. {
  5615. auto res = cli.Get("/user/john");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::OK_200, res->status);
  5618. EXPECT_EQ("john", res->body);
  5619. }
  5620. {
  5621. auto res = cli.Get("/user/invalid-user");
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5624. EXPECT_EQ("error", res->body);
  5625. }
  5626. }
  5627. // The pre-request handler must run before the request body is read, so a
  5628. // rejected request never forces the server to buffer a (potentially large)
  5629. // body. Here the posted body is larger than the payload limit: if the body
  5630. // were read first the server would answer 413, but because the pre-request
  5631. // handler runs first it answers 403 and the body is never read.
  5632. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5633. Server svr;
  5634. svr.set_payload_max_length(8);
  5635. auto handler_ran = false;
  5636. svr.Post("/reject", [&](const Request &req, Response &res) {
  5637. handler_ran = true;
  5638. res.set_content(req.body, "text/plain");
  5639. });
  5640. svr.Post("/accept", [](const Request &req, Response &res) {
  5641. res.set_content(req.body, "text/plain");
  5642. });
  5643. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5644. if (req.matched_route == "/reject") {
  5645. res.status = StatusCode::Forbidden_403;
  5646. res.set_content("denied", "text/plain");
  5647. return Server::HandlerResponse::Handled;
  5648. }
  5649. return Server::HandlerResponse::Unhandled;
  5650. });
  5651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5652. auto se = detail::scope_exit([&] {
  5653. svr.stop();
  5654. thread.join();
  5655. ASSERT_FALSE(svr.is_running());
  5656. });
  5657. svr.wait_until_ready();
  5658. Client cli(HOST, PORT);
  5659. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5660. // rejects with 403 before the body is read, so 413 is never reached.
  5661. {
  5662. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5665. EXPECT_EQ("denied", res->body);
  5666. EXPECT_FALSE(handler_ran);
  5667. }
  5668. // An approved route still reads the body and enforces the payload limit.
  5669. {
  5670. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5673. }
  5674. }
  5675. TEST(UserDataTest, BasicOperations) {
  5676. httplib::UserData ud;
  5677. // Initially empty
  5678. EXPECT_FALSE(ud.has("key"));
  5679. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5680. // set and get
  5681. ud.set("key", 42);
  5682. EXPECT_TRUE(ud.has("key"));
  5683. auto *p = ud.get<int>("key");
  5684. ASSERT_NE(nullptr, p);
  5685. EXPECT_EQ(42, *p);
  5686. // Type mismatch → nullptr
  5687. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5688. // Overwrite with different type
  5689. ud.set("key", std::string("hello"));
  5690. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5691. auto *s = ud.get<std::string>("key");
  5692. ASSERT_NE(nullptr, s);
  5693. EXPECT_EQ("hello", *s);
  5694. // erase
  5695. ud.erase("key");
  5696. EXPECT_FALSE(ud.has("key"));
  5697. // clear
  5698. ud.set("a", 1);
  5699. ud.set("b", 2);
  5700. ud.clear();
  5701. EXPECT_FALSE(ud.has("a"));
  5702. EXPECT_FALSE(ud.has("b"));
  5703. }
  5704. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5705. struct AuthCtx {
  5706. std::string user_id;
  5707. };
  5708. Server svr;
  5709. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5710. res.user_data.set("auth", AuthCtx{"alice"});
  5711. return Server::HandlerResponse::Unhandled;
  5712. });
  5713. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5714. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5715. ASSERT_NE(nullptr, ctx);
  5716. res.set_content("Hello " + ctx->user_id, "text/plain");
  5717. });
  5718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5719. auto se = detail::scope_exit([&] {
  5720. svr.stop();
  5721. thread.join();
  5722. ASSERT_FALSE(svr.is_running());
  5723. });
  5724. svr.wait_until_ready();
  5725. Client cli(HOST, PORT);
  5726. auto res = cli.Get("/me");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. EXPECT_EQ("Hello alice", res->body);
  5730. }
  5731. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5732. struct RoleCtx {
  5733. std::string role;
  5734. };
  5735. Server svr;
  5736. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5737. res.user_data.set("role", RoleCtx{"admin"});
  5738. return Server::HandlerResponse::Unhandled;
  5739. });
  5740. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5741. auto *ctx = res.user_data.get<RoleCtx>("role");
  5742. ASSERT_NE(nullptr, ctx);
  5743. res.set_content(ctx->role, "text/plain");
  5744. });
  5745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5746. auto se = detail::scope_exit([&] {
  5747. svr.stop();
  5748. thread.join();
  5749. ASSERT_FALSE(svr.is_running());
  5750. });
  5751. svr.wait_until_ready();
  5752. Client cli(HOST, PORT);
  5753. auto res = cli.Get("/role");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. EXPECT_EQ("admin", res->body);
  5757. }
  5758. TEST(InvalidFormatTest, StatusCode) {
  5759. Server svr;
  5760. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5761. res.set_content("Hello World!\n", "text/plain");
  5762. res.status = 9999; // Status should be a three-digit code...
  5763. });
  5764. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5765. auto se = detail::scope_exit([&] {
  5766. svr.stop();
  5767. thread.join();
  5768. ASSERT_FALSE(svr.is_running());
  5769. });
  5770. svr.wait_until_ready();
  5771. {
  5772. Client cli(HOST, PORT);
  5773. auto res = cli.Get("/hi");
  5774. ASSERT_FALSE(res);
  5775. }
  5776. }
  5777. TEST(URLFragmentTest, WithFragment) {
  5778. Server svr;
  5779. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5780. EXPECT_TRUE(req.target == "/hi");
  5781. });
  5782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5783. auto se = detail::scope_exit([&] {
  5784. svr.stop();
  5785. thread.join();
  5786. ASSERT_FALSE(svr.is_running());
  5787. });
  5788. svr.wait_until_ready();
  5789. {
  5790. Client cli(HOST, PORT);
  5791. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5792. EXPECT_TRUE(res);
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. res = cli.Get("/hi%23key1=val1=key2=val2");
  5795. EXPECT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5797. }
  5798. }
  5799. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5800. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5801. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5802. Server svr;
  5803. std::vector<std::string> targets;
  5804. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5805. targets.push_back(req.target);
  5806. });
  5807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5808. auto se = detail::scope_exit([&] {
  5809. svr.stop();
  5810. thread.join();
  5811. ASSERT_FALSE(svr.is_running());
  5812. });
  5813. svr.wait_until_ready();
  5814. Client cli(HOST, PORT);
  5815. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5816. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5817. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5818. // A '?' after the '#' belongs to the fragment, not to the query.
  5819. Request req;
  5820. req.method = "GET";
  5821. req.path = "/hi#f?x=1";
  5822. req.params.emplace("a", "1");
  5823. Response res;
  5824. auto error = Error::Success;
  5825. EXPECT_TRUE(cli.send(req, res, error));
  5826. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5827. "/hi?a=1"}),
  5828. targets);
  5829. }
  5830. TEST(HeaderWriter, SetHeaderWriter) {
  5831. Server svr;
  5832. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5833. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5834. return detail::write_headers(strm, hdrs);
  5835. });
  5836. svr.Get("/hi", [](const Request &req, Response &res) {
  5837. auto it = req.headers.find("CustomClientHeader");
  5838. EXPECT_TRUE(it != req.headers.end());
  5839. EXPECT_EQ(it->second, "CustomClientValue");
  5840. res.set_content("Hello World!\n", "text/plain");
  5841. });
  5842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5843. auto se = detail::scope_exit([&] {
  5844. svr.stop();
  5845. thread.join();
  5846. ASSERT_FALSE(svr.is_running());
  5847. });
  5848. svr.wait_until_ready();
  5849. {
  5850. Client cli(HOST, PORT);
  5851. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5852. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5853. return detail::write_headers(strm, hdrs);
  5854. });
  5855. auto res = cli.Get("/hi");
  5856. EXPECT_TRUE(res);
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. auto it = res->headers.find("CustomServerHeader");
  5859. EXPECT_TRUE(it != res->headers.end());
  5860. EXPECT_EQ(it->second, "CustomServerValue");
  5861. }
  5862. }
  5863. class ServerTest : public ::testing::Test {
  5864. protected:
  5865. ServerTest()
  5866. : cli_(HOST, PORT)
  5867. #ifdef CPPHTTPLIB_SSL_ENABLED
  5868. ,
  5869. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5870. #endif
  5871. {
  5872. #ifdef CPPHTTPLIB_SSL_ENABLED
  5873. cli_.enable_server_certificate_verification(false);
  5874. #endif
  5875. // Allow LARGE_DATA (100MB) responses
  5876. cli_.set_payload_max_length(200 * 1024 * 1024);
  5877. }
  5878. virtual void SetUp() {
  5879. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5880. svr_.set_payload_max_length(200 * 1024 * 1024);
  5881. svr_.set_mount_point("/", "./www");
  5882. svr_.set_mount_point("/mount", "./www2");
  5883. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5884. svr_.Get("/hi",
  5885. [&](const Request & /*req*/, Response &res) {
  5886. res.set_content("Hello World!", "text/plain");
  5887. })
  5888. .Get("/file_content",
  5889. [&](const Request & /*req*/, Response &res) {
  5890. res.set_file_content("./www/dir/test.html");
  5891. })
  5892. .Get("/file_content_with_content_type",
  5893. [&](const Request & /*req*/, Response &res) {
  5894. res.set_file_content("./www/file", "text/plain");
  5895. })
  5896. .Get("/invalid_file_content",
  5897. [&](const Request & /*req*/, Response &res) {
  5898. res.set_file_content("./www/dir/invalid_file_path");
  5899. })
  5900. .Get("/http_response_splitting",
  5901. [&](const Request & /*req*/, Response &res) {
  5902. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5903. EXPECT_EQ(0U, res.headers.size());
  5904. EXPECT_FALSE(res.has_header("a"));
  5905. res.set_header("a", "1\nSet-Cookie: a=1");
  5906. EXPECT_EQ(0U, res.headers.size());
  5907. EXPECT_FALSE(res.has_header("a"));
  5908. res.set_header("a", "1\rSet-Cookie: a=1");
  5909. EXPECT_EQ(0U, res.headers.size());
  5910. EXPECT_FALSE(res.has_header("a"));
  5911. res.set_header("a\r\nb", "0");
  5912. EXPECT_EQ(0U, res.headers.size());
  5913. EXPECT_FALSE(res.has_header("a"));
  5914. res.set_header("a\rb", "0");
  5915. EXPECT_EQ(0U, res.headers.size());
  5916. EXPECT_FALSE(res.has_header("a"));
  5917. res.set_header("a\nb", "0");
  5918. EXPECT_EQ(0U, res.headers.size());
  5919. EXPECT_FALSE(res.has_header("a"));
  5920. res.set_redirect("1\r\nSet-Cookie: a=1");
  5921. EXPECT_EQ(0U, res.headers.size());
  5922. EXPECT_FALSE(res.has_header("Location"));
  5923. })
  5924. .Get("/slow",
  5925. [&](const Request & /*req*/, Response &res) {
  5926. std::this_thread::sleep_for(std::chrono::seconds(4));
  5927. res.set_content("slow", "text/plain");
  5928. })
  5929. #if 0
  5930. .Post("/slowpost",
  5931. [&](const Request & /*req*/, Response &res) {
  5932. std::this_thread::sleep_for(std::chrono::seconds(2));
  5933. res.set_content("slow", "text/plain");
  5934. })
  5935. #endif
  5936. .Get("/remote_addr",
  5937. [&](const Request &req, Response &res) {
  5938. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5939. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5941. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5942. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5943. #endif
  5944. res.set_content(req.remote_addr, "text/plain");
  5945. })
  5946. .Get("/local_addr",
  5947. [&](const Request &req, Response &res) {
  5948. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5949. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5950. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5951. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5952. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5953. #endif
  5954. auto local_addr = req.local_addr;
  5955. auto local_port = std::to_string(req.local_port);
  5956. res.set_content(local_addr.append(":").append(local_port),
  5957. "text/plain");
  5958. })
  5959. .Get("/endwith%",
  5960. [&](const Request & /*req*/, Response &res) {
  5961. res.set_content("Hello World!", "text/plain");
  5962. })
  5963. .Get("/a\\+\\+b",
  5964. [&](const Request &req, Response &res) {
  5965. ASSERT_TRUE(req.has_param("a +b"));
  5966. auto val = req.get_param_value("a +b");
  5967. res.set_content(val, "text/plain");
  5968. })
  5969. .Get("/", [&](const Request & /*req*/,
  5970. Response &res) { res.set_redirect("/hi"); })
  5971. .Post("/1",
  5972. [](const Request & /*req*/, Response &res) {
  5973. res.set_redirect("/2", StatusCode::SeeOther_303);
  5974. })
  5975. .Get("/2",
  5976. [](const Request & /*req*/, Response &res) {
  5977. res.set_content("redirected.", "text/plain");
  5978. res.status = StatusCode::OK_200;
  5979. })
  5980. .Post("/person",
  5981. [&](const Request &req, Response &res) {
  5982. if (req.has_param("name") && req.has_param("note")) {
  5983. persons_[req.get_param_value("name")] =
  5984. req.get_param_value("note");
  5985. } else {
  5986. res.status = StatusCode::BadRequest_400;
  5987. }
  5988. })
  5989. .Put("/person",
  5990. [&](const Request &req, Response &res) {
  5991. if (req.has_param("name") && req.has_param("note")) {
  5992. persons_[req.get_param_value("name")] =
  5993. req.get_param_value("note");
  5994. } else {
  5995. res.status = StatusCode::BadRequest_400;
  5996. }
  5997. })
  5998. .Get("/person/(.*)",
  5999. [&](const Request &req, Response &res) {
  6000. string name = req.matches[1];
  6001. if (persons_.find(name) != persons_.end()) {
  6002. auto note = persons_[name];
  6003. res.set_content(note, "text/plain");
  6004. } else {
  6005. res.status = StatusCode::NotFound_404;
  6006. }
  6007. })
  6008. .Delete("/person",
  6009. [&](const Request &req, Response &res) {
  6010. if (req.has_param("name")) {
  6011. string name = req.get_param_value("name");
  6012. if (persons_.find(name) != persons_.end()) {
  6013. persons_.erase(name);
  6014. res.set_content("DELETED", "text/plain");
  6015. } else {
  6016. res.status = StatusCode::NotFound_404;
  6017. }
  6018. } else {
  6019. res.status = StatusCode::BadRequest_400;
  6020. }
  6021. })
  6022. .Post("/x-www-form-urlencoded-json",
  6023. [&](const Request &req, Response &res) {
  6024. auto json = req.get_param_value("json");
  6025. ASSERT_EQ(JSON_DATA, json);
  6026. res.set_content(json, "appliation/json");
  6027. res.status = StatusCode::OK_200;
  6028. })
  6029. .Get("/streamed-chunked",
  6030. [&](const Request & /*req*/, Response &res) {
  6031. res.set_chunked_content_provider(
  6032. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6033. sink.os << "123";
  6034. sink.os << "456";
  6035. sink.os << "789";
  6036. sink.done();
  6037. return true;
  6038. });
  6039. })
  6040. .Get("/streamed-chunked-with-prohibited-trailer",
  6041. [&](const Request & /*req*/, Response &res) {
  6042. auto i = new int(0);
  6043. // Declare both a prohibited trailer (Content-Length) and an
  6044. // allowed one
  6045. res.set_header("Trailer", "Content-Length, X-Allowed");
  6046. res.set_chunked_content_provider(
  6047. "text/plain",
  6048. [i](size_t /*offset*/, DataSink &sink) {
  6049. switch (*i) {
  6050. case 0: sink.os << "123"; break;
  6051. case 1: sink.os << "456"; break;
  6052. case 2: sink.os << "789"; break;
  6053. case 3: {
  6054. sink.done_with_trailer(
  6055. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6056. } break;
  6057. }
  6058. (*i)++;
  6059. return true;
  6060. },
  6061. [i](bool success) {
  6062. EXPECT_TRUE(success);
  6063. delete i;
  6064. });
  6065. })
  6066. .Get("/streamed-chunked2",
  6067. [&](const Request & /*req*/, Response &res) {
  6068. auto i = new int(0);
  6069. res.set_chunked_content_provider(
  6070. "text/plain",
  6071. [i](size_t /*offset*/, DataSink &sink) {
  6072. switch (*i) {
  6073. case 0: sink.os << "123"; break;
  6074. case 1: sink.os << "456"; break;
  6075. case 2: sink.os << "789"; break;
  6076. case 3: sink.done(); break;
  6077. }
  6078. (*i)++;
  6079. return true;
  6080. },
  6081. [i](bool success) {
  6082. EXPECT_TRUE(success);
  6083. delete i;
  6084. });
  6085. })
  6086. .Get("/streamed-chunked-with-trailer",
  6087. [&](const Request & /*req*/, Response &res) {
  6088. auto i = new int(0);
  6089. res.set_header("Trailer", "Dummy1, Dummy2");
  6090. res.set_chunked_content_provider(
  6091. "text/plain",
  6092. [i](size_t /*offset*/, DataSink &sink) {
  6093. switch (*i) {
  6094. case 0: sink.os << "123"; break;
  6095. case 1: sink.os << "456"; break;
  6096. case 2: sink.os << "789"; break;
  6097. case 3: {
  6098. sink.done_with_trailer(
  6099. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6100. } break;
  6101. }
  6102. (*i)++;
  6103. return true;
  6104. },
  6105. [i](bool success) {
  6106. EXPECT_TRUE(success);
  6107. delete i;
  6108. });
  6109. })
  6110. .Get("/streamed",
  6111. [&](const Request & /*req*/, Response &res) {
  6112. res.set_content_provider(
  6113. 6, "text/plain",
  6114. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6115. sink.os << (offset < 3 ? "a" : "b");
  6116. return true;
  6117. });
  6118. })
  6119. .Get("/streamed-without-length",
  6120. [&](const Request & /*req*/, Response &res) {
  6121. auto data = new std::string("abcdefg");
  6122. res.set_content_provider(
  6123. "text/plain",
  6124. [data](size_t offset, DataSink &sink) {
  6125. if (offset < data->size()) {
  6126. sink.os << data->substr(offset);
  6127. }
  6128. sink.done();
  6129. return true;
  6130. },
  6131. [data](bool success) {
  6132. EXPECT_TRUE(success);
  6133. delete data;
  6134. });
  6135. })
  6136. .Get("/streamed-with-range",
  6137. [&](const Request &req, Response &res) {
  6138. auto data = new std::string("abcdefg");
  6139. // An explicit status keeps the server from picking the 206 it
  6140. // would otherwise choose for a ranged request, so the response
  6141. // is not a partial representation.
  6142. auto status = req.get_param_value("status");
  6143. if (status == "200") {
  6144. res.status = StatusCode::OK_200;
  6145. } else if (status == "403") {
  6146. res.status = StatusCode::Forbidden_403;
  6147. }
  6148. res.set_content_provider(
  6149. data->size(), "text/plain",
  6150. [data](size_t offset, size_t length, DataSink &sink) {
  6151. size_t DATA_CHUNK_SIZE = 4;
  6152. const auto &d = *data;
  6153. auto out_len =
  6154. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6155. auto ret =
  6156. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6157. EXPECT_TRUE(ret);
  6158. return true;
  6159. },
  6160. [data, &req](bool success) {
  6161. EXPECT_EQ(success, !req.has_param("error"));
  6162. delete data;
  6163. });
  6164. })
  6165. .Get("/streamed-cancel",
  6166. [&](const Request & /*req*/, Response &res) {
  6167. res.set_content_provider(
  6168. size_t(-1), "text/plain",
  6169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6170. sink.os << "data_chunk";
  6171. return true;
  6172. });
  6173. })
  6174. .Get("/regex-with-delimiter",
  6175. [&](const Request &req, Response & /*res*/) {
  6176. ASSERT_TRUE(req.has_param("key"));
  6177. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6178. })
  6179. .Get("/with-range",
  6180. [&](const Request & /*req*/, Response &res) {
  6181. res.set_content("abcdefg", "text/plain");
  6182. })
  6183. .Get("/test-start-time",
  6184. [&](const Request &req, Response & /*res*/) {
  6185. EXPECT_NE(req.start_time_,
  6186. std::chrono::steady_clock::time_point::min());
  6187. })
  6188. .Get("/with-range-customized-response",
  6189. [&](const Request & /*req*/, Response &res) {
  6190. res.status = StatusCode::BadRequest_400;
  6191. res.set_content(JSON_DATA, "application/json");
  6192. })
  6193. .Post("/chunked",
  6194. [&](const Request &req, Response & /*res*/) {
  6195. EXPECT_EQ(req.body, "dechunked post body");
  6196. })
  6197. .Post("/large-chunked",
  6198. [&](const Request &req, Response & /*res*/) {
  6199. std::string expected(6 * 30 * 1024u, 'a');
  6200. EXPECT_EQ(req.body, expected);
  6201. })
  6202. .Post("/multipart",
  6203. [&](const Request &req, Response & /*res*/) {
  6204. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6205. req.form.get_field_count("text2") +
  6206. req.form.get_field_count("file3") +
  6207. req.form.get_field_count("file4"));
  6208. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6209. req.form.get_file_count("file2"));
  6210. ASSERT_TRUE(!req.form.has_file("???"));
  6211. ASSERT_TRUE(!req.form.has_field("???"));
  6212. ASSERT_TRUE(req.body.empty());
  6213. {
  6214. const auto &text = req.form.get_field("text1");
  6215. EXPECT_EQ("text default", text);
  6216. }
  6217. {
  6218. const auto &text = req.form.get_field("text2");
  6219. EXPECT_EQ("aωb", text);
  6220. }
  6221. {
  6222. const auto &file = req.form.get_file("file1");
  6223. EXPECT_EQ("hello.txt", file.filename);
  6224. EXPECT_EQ("text/plain", file.content_type);
  6225. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6226. }
  6227. {
  6228. const auto &file = req.form.get_file("file2");
  6229. EXPECT_EQ("world.json", file.filename);
  6230. EXPECT_EQ("application/json", file.content_type);
  6231. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6232. }
  6233. {
  6234. const auto &text = req.form.get_field("file3");
  6235. EXPECT_EQ(0u, text.size());
  6236. }
  6237. {
  6238. const auto &text = req.form.get_field("file4");
  6239. EXPECT_EQ(0u, text.size());
  6240. }
  6241. })
  6242. .Post("/multipart/multi_file_values",
  6243. [&](const Request &req, Response & /*res*/) {
  6244. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6245. req.form.get_field_count("multi_text1"));
  6246. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6247. ASSERT_TRUE(!req.form.has_file("???"));
  6248. ASSERT_TRUE(!req.form.has_field("???"));
  6249. ASSERT_TRUE(req.body.empty());
  6250. {
  6251. const auto &text = req.form.get_field("text");
  6252. EXPECT_EQ("default text", text);
  6253. }
  6254. {
  6255. const auto &text1_values = req.form.get_fields("multi_text1");
  6256. EXPECT_EQ(2u, text1_values.size());
  6257. EXPECT_EQ("aaaaa", text1_values[0]);
  6258. EXPECT_EQ("bbbbb", text1_values[1]);
  6259. }
  6260. {
  6261. const auto &file1_values = req.form.get_files("multi_file1");
  6262. EXPECT_EQ(2u, file1_values.size());
  6263. auto file1 = file1_values[0];
  6264. EXPECT_EQ(file1.filename, "hello.txt");
  6265. EXPECT_EQ(file1.content_type, "text/plain");
  6266. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6267. auto file2 = file1_values[1];
  6268. EXPECT_EQ(file2.filename, "world.json");
  6269. EXPECT_EQ(file2.content_type, "application/json");
  6270. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6271. }
  6272. })
  6273. .Post("/empty",
  6274. [&](const Request &req, Response &res) {
  6275. EXPECT_EQ(req.body, "");
  6276. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6277. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6278. res.set_content("empty", "text/plain");
  6279. })
  6280. .Post("/empty-no-content-type",
  6281. [&](const Request &req, Response &res) {
  6282. EXPECT_EQ(req.body, "");
  6283. EXPECT_FALSE(req.has_header("Content-Type"));
  6284. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6285. res.set_content("empty-no-content-type", "text/plain");
  6286. })
  6287. .Post("/path-only",
  6288. [&](const Request &req, Response &res) {
  6289. EXPECT_EQ(req.body, "");
  6290. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6291. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6292. res.set_content("path-only", "text/plain");
  6293. })
  6294. .Post("/path-headers-only",
  6295. [&](const Request &req, Response &res) {
  6296. EXPECT_EQ(req.body, "");
  6297. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6298. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6299. EXPECT_EQ("world", req.get_header_value("hello"));
  6300. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6301. res.set_content("path-headers-only", "text/plain");
  6302. })
  6303. .Post("/post-large",
  6304. [&](const Request &req, Response &res) {
  6305. EXPECT_EQ(req.body, LARGE_DATA);
  6306. res.set_content(req.body, "text/plain");
  6307. })
  6308. .Post("/post-loopback",
  6309. [&](const Request &, Response &res,
  6310. ContentReader const &content_reader) {
  6311. std::string body;
  6312. content_reader([&](const char *data, size_t data_length) {
  6313. body.append(data, data_length);
  6314. return true;
  6315. });
  6316. res.set_content(body, "text/plain");
  6317. })
  6318. .Put("/put-loopback",
  6319. [&](const Request &, Response &res,
  6320. ContentReader const &content_reader) {
  6321. std::string body;
  6322. content_reader([&](const char *data, size_t data_length) {
  6323. body.append(data, data_length);
  6324. return true;
  6325. });
  6326. res.set_content(body, "text/plain");
  6327. })
  6328. .Patch("/patch-loopback",
  6329. [&](const Request &, Response &res,
  6330. ContentReader const &content_reader) {
  6331. std::string body;
  6332. content_reader([&](const char *data, size_t data_length) {
  6333. body.append(data, data_length);
  6334. return true;
  6335. });
  6336. res.set_content(body, "text/plain");
  6337. })
  6338. .Put("/empty-no-content-type",
  6339. [&](const Request &req, Response &res) {
  6340. EXPECT_EQ(req.body, "");
  6341. EXPECT_FALSE(req.has_header("Content-Type"));
  6342. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6343. res.set_content("empty-no-content-type", "text/plain");
  6344. })
  6345. .Put("/put",
  6346. [&](const Request &req, Response &res) {
  6347. EXPECT_EQ(req.body, "PUT");
  6348. res.set_content(req.body, "text/plain");
  6349. })
  6350. .Put("/put-large",
  6351. [&](const Request &req, Response &res) {
  6352. EXPECT_EQ(req.body, LARGE_DATA);
  6353. res.set_content(req.body, "text/plain");
  6354. })
  6355. .Patch("/patch",
  6356. [&](const Request &req, Response &res) {
  6357. EXPECT_EQ(req.body, "PATCH");
  6358. res.set_content(req.body, "text/plain");
  6359. })
  6360. .Delete("/delete",
  6361. [&](const Request & /*req*/, Response &res) {
  6362. res.set_content("DELETE", "text/plain");
  6363. })
  6364. .Delete("/delete-body",
  6365. [&](const Request &req, Response &res) {
  6366. EXPECT_EQ(req.body, "content");
  6367. res.set_content(req.body, "text/plain");
  6368. })
  6369. .Options(R"(\*)",
  6370. [&](const Request & /*req*/, Response &res) {
  6371. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6372. })
  6373. .CustomRoute("PROPFIND", "/dav/:id",
  6374. [&](const Request &req, Response &res) {
  6375. res.set_header("x-body-size",
  6376. std::to_string(req.body.size()));
  6377. res.set_header("x-matched-route", req.matched_route);
  6378. res.set_header("x-dav-id", req.path_params.at("id"));
  6379. res.status = StatusCode::MultiStatus_207;
  6380. res.set_content(req.body, "application/xml");
  6381. })
  6382. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6383. [&](const Request &req, Response &res) {
  6384. res.set_header("x-dav-match", req.matches[1]);
  6385. res.status = StatusCode::MultiStatus_207;
  6386. })
  6387. .CustomRoute("MKCOL", "/dav-mkcol",
  6388. [&](const Request &req, Response &res) {
  6389. EXPECT_TRUE(req.body.empty());
  6390. res.status = StatusCode::Created_201;
  6391. })
  6392. .CustomRoute(
  6393. "REPORT", "/dav-report",
  6394. [&](const Request & /*req*/, Response &res,
  6395. const ContentReader &content_reader) {
  6396. std::string body;
  6397. content_reader([&](const char *data, size_t data_length) {
  6398. body.append(data, data_length);
  6399. return true;
  6400. });
  6401. res.set_header("x-body-size", std::to_string(body.size()));
  6402. res.status = StatusCode::MultiStatus_207;
  6403. res.set_content(body, "application/xml");
  6404. })
  6405. .Get("/request-target",
  6406. [&](const Request &req, Response & /*res*/) {
  6407. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6408. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6409. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6410. })
  6411. .Get("/long-query-value",
  6412. [&](const Request &req, Response & /*res*/) {
  6413. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6414. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6415. })
  6416. .Get("/too-long-query-value",
  6417. [&](const Request &req, Response & /*res*/) {
  6418. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6419. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6420. })
  6421. .Get("/array-param",
  6422. [&](const Request &req, Response & /*res*/) {
  6423. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6424. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6425. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6426. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6427. })
  6428. .Get("/array-param-values",
  6429. [&](const Request &req, Response & /*res*/) {
  6430. auto values = req.get_param_values("array");
  6431. EXPECT_EQ(3u, values.size());
  6432. EXPECT_EQ("value1", values[0]);
  6433. EXPECT_EQ("value2", values[1]);
  6434. EXPECT_EQ("value3", values[2]);
  6435. auto empty = req.get_param_values("nonexistent");
  6436. EXPECT_TRUE(empty.empty());
  6437. })
  6438. .Post("/validate-no-multiple-headers",
  6439. [&](const Request &req, Response & /*res*/) {
  6440. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6441. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6442. })
  6443. .Post("/content_receiver",
  6444. [&](const Request &req, Response &res,
  6445. const ContentReader &content_reader) {
  6446. if (req.is_multipart_form_data()) {
  6447. std::vector<FormData> items;
  6448. content_reader(
  6449. [&](const FormData &file) {
  6450. items.push_back(file);
  6451. return true;
  6452. },
  6453. [&](const char *data, size_t data_length) {
  6454. items.back().content.append(data, data_length);
  6455. return true;
  6456. });
  6457. EXPECT_EQ(5u, items.size());
  6458. {
  6459. const auto &file = get_file_value(items, "text1");
  6460. EXPECT_TRUE(file.filename.empty());
  6461. EXPECT_EQ("text default", file.content);
  6462. }
  6463. {
  6464. const auto &file = get_file_value(items, "text2");
  6465. EXPECT_TRUE(file.filename.empty());
  6466. EXPECT_EQ("aωb", file.content);
  6467. }
  6468. {
  6469. const auto &file = get_file_value(items, "file1");
  6470. EXPECT_EQ("hello.txt", file.filename);
  6471. EXPECT_EQ("text/plain", file.content_type);
  6472. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6473. }
  6474. {
  6475. const auto &file = get_file_value(items, "file2");
  6476. EXPECT_EQ("world.json", file.filename);
  6477. EXPECT_EQ("application/json", file.content_type);
  6478. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6479. }
  6480. {
  6481. const auto &file = get_file_value(items, "file3");
  6482. EXPECT_TRUE(file.filename.empty());
  6483. EXPECT_EQ("application/octet-stream", file.content_type);
  6484. EXPECT_EQ(0u, file.content.size());
  6485. }
  6486. } else {
  6487. std::string body;
  6488. content_reader([&](const char *data, size_t data_length) {
  6489. EXPECT_EQ(7U, data_length);
  6490. body.append(data, data_length);
  6491. return true;
  6492. });
  6493. EXPECT_EQ(body, "content");
  6494. res.set_content(body, "text/plain");
  6495. }
  6496. })
  6497. .Put("/content_receiver",
  6498. [&](const Request & /*req*/, Response &res,
  6499. const ContentReader &content_reader) {
  6500. std::string body;
  6501. content_reader([&](const char *data, size_t data_length) {
  6502. body.append(data, data_length);
  6503. return true;
  6504. });
  6505. EXPECT_EQ(body, "content");
  6506. res.set_content(body, "text/plain");
  6507. })
  6508. .Patch("/content_receiver",
  6509. [&](const Request & /*req*/, Response &res,
  6510. const ContentReader &content_reader) {
  6511. std::string body;
  6512. content_reader([&](const char *data, size_t data_length) {
  6513. body.append(data, data_length);
  6514. return true;
  6515. });
  6516. EXPECT_EQ(body, "content");
  6517. res.set_content(body, "text/plain");
  6518. })
  6519. .Post("/query-string-and-body",
  6520. [&](const Request &req, Response & /*res*/) {
  6521. ASSERT_TRUE(req.has_param("key"));
  6522. EXPECT_EQ(req.get_param_value("key"), "value");
  6523. EXPECT_EQ(req.body, "content");
  6524. })
  6525. .Get("/last-request",
  6526. [&](const Request &req, Response & /*res*/) {
  6527. EXPECT_EQ("close", req.get_header_value("Connection"));
  6528. })
  6529. .Get(R"(/redirect/(\d+))",
  6530. [&](const Request &req, Response &res) {
  6531. auto num = std::stoi(req.matches[1]) + 1;
  6532. std::string url = "/redirect/" + std::to_string(num);
  6533. res.set_redirect(url);
  6534. })
  6535. .Post("/binary",
  6536. [&](const Request &req, Response &res) {
  6537. EXPECT_EQ(4U, req.body.size());
  6538. EXPECT_EQ("application/octet-stream",
  6539. req.get_header_value("Content-Type"));
  6540. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6541. res.set_content(req.body, "application/octet-stream");
  6542. })
  6543. .Put("/binary",
  6544. [&](const Request &req, Response &res) {
  6545. EXPECT_EQ(4U, req.body.size());
  6546. EXPECT_EQ("application/octet-stream",
  6547. req.get_header_value("Content-Type"));
  6548. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6549. res.set_content(req.body, "application/octet-stream");
  6550. })
  6551. .Patch("/binary",
  6552. [&](const Request &req, Response &res) {
  6553. EXPECT_EQ(4U, req.body.size());
  6554. EXPECT_EQ("application/octet-stream",
  6555. req.get_header_value("Content-Type"));
  6556. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6557. res.set_content(req.body, "application/octet-stream");
  6558. })
  6559. .Delete("/binary",
  6560. [&](const Request &req, Response &res) {
  6561. EXPECT_EQ(4U, req.body.size());
  6562. EXPECT_EQ("application/octet-stream",
  6563. req.get_header_value("Content-Type"));
  6564. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6565. res.set_content(req.body, "application/octet-stream");
  6566. })
  6567. .Get("/issue1772",
  6568. [&](const Request & /*req*/, Response &res) {
  6569. res.status = 401;
  6570. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6571. })
  6572. .Delete("/issue609",
  6573. [](const httplib::Request &, httplib::Response &res,
  6574. const httplib::ContentReader &) {
  6575. res.set_content("ok", "text/plain");
  6576. })
  6577. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6578. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6579. .Get("/compress",
  6580. [&](const Request & /*req*/, Response &res) {
  6581. res.set_content(
  6582. "12345678901234567890123456789012345678901234567890123456789"
  6583. "01234567890123456789012345678901234567890",
  6584. "text/plain");
  6585. })
  6586. .Get("/compress-with-charset",
  6587. [&](const Request & /*req*/, Response &res) {
  6588. res.set_content(
  6589. "12345678901234567890123456789012345678901234567890123456789"
  6590. "01234567890123456789012345678901234567890",
  6591. "application/json; charset=utf-8");
  6592. })
  6593. .Get("/nocompress",
  6594. [&](const Request & /*req*/, Response &res) {
  6595. res.set_content(
  6596. "12345678901234567890123456789012345678901234567890123456789"
  6597. "01234567890123456789012345678901234567890",
  6598. "application/octet-stream");
  6599. })
  6600. .Post("/compress-multipart",
  6601. [&](const Request &req, Response & /*res*/) {
  6602. EXPECT_EQ(2u, req.form.fields.size());
  6603. ASSERT_TRUE(!req.form.has_field("???"));
  6604. {
  6605. const auto &text = req.form.get_field("key1");
  6606. EXPECT_EQ("test", text);
  6607. }
  6608. {
  6609. const auto &text = req.form.get_field("key2");
  6610. EXPECT_EQ("--abcdefg123", text);
  6611. }
  6612. })
  6613. #endif
  6614. ;
  6615. persons_["john"] = "programmer";
  6616. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6617. svr_.wait_until_ready();
  6618. }
  6619. virtual void TearDown() {
  6620. svr_.stop();
  6621. if (!request_threads_.empty()) {
  6622. std::this_thread::sleep_for(std::chrono::seconds(1));
  6623. for (auto &t : request_threads_) {
  6624. t.join();
  6625. }
  6626. }
  6627. t_.join();
  6628. }
  6629. map<string, string> persons_;
  6630. #ifdef CPPHTTPLIB_SSL_ENABLED
  6631. SSLClient cli_;
  6632. SSLServer svr_;
  6633. #else
  6634. Client cli_;
  6635. Server svr_;
  6636. #endif
  6637. thread t_;
  6638. std::vector<thread> request_threads_;
  6639. };
  6640. TEST_F(ServerTest, GetMethod200) {
  6641. auto res = cli_.Get("/hi");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ("HTTP/1.1", res->version);
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. EXPECT_EQ("OK", res->reason);
  6646. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6647. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6648. EXPECT_EQ("Hello World!", res->body);
  6649. }
  6650. TEST_F(ServerTest, GetEmptyFile) {
  6651. auto res = cli_.Get("/empty_file");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::OK_200, res->status);
  6654. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6655. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6656. EXPECT_EQ("", res->body);
  6657. }
  6658. TEST_F(ServerTest, GetFileContent) {
  6659. auto res = cli_.Get("/file_content");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6663. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6664. EXPECT_EQ("test.html", res->body);
  6665. }
  6666. TEST_F(ServerTest, GetFileContentWithRange) {
  6667. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6670. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6671. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6672. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6673. EXPECT_EQ("est", res->body);
  6674. }
  6675. TEST_F(ServerTest, GetFileContentWithContentType) {
  6676. auto res = cli_.Get("/file_content_with_content_type");
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6680. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6681. EXPECT_EQ("file\n", res->body);
  6682. }
  6683. TEST_F(ServerTest, GetInvalidFileContent) {
  6684. auto res = cli_.Get("/invalid_file_content");
  6685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6687. }
  6688. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6689. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ("HTTP/1.1", res->version);
  6692. EXPECT_EQ(StatusCode::OK_200, res->status);
  6693. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6694. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6695. EXPECT_EQ("Hello World!", res->body);
  6696. }
  6697. TEST_F(ServerTest, GetMethod302) {
  6698. auto res = cli_.Get("/");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::Found_302, res->status);
  6701. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6702. }
  6703. TEST_F(ServerTest, GetMethod302Redirect) {
  6704. cli_.set_follow_location(true);
  6705. auto res = cli_.Get("/");
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::OK_200, res->status);
  6708. EXPECT_EQ("Hello World!", res->body);
  6709. EXPECT_EQ("/hi", res->location);
  6710. }
  6711. TEST_F(ServerTest, GetMethod404) {
  6712. auto res = cli_.Get("/invalid");
  6713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6715. }
  6716. TEST_F(ServerTest, HeadMethod200) {
  6717. auto res = cli_.Head("/hi");
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6721. EXPECT_TRUE(res->body.empty());
  6722. }
  6723. TEST_F(ServerTest, HeadMethod200Static) {
  6724. auto res = cli_.Head("/mount/dir/index.html");
  6725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6728. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6729. EXPECT_TRUE(res->body.empty());
  6730. }
  6731. TEST_F(ServerTest, HeadMethod404) {
  6732. auto res = cli_.Head("/invalid");
  6733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6734. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6735. EXPECT_TRUE(res->body.empty());
  6736. }
  6737. TEST_F(ServerTest, GetMethodPersonJohn) {
  6738. auto res = cli_.Get("/person/john");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::OK_200, res->status);
  6741. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6742. EXPECT_EQ("programmer", res->body);
  6743. }
  6744. TEST_F(ServerTest, PostMethod1) {
  6745. auto res = cli_.Get("/person/john1");
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6748. res = cli_.Post("/person", "name=john1&note=coder",
  6749. "application/x-www-form-urlencoded");
  6750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6751. ASSERT_EQ(StatusCode::OK_200, res->status);
  6752. res = cli_.Get("/person/john1");
  6753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6754. ASSERT_EQ(StatusCode::OK_200, res->status);
  6755. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6756. ASSERT_EQ("coder", res->body);
  6757. }
  6758. TEST_F(ServerTest, PostMethod2) {
  6759. auto res = cli_.Get("/person/john2");
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6762. Params params;
  6763. params.emplace("name", "john2");
  6764. params.emplace("note", "coder");
  6765. res = cli_.Post("/person", params);
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. ASSERT_EQ(StatusCode::OK_200, res->status);
  6768. res = cli_.Get("/person/john2");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. ASSERT_EQ(StatusCode::OK_200, res->status);
  6771. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6772. ASSERT_EQ("coder", res->body);
  6773. }
  6774. TEST_F(ServerTest, PutMethod3) {
  6775. auto res = cli_.Get("/person/john3");
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6778. Params params;
  6779. params.emplace("name", "john3");
  6780. params.emplace("note", "coder");
  6781. res = cli_.Put("/person", params);
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. ASSERT_EQ(StatusCode::OK_200, res->status);
  6784. res = cli_.Get("/person/john3");
  6785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6786. ASSERT_EQ(StatusCode::OK_200, res->status);
  6787. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6788. ASSERT_EQ("coder", res->body);
  6789. }
  6790. TEST_F(ServerTest, DeleteMethod1) {
  6791. auto res = cli_.Get("/person/john4");
  6792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6793. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6794. Params params;
  6795. params.emplace("name", "john4");
  6796. params.emplace("note", "coder");
  6797. res = cli_.Post("/person", params);
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. ASSERT_EQ(StatusCode::OK_200, res->status);
  6800. res = cli_.Get("/person/john4");
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. ASSERT_EQ(StatusCode::OK_200, res->status);
  6803. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6804. ASSERT_EQ("coder", res->body);
  6805. Params delete_params;
  6806. delete_params.emplace("name", "john4");
  6807. res = cli_.Delete("/person", delete_params);
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. ASSERT_EQ(StatusCode::OK_200, res->status);
  6810. ASSERT_EQ("DELETED", res->body);
  6811. res = cli_.Get("/person/john4");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6814. }
  6815. TEST_F(ServerTest, DeleteMethod2) {
  6816. auto res = cli_.Get("/person/john5");
  6817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6818. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6819. Params params;
  6820. params.emplace("name", "john5");
  6821. params.emplace("note", "developer");
  6822. res = cli_.Post("/person", params);
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. ASSERT_EQ(StatusCode::OK_200, res->status);
  6825. res = cli_.Get("/person/john5");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. ASSERT_EQ(StatusCode::OK_200, res->status);
  6828. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6829. ASSERT_EQ("developer", res->body);
  6830. Params delete_params;
  6831. delete_params.emplace("name", "john5");
  6832. Headers headers;
  6833. headers.emplace("Custom-Header", "test-value");
  6834. res = cli_.Delete("/person", headers, delete_params);
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. ASSERT_EQ(StatusCode::OK_200, res->status);
  6837. ASSERT_EQ("DELETED", res->body);
  6838. res = cli_.Get("/person/john5");
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6841. }
  6842. TEST_F(ServerTest, DeleteMethod3) {
  6843. auto res = cli_.Get("/person/john6");
  6844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6845. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6846. Params params;
  6847. params.emplace("name", "john6");
  6848. params.emplace("note", "tester");
  6849. res = cli_.Post("/person", params);
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. ASSERT_EQ(StatusCode::OK_200, res->status);
  6852. res = cli_.Get("/person/john6");
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. ASSERT_EQ(StatusCode::OK_200, res->status);
  6855. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6856. ASSERT_EQ("tester", res->body);
  6857. Params delete_params;
  6858. delete_params.emplace("name", "john6");
  6859. Headers headers;
  6860. headers.emplace("Custom-Header", "test-value");
  6861. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. ASSERT_EQ(StatusCode::OK_200, res->status);
  6864. ASSERT_EQ("DELETED", res->body);
  6865. res = cli_.Get("/person/john6");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6868. }
  6869. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6870. Params params;
  6871. params.emplace("json", JSON_DATA);
  6872. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. ASSERT_EQ(StatusCode::OK_200, res->status);
  6875. ASSERT_EQ(JSON_DATA, res->body);
  6876. }
  6877. TEST_F(ServerTest, PostEmptyContent) {
  6878. auto res = cli_.Post("/empty", "", "text/plain");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. ASSERT_EQ(StatusCode::OK_200, res->status);
  6881. ASSERT_EQ("empty", res->body);
  6882. }
  6883. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6884. auto res = cli_.Post("/empty-no-content-type");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. ASSERT_EQ(StatusCode::OK_200, res->status);
  6887. ASSERT_EQ("empty-no-content-type", res->body);
  6888. }
  6889. TEST_F(ServerTest, PostPathOnly) {
  6890. auto res = cli_.Post("/path-only");
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. ASSERT_EQ(StatusCode::OK_200, res->status);
  6893. ASSERT_EQ("path-only", res->body);
  6894. }
  6895. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6896. auto res = cli_.Post("/path-headers-only",
  6897. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6899. ASSERT_EQ(StatusCode::OK_200, res->status);
  6900. ASSERT_EQ("path-headers-only", res->body);
  6901. }
  6902. TEST_F(ServerTest, PostLarge) {
  6903. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, res->status);
  6906. EXPECT_EQ(LARGE_DATA, res->body);
  6907. }
  6908. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6909. auto res = cli_.Put("/empty-no-content-type");
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. ASSERT_EQ(StatusCode::OK_200, res->status);
  6912. ASSERT_EQ("empty-no-content-type", res->body);
  6913. }
  6914. TEST_F(ServerTest, GetMethodDir) {
  6915. auto res = cli_.Get("/dir/");
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(StatusCode::OK_200, res->status);
  6918. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6919. auto body = R"(<html>
  6920. <head>
  6921. </head>
  6922. <body>
  6923. <a href="/dir/test.html">Test</a>
  6924. <a href="/hi">hi</a>
  6925. </body>
  6926. </html>
  6927. )";
  6928. EXPECT_EQ(body, res->body);
  6929. }
  6930. TEST_F(ServerTest, GetMethodDirTest) {
  6931. auto res = cli_.Get("/dir/test.html");
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. EXPECT_EQ(StatusCode::OK_200, res->status);
  6934. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6935. EXPECT_EQ("test.html", res->body);
  6936. }
  6937. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6938. auto res = cli_.Get("/dir/../dir/test.html");
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6941. }
  6942. TEST_F(ServerTest, GetMethodInvalidPath) {
  6943. auto res = cli_.Get("/dir/../test.html");
  6944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6946. }
  6947. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6948. auto res = cli_.Get("/../www/dir/test.html");
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6951. }
  6952. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6953. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6956. }
  6957. TEST_F(ServerTest, GetMethodDirMountTest) {
  6958. auto res = cli_.Get("/mount/dir/test.html");
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6962. EXPECT_EQ("test.html", res->body);
  6963. }
  6964. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6965. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6968. }
  6969. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6970. auto res = cli_.Get("/mount/dir/../test.html");
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6973. }
  6974. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6975. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6978. }
  6979. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6980. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6983. }
  6984. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6985. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6988. }
  6989. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6990. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6993. }
  6994. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6995. auto res = cli_.Get("/mount/dir");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6998. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6999. }
  7000. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7001. auto res = cli_.Get("//dir");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7004. EXPECT_FALSE(res->has_header("Location"));
  7005. }
  7006. TEST_F(ServerTest, PostMethod303) {
  7007. auto res = cli_.Post("/1", "body", "text/plain");
  7008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7009. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7010. EXPECT_EQ("/2", res->get_header_value("Location"));
  7011. }
  7012. TEST_F(ServerTest, PostMethod303Redirect) {
  7013. cli_.set_follow_location(true);
  7014. auto res = cli_.Post("/1", "body", "text/plain");
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. EXPECT_EQ("redirected.", res->body);
  7018. EXPECT_EQ("/2", res->location);
  7019. }
  7020. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7021. auto res = cli_.Get("/dir/test.abcde");
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::OK_200, res->status);
  7024. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7025. EXPECT_EQ("abcde", res->body);
  7026. }
  7027. TEST_F(ServerTest, StaticFileRange) {
  7028. auto res =
  7029. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7032. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7033. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7034. EXPECT_EQ(true, res->has_header("Content-Range"));
  7035. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7036. EXPECT_EQ(std::string("cd"), res->body);
  7037. }
  7038. TEST_F(ServerTest, StaticFileRanges) {
  7039. auto res = cli_.Get("/dir/test.abcde",
  7040. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7043. EXPECT_TRUE(
  7044. res->get_header_value("Content-Type")
  7045. .find(
  7046. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7047. 0);
  7048. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7049. }
  7050. TEST_F(ServerTest, StaticFileRangeHead) {
  7051. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7054. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7055. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7056. EXPECT_EQ(true, res->has_header("Content-Range"));
  7057. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7058. }
  7059. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7060. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7063. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7064. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7065. EXPECT_EQ(true, res->has_header("Content-Range"));
  7066. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7067. res->get_header_value("Content-Range"));
  7068. EXPECT_EQ("LAST\n", res->body);
  7069. }
  7070. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7071. auto res =
  7072. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7076. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7077. EXPECT_EQ(true, res->has_header("Content-Range"));
  7078. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7079. }
  7080. TEST_F(ServerTest, StaticFileBigFile) {
  7081. auto res = cli_.Get("/dir/1MB.txt");
  7082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7083. EXPECT_EQ(StatusCode::OK_200, res->status);
  7084. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7085. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7086. }
  7087. TEST_F(ServerTest, InvalidBaseDirMount) {
  7088. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7089. }
  7090. TEST_F(ServerTest, Binary) {
  7091. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7092. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7093. "application/octet-stream");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. ASSERT_EQ(StatusCode::OK_200, res->status);
  7096. ASSERT_EQ(4U, res->body.size());
  7097. res = cli_.Put("/binary", binary.data(), binary.size(),
  7098. "application/octet-stream");
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. ASSERT_EQ(StatusCode::OK_200, res->status);
  7101. ASSERT_EQ(4U, res->body.size());
  7102. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7103. "application/octet-stream");
  7104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7105. ASSERT_EQ(StatusCode::OK_200, res->status);
  7106. ASSERT_EQ(4U, res->body.size());
  7107. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7108. "application/octet-stream");
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. ASSERT_EQ(StatusCode::OK_200, res->status);
  7111. ASSERT_EQ(4U, res->body.size());
  7112. }
  7113. TEST_F(ServerTest, BinaryString) {
  7114. auto binary = std::string("\x00\x01\x02\x03", 4);
  7115. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. ASSERT_EQ(StatusCode::OK_200, res->status);
  7118. ASSERT_EQ(4U, res->body.size());
  7119. res = cli_.Put("/binary", binary, "application/octet-stream");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. ASSERT_EQ(StatusCode::OK_200, res->status);
  7122. ASSERT_EQ(4U, res->body.size());
  7123. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. ASSERT_EQ(StatusCode::OK_200, res->status);
  7126. ASSERT_EQ(4U, res->body.size());
  7127. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7129. ASSERT_EQ(StatusCode::OK_200, res->status);
  7130. ASSERT_EQ(4U, res->body.size());
  7131. }
  7132. TEST_F(ServerTest, EmptyRequest) {
  7133. auto res = cli_.Get("");
  7134. ASSERT_TRUE(!res);
  7135. EXPECT_EQ(Error::Connection, res.error());
  7136. }
  7137. TEST_F(ServerTest, LongRequest) {
  7138. std::string request;
  7139. for (size_t i = 0; i < 545; i++) {
  7140. request += "/TooLongRequest";
  7141. }
  7142. request += "OK";
  7143. auto res = cli_.Get(request.c_str());
  7144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7146. }
  7147. TEST_F(ServerTest, TooLongRequest) {
  7148. std::string request;
  7149. for (size_t i = 0; i < 546; i++) {
  7150. request += "/TooLongRequest";
  7151. }
  7152. request += "_NG";
  7153. auto start = std::chrono::high_resolution_clock::now();
  7154. cli_.set_keep_alive(true);
  7155. auto res = cli_.Get(request.c_str());
  7156. auto end = std::chrono::high_resolution_clock::now();
  7157. auto elapsed =
  7158. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7159. .count();
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7162. EXPECT_LE(elapsed, 1000);
  7163. EXPECT_EQ("close", res->get_header_value("Connection"));
  7164. EXPECT_FALSE(cli_.is_socket_open());
  7165. }
  7166. TEST_F(ServerTest, AlmostTooLongRequest) {
  7167. // test for #2046 - URI length check shouldn't include other content on req
  7168. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7169. // leading /, space, HTTP/1.1)
  7170. std::string request =
  7171. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7172. auto res = cli_.Get(request.c_str());
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7175. }
  7176. TEST_F(ServerTest, LongHeader) {
  7177. Request req;
  7178. req.method = "GET";
  7179. req.path = "/hi";
  7180. std::string host_and_port;
  7181. host_and_port += HOST;
  7182. host_and_port += ":";
  7183. host_and_port += std::to_string(PORT);
  7184. req.headers.emplace("Host", host_and_port.c_str());
  7185. req.headers.emplace("Accept", "*/*");
  7186. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7187. req.headers.emplace(
  7188. "Header-Name",
  7189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7217. "@@@@@@@@@@@@@@@@");
  7218. auto res = std::make_shared<Response>();
  7219. auto error = Error::Success;
  7220. auto ret = cli_.send(req, *res, error);
  7221. ASSERT_TRUE(ret);
  7222. EXPECT_EQ(StatusCode::OK_200, res->status);
  7223. }
  7224. TEST_F(ServerTest, LongQueryValue) {
  7225. auto start = std::chrono::high_resolution_clock::now();
  7226. cli_.set_keep_alive(true);
  7227. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7228. auto end = std::chrono::high_resolution_clock::now();
  7229. auto elapsed =
  7230. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7231. .count();
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7234. EXPECT_LE(elapsed, 1000);
  7235. EXPECT_EQ("close", res->get_header_value("Connection"));
  7236. EXPECT_FALSE(cli_.is_socket_open());
  7237. }
  7238. TEST_F(ServerTest, TooLongQueryValue) {
  7239. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7240. ASSERT_FALSE(res);
  7241. EXPECT_EQ(Error::Read, res.error());
  7242. }
  7243. TEST_F(ServerTest, TooLongHeader) {
  7244. Request req;
  7245. req.method = "GET";
  7246. req.path = "/hi";
  7247. std::string host_and_port;
  7248. host_and_port += HOST;
  7249. host_and_port += ":";
  7250. host_and_port += std::to_string(PORT);
  7251. req.headers.emplace("Host", host_and_port.c_str());
  7252. req.headers.emplace("Accept", "*/*");
  7253. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7254. req.headers.emplace(
  7255. "Header-Name",
  7256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7284. "@@@@@@@@@@@@@@@@@");
  7285. auto res = std::make_shared<Response>();
  7286. auto error = Error::Success;
  7287. auto ret = cli_.send(req, *res, error);
  7288. ASSERT_TRUE(ret);
  7289. EXPECT_EQ(StatusCode::OK_200, res->status);
  7290. }
  7291. TEST_F(ServerTest, HeaderCountAtLimit) {
  7292. // Test with headers just under the 100 limit
  7293. httplib::Headers headers;
  7294. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7295. // This should keep us just under the 100 header limit
  7296. for (int i = 0; i < 95; i++) {
  7297. std::string name = "X-Test-Header-" + std::to_string(i);
  7298. std::string value = "value" + std::to_string(i);
  7299. headers.emplace(name, value);
  7300. }
  7301. // This should work fine as we're under the limit
  7302. auto res = cli_.Get("/hi", headers);
  7303. EXPECT_TRUE(res);
  7304. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7305. }
  7306. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7307. // Test with many headers to exceed the 100 limit
  7308. httplib::Headers headers;
  7309. // Add 150 headers to definitely exceed the 100 limit
  7310. for (int i = 0; i < 150; i++) {
  7311. std::string name = "X-Test-Header-" + std::to_string(i);
  7312. std::string value = "value" + std::to_string(i);
  7313. headers.emplace(name, value);
  7314. }
  7315. // This should fail due to exceeding header count limit
  7316. cli_.set_keep_alive(true);
  7317. auto res = cli_.Get("/hi", headers);
  7318. // The server should respond with 400 Bad Request
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7321. EXPECT_EQ("close", res->get_header_value("Connection"));
  7322. EXPECT_FALSE(cli_.is_socket_open());
  7323. }
  7324. TEST_F(ServerTest, PercentEncoding) {
  7325. auto res = cli_.Get("/e%6edwith%");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. }
  7329. TEST_F(ServerTest, PercentEncodingUnicode) {
  7330. auto res = cli_.Get("/e%u006edwith%");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. }
  7334. TEST_F(ServerTest, InvalidPercentEncoding) {
  7335. auto res = cli_.Get("/%endwith%");
  7336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7338. }
  7339. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7340. auto res = cli_.Get("/%uendwith%");
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7343. }
  7344. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7345. auto res = cli_.Get("/hello?aaa=bbb%");
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7348. }
  7349. TEST_F(ServerTest, PlusSignEncoding) {
  7350. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. EXPECT_EQ("a +b", res->body);
  7354. }
  7355. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7356. // This test simulates a potential DoS attack using many headers
  7357. // to verify our security fix prevents memory exhaustion
  7358. httplib::Headers attack_headers;
  7359. // Attempt to add many headers like an attacker would (200 headers to far
  7360. // exceed limit)
  7361. for (int i = 0; i < 200; i++) {
  7362. std::string name = "X-Attack-Header-" + std::to_string(i);
  7363. std::string value = "attack_payload_" + std::to_string(i);
  7364. attack_headers.emplace(name, value);
  7365. }
  7366. // Try to POST with excessive headers
  7367. cli_.set_keep_alive(true);
  7368. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7369. // Should either fail or return 400 Bad Request due to security limit
  7370. if (res) {
  7371. // If we get a response, it should be 400 Bad Request
  7372. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7373. EXPECT_EQ("close", res->get_header_value("Connection"));
  7374. }
  7375. EXPECT_FALSE(cli_.is_socket_open());
  7376. }
  7377. TEST_F(ServerTest, MultipartFormData) {
  7378. UploadFormDataItems items = {
  7379. {"text1", "text default", "", ""},
  7380. {"text2", "aωb", "", ""},
  7381. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7382. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7383. {"file3", "", "", "application/octet-stream"},
  7384. {"file4", "", "", " application/json tmp-string "}};
  7385. auto res = cli_.Post("/multipart", items);
  7386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7387. EXPECT_EQ(StatusCode::OK_200, res->status);
  7388. }
  7389. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7390. UploadFormDataItems items = {
  7391. {"text", "default text", "", ""},
  7392. {"multi_text1", "aaaaa", "", ""},
  7393. {"multi_text1", "bbbbb", "", ""},
  7394. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7395. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7396. "application/json"},
  7397. };
  7398. auto res = cli_.Post("/multipart/multi_file_values", items);
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_EQ(StatusCode::OK_200, res->status);
  7401. }
  7402. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7403. auto res = cli_.Get("/hi");
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7407. EXPECT_EQ("Hello World!", res->body);
  7408. }
  7409. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7410. Request req;
  7411. req.method = "POST";
  7412. req.path = "/chunked";
  7413. std::string host_and_port;
  7414. host_and_port += HOST;
  7415. host_and_port += ":";
  7416. host_and_port += std::to_string(PORT);
  7417. req.headers.emplace("Host", host_and_port.c_str());
  7418. req.headers.emplace("Accept", "*/*");
  7419. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7420. req.headers.emplace("Content-Type", "text/plain");
  7421. req.headers.emplace("Content-Length", "0");
  7422. req.headers.emplace(
  7423. "Transfer-Encoding",
  7424. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7425. // Client does not chunk, so make a chunked body manually.
  7426. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7427. auto res = std::make_shared<Response>();
  7428. auto error = Error::Success;
  7429. auto ret = cli_.send(req, *res, error);
  7430. ASSERT_TRUE(ret);
  7431. EXPECT_EQ(StatusCode::OK_200, res->status);
  7432. }
  7433. template <typename ClientT>
  7434. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7435. int expected_status) {
  7436. Request req;
  7437. req.method = "POST";
  7438. req.path = "/chunked";
  7439. std::string host_and_port;
  7440. host_and_port += HOST;
  7441. host_and_port += ":";
  7442. host_and_port += std::to_string(PORT);
  7443. req.headers.emplace("Host", host_and_port.c_str());
  7444. req.headers.emplace("Content-Length", "0");
  7445. req.headers.emplace("Transfer-Encoding", "chunked");
  7446. req.body = body;
  7447. auto res = std::make_shared<Response>();
  7448. auto error = Error::Success;
  7449. ASSERT_TRUE(cli.send(req, *res, error));
  7450. EXPECT_EQ(expected_status, res->status);
  7451. }
  7452. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7453. // rather than treat them as valid lengths.
  7454. template <typename ClientT>
  7455. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7456. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7457. }
  7458. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7459. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7460. }
  7461. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7462. expect_chunked_body_rejected(
  7463. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7464. }
  7465. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7466. // chunk-size line carries no CR, LF or other control character ahead of its
  7467. // terminator. Such a line must be refused rather than read as extension text.
  7468. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7469. expect_chunked_body_rejected(
  7470. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7471. }
  7472. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7473. expect_chunked_body_rejected(
  7474. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7475. }
  7476. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7477. expect_chunked_body_rejected(
  7478. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7479. }
  7480. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7481. // The literal stays split: a hex escape consumes every hex digit that
  7482. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7483. expect_chunked_body_rejected(
  7484. cli_, "4;a\x01"
  7485. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7486. }
  7487. // The bytes around chunk data are no payload, so they cannot ride on the
  7488. // payload limit
  7489. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7490. // Small enough that the whole request is sent before the server turns it
  7491. // down, yet past the limit by the last chunks
  7492. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7493. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7494. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7495. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7496. SCOPED_TRACE(size_line.substr(0, 2));
  7497. std::string body;
  7498. for (auto c : std::string("dechunked post body")) {
  7499. body += size_line + "\r\n" + c + "\r\n";
  7500. }
  7501. body += "0\r\n\r\n";
  7502. expect_chunked_body_rejected(cli_, body.c_str());
  7503. }
  7504. }
  7505. TEST_F(ServerTest, AcceptsChunkExtension) {
  7506. expect_chunked_body_status(cli_,
  7507. "4;name=value\r\ndech\r\n"
  7508. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7509. "0;last\r\n\r\n",
  7510. StatusCode::OK_200);
  7511. }
  7512. TEST_F(ServerTest, GetStreamed2) {
  7513. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7515. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7516. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7517. EXPECT_EQ(true, res->has_header("Content-Range"));
  7518. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7519. EXPECT_EQ(std::string("ab"), res->body);
  7520. }
  7521. TEST_F(ServerTest, GetStreamed) {
  7522. auto res = cli_.Get("/streamed");
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7526. EXPECT_EQ(std::string("aaabbb"), res->body);
  7527. }
  7528. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7529. auto res = cli_.Get("/streamed-without-length",
  7530. Headers{make_range_header({{0, -1}})});
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ(false, res->has_header("Content-Length"));
  7534. EXPECT_EQ(false, res->has_header("Content-Range"));
  7535. EXPECT_EQ(std::string("abcdefg"), res->body);
  7536. }
  7537. TEST_F(ServerTest, GetStreamedWithRange1) {
  7538. auto res =
  7539. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7542. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7543. EXPECT_EQ(true, res->has_header("Content-Range"));
  7544. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7545. EXPECT_EQ(std::string("def"), res->body);
  7546. }
  7547. TEST_F(ServerTest, GetStreamedWithRange2) {
  7548. auto res =
  7549. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7552. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7553. EXPECT_EQ(true, res->has_header("Content-Range"));
  7554. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7555. EXPECT_EQ(std::string("bcdefg"), res->body);
  7556. }
  7557. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7558. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7561. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7562. EXPECT_EQ(true, res->has_header("Content-Range"));
  7563. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7564. EXPECT_EQ(std::string("efg"), res->body);
  7565. }
  7566. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7567. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7568. // the entire representation.
  7569. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7570. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7573. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7574. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7575. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7576. }
  7577. }
  7578. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7579. auto res =
  7580. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7583. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7584. EXPECT_EQ(false, res->has_header("Content-Range"));
  7585. EXPECT_EQ(0U, res->body.size());
  7586. }
  7587. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7588. // Only a 206 is served as a partial representation. Under any other status
  7589. // `apply_ranges()` reported the full content length, so the body must match
  7590. // that header, and the content provider must never be asked for an offset
  7591. // outside the representation.
  7592. auto check = [&](int status, const char *range) {
  7593. auto path =
  7594. std::string("/streamed-with-range?status=") + std::to_string(status);
  7595. auto ctx = path + " Range: " + range;
  7596. auto res = cli_.Get(path, Headers{{"Range", range}});
  7597. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7598. EXPECT_EQ(status, res->status) << ctx;
  7599. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7601. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7602. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7603. };
  7604. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7605. check(403, "bytes=3-5");
  7606. // The offset is far past the representation.
  7607. check(403, "bytes=100000-100200");
  7608. // `first_pos` is still -1 here, and the bounds asserts in
  7609. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7610. check(403, "bytes=-3");
  7611. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7612. // multipart branch would have written one that is empty.
  7613. check(403, "bytes=1-2, 4-5");
  7614. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7615. // covers the whole representation.
  7616. check(200, "bytes=3-5");
  7617. check(200, "bytes=1-2, 4-5");
  7618. }
  7619. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7620. auto res =
  7621. cli_.Get("/streamed-with-range",
  7622. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7623. "92233720368547758079223372036854775807"}});
  7624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7626. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7627. EXPECT_EQ(false, res->has_header("Content-Range"));
  7628. EXPECT_EQ(0U, res->body.size());
  7629. }
  7630. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7631. auto res = cli_.Get(
  7632. "/with-range",
  7633. Headers{{"Range",
  7634. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7635. {"Accept-Encoding", ""}});
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7638. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7639. EXPECT_EQ(true, res->has_header("Content-Range"));
  7640. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7641. EXPECT_EQ(std::string("abcdefg"), res->body);
  7642. }
  7643. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7644. auto res = cli_.Get("/with-range", Headers{
  7645. {"Range", "bytes=0-"},
  7646. {"Accept-Encoding", ""},
  7647. });
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7650. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7651. EXPECT_EQ(true, res->has_header("Content-Range"));
  7652. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7653. EXPECT_EQ(std::string("abcdefg"), res->body);
  7654. }
  7655. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7656. auto res = cli_.Get("/streamed-with-range",
  7657. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7660. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7661. EXPECT_EQ(false, res->has_header("Content-Range"));
  7662. EXPECT_EQ(267U, res->body.size());
  7663. // Check that both range contents are present
  7664. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7665. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7666. // Check that Content-Range headers are present for both ranges
  7667. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7668. std::string::npos);
  7669. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7670. std::string::npos);
  7671. }
  7672. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7673. Ranges ranges;
  7674. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7675. ranges.emplace_back(0, -1);
  7676. }
  7677. auto res = cli_.Get("/streamed-with-range?error",
  7678. Headers{{make_range_header(ranges)}});
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7681. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7682. EXPECT_EQ(false, res->has_header("Content-Range"));
  7683. EXPECT_EQ(0U, res->body.size());
  7684. }
  7685. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7686. auto res = cli_.Get("/streamed-with-range",
  7687. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7690. EXPECT_EQ(5U, res->body.size());
  7691. // Check that overlapping ranges are coalesced into a single range
  7692. EXPECT_EQ("bcdef", res->body);
  7693. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7694. // Should be single range, not multipart
  7695. EXPECT_TRUE(res->has_header("Content-Range"));
  7696. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7697. }
  7698. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7699. auto res = cli_.Get("/streamed-with-range",
  7700. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7703. EXPECT_EQ(268U, res->body.size());
  7704. // Check that both range contents are present
  7705. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7706. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7707. // Check that Content-Range headers are present for both ranges
  7708. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7709. std::string::npos);
  7710. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7711. std::string::npos);
  7712. }
  7713. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7714. auto res = cli_.Get("/streamed-with-range",
  7715. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7718. EXPECT_EQ(269U, res->body.size());
  7719. // Check that both duplicate range contents are present
  7720. size_t first_abc = res->body.find("abc\r\n");
  7721. EXPECT_TRUE(first_abc != std::string::npos);
  7722. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7723. EXPECT_TRUE(second_abc != std::string::npos);
  7724. // Check that Content-Range headers are present for both ranges
  7725. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7726. EXPECT_TRUE(first_range != std::string::npos);
  7727. size_t second_range =
  7728. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7729. EXPECT_TRUE(second_range != std::string::npos);
  7730. }
  7731. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7732. auto res =
  7733. cli_.Get("/streamed-with-range?error",
  7734. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7737. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7738. EXPECT_EQ(false, res->has_header("Content-Range"));
  7739. EXPECT_EQ(0U, res->body.size());
  7740. }
  7741. TEST_F(ServerTest, GetStreamedEndless) {
  7742. uint64_t offset = 0;
  7743. auto res = cli_.Get("/streamed-cancel",
  7744. [&](const char * /*data*/, uint64_t data_length) {
  7745. if (offset < 100) {
  7746. offset += data_length;
  7747. return true;
  7748. }
  7749. return false;
  7750. });
  7751. ASSERT_TRUE(!res);
  7752. EXPECT_EQ(Error::Canceled, res.error());
  7753. }
  7754. TEST_F(ServerTest, ClientStop) {
  7755. std::atomic_size_t count{4};
  7756. std::vector<std::thread> threads;
  7757. for (auto i = count.load(); i != 0; --i) {
  7758. threads.emplace_back([&]() {
  7759. auto res = cli_.Get("/streamed-cancel",
  7760. [&](const char *, uint64_t) { return true; });
  7761. --count;
  7762. ASSERT_TRUE(!res);
  7763. EXPECT_TRUE(res.error() == Error::Canceled ||
  7764. res.error() == Error::Read || res.error() == Error::Write);
  7765. });
  7766. }
  7767. std::this_thread::sleep_for(std::chrono::seconds(2));
  7768. while (count != 0) {
  7769. cli_.stop();
  7770. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7771. }
  7772. for (auto &t : threads) {
  7773. t.join();
  7774. }
  7775. }
  7776. TEST_F(ServerTest, GetWithRange1) {
  7777. auto res = cli_.Get("/with-range", Headers{
  7778. make_range_header({{3, 5}}),
  7779. {"Accept-Encoding", ""},
  7780. });
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7783. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7784. EXPECT_EQ(true, res->has_header("Content-Range"));
  7785. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7786. EXPECT_EQ(std::string("def"), res->body);
  7787. }
  7788. TEST_F(ServerTest, GetWithRange2) {
  7789. auto res = cli_.Get("/with-range", Headers{
  7790. make_range_header({{1, -1}}),
  7791. {"Accept-Encoding", ""},
  7792. });
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7795. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7796. EXPECT_EQ(true, res->has_header("Content-Range"));
  7797. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7798. EXPECT_EQ(std::string("bcdefg"), res->body);
  7799. }
  7800. TEST_F(ServerTest, GetWithRange3) {
  7801. auto res = cli_.Get("/with-range", Headers{
  7802. make_range_header({{0, 0}}),
  7803. {"Accept-Encoding", ""},
  7804. });
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7807. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7808. EXPECT_EQ(true, res->has_header("Content-Range"));
  7809. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7810. EXPECT_EQ(std::string("a"), res->body);
  7811. }
  7812. TEST_F(ServerTest, GetWithRange4) {
  7813. auto res = cli_.Get("/with-range", Headers{
  7814. make_range_header({{-1, 2}}),
  7815. {"Accept-Encoding", ""},
  7816. });
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7819. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7820. EXPECT_EQ(true, res->has_header("Content-Range"));
  7821. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7822. EXPECT_EQ(std::string("fg"), res->body);
  7823. }
  7824. TEST_F(ServerTest, GetWithRange5) {
  7825. auto res = cli_.Get("/with-range", Headers{
  7826. make_range_header({{0, 5}}),
  7827. {"Accept-Encoding", ""},
  7828. });
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7831. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7832. EXPECT_EQ(true, res->has_header("Content-Range"));
  7833. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7834. EXPECT_EQ(std::string("abcdef"), res->body);
  7835. }
  7836. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7837. auto res =
  7838. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7841. }
  7842. TEST_F(ServerTest, GetWithRangeMultipart) {
  7843. auto res =
  7844. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7847. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7848. EXPECT_EQ(false, res->has_header("Content-Range"));
  7849. EXPECT_EQ(267U, res->body.size());
  7850. }
  7851. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7852. auto res = cli_.Get("/with-range",
  7853. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7856. }
  7857. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7858. auto res = cli_.Get("/with-range-customized-response",
  7859. Headers{{make_range_header({{1, 2}})}});
  7860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7862. EXPECT_EQ(true, res->has_header("Content-Length"));
  7863. EXPECT_EQ(false, res->has_header("Content-Range"));
  7864. EXPECT_EQ(JSON_DATA, res->body);
  7865. }
  7866. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7867. auto res = cli_.Get("/with-range-customized-response",
  7868. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7871. EXPECT_EQ(true, res->has_header("Content-Length"));
  7872. EXPECT_EQ(false, res->has_header("Content-Range"));
  7873. EXPECT_EQ(JSON_DATA, res->body);
  7874. }
  7875. TEST_F(ServerTest, Issue1772) {
  7876. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7879. }
  7880. TEST_F(ServerTest, Issue609) {
  7881. auto res = cli_.Delete("/issue609");
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. EXPECT_EQ(StatusCode::OK_200, res->status);
  7884. EXPECT_EQ(std::string("ok"), res->body);
  7885. }
  7886. TEST_F(ServerTest, GetStreamedChunked) {
  7887. auto res = cli_.Get("/streamed-chunked");
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ(std::string("123456789"), res->body);
  7891. }
  7892. TEST_F(ServerTest, GetStreamedChunked2) {
  7893. auto res = cli_.Get("/streamed-chunked2");
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ(std::string("123456789"), res->body);
  7897. }
  7898. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7899. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7901. EXPECT_EQ(StatusCode::OK_200, res->status);
  7902. EXPECT_EQ(std::string("123456789"), res->body);
  7903. EXPECT_TRUE(res->has_header("Trailer"));
  7904. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7905. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7906. // Trailers are now stored separately from headers (security fix)
  7907. EXPECT_EQ(2U, res->trailers.size());
  7908. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7909. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7910. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7911. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7912. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7913. // Verify trailers are NOT in headers (security verification)
  7914. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7915. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7916. }
  7917. TEST_F(ServerTest, LargeChunkedPost) {
  7918. Request req;
  7919. req.method = "POST";
  7920. req.path = "/large-chunked";
  7921. std::string host_and_port;
  7922. host_and_port += HOST;
  7923. host_and_port += ":";
  7924. host_and_port += std::to_string(PORT);
  7925. req.headers.emplace("Host", host_and_port.c_str());
  7926. req.headers.emplace("Accept", "*/*");
  7927. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7928. req.headers.emplace("Content-Type", "text/plain");
  7929. req.headers.emplace("Content-Length", "0");
  7930. req.headers.emplace("Transfer-Encoding", "chunked");
  7931. std::string long_string(30 * 1024u, 'a');
  7932. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7933. // Attempt to make a large enough post to exceed OS buffers, to test that
  7934. // the server handles short reads if the full chunk data isn't available.
  7935. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7936. auto res = std::make_shared<Response>();
  7937. auto error = Error::Success;
  7938. auto ret = cli_.send(req, *res, error);
  7939. ASSERT_TRUE(ret);
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. }
  7942. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7943. auto res = cli_.Get("/remote_addr");
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7947. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7948. }
  7949. TEST_F(ServerTest, GetMethodLocalAddr) {
  7950. auto res = cli_.Get("/local_addr");
  7951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7952. EXPECT_EQ(StatusCode::OK_200, res->status);
  7953. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7954. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7955. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7956. }
  7957. TEST_F(ServerTest, HTTPResponseSplitting) {
  7958. auto res = cli_.Get("/http_response_splitting");
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. TEST_F(ServerTest, SlowRequest) {
  7963. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7964. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7965. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7966. }
  7967. #if 0
  7968. TEST_F(ServerTest, SlowPost) {
  7969. char buffer[64 * 1024];
  7970. memset(buffer, 0x42, sizeof(buffer));
  7971. auto res = cli_.Post(
  7972. "/slowpost", 64 * 1024 * 1024,
  7973. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7974. auto ret = sink.write(buffer, sizeof(buffer));
  7975. EXPECT_TRUE(ret);
  7976. return true;
  7977. },
  7978. "text/plain");
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST_F(ServerTest, SlowPostFail) {
  7983. char buffer[64 * 1024];
  7984. memset(buffer, 0x42, sizeof(buffer));
  7985. cli_.set_write_timeout(std::chrono::seconds(0));
  7986. auto res = cli_.Post(
  7987. "/slowpost", 64 * 1024 * 1024,
  7988. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7989. sink.write(buffer, sizeof(buffer));
  7990. return true;
  7991. },
  7992. "text/plain");
  7993. ASSERT_TRUE(!res);
  7994. EXPECT_EQ(Error::Write, res.error());
  7995. }
  7996. #endif
  7997. TEST_F(ServerTest, Put) {
  7998. auto res = cli_.Put("/put", "PUT", "text/plain");
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ(StatusCode::OK_200, res->status);
  8001. EXPECT_EQ("PUT", res->body);
  8002. }
  8003. TEST_F(ServerTest, PutWithContentProvider) {
  8004. auto res = cli_.Put(
  8005. "/put", 3,
  8006. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8007. sink.os << "PUT";
  8008. return true;
  8009. },
  8010. "text/plain");
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. EXPECT_EQ(StatusCode::OK_200, res->status);
  8013. EXPECT_EQ("PUT", res->body);
  8014. }
  8015. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8016. auto res = cli_.Post(
  8017. "/post", 42,
  8018. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8019. return false;
  8020. },
  8021. "text/plain");
  8022. ASSERT_TRUE(!res);
  8023. EXPECT_EQ(Error::Canceled, res.error());
  8024. }
  8025. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8026. auto res = cli_.Put(
  8027. "/put",
  8028. [](size_t /*offset*/, DataSink &sink) {
  8029. sink.os << "PUT";
  8030. sink.done();
  8031. return true;
  8032. },
  8033. "text/plain");
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::OK_200, res->status);
  8036. EXPECT_EQ("PUT", res->body);
  8037. }
  8038. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8039. auto res = cli_.Post(
  8040. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8041. "text/plain");
  8042. ASSERT_TRUE(!res);
  8043. EXPECT_EQ(Error::Canceled, res.error());
  8044. }
  8045. TEST_F(ServerTest, PostLoopBack) {
  8046. std::string body;
  8047. auto res = cli_.Post(
  8048. "/post-loopback", 9,
  8049. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8050. EXPECT_EQ(9u, length);
  8051. sink.write("123", 3);
  8052. sink.write("456", 3);
  8053. sink.write("789", 3);
  8054. return true;
  8055. },
  8056. "text/plain",
  8057. [&body](const char *data, size_t data_length) {
  8058. body.append(data, data_length);
  8059. return true;
  8060. });
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. EXPECT_EQ("123456789", body);
  8064. }
  8065. TEST_F(ServerTest, PutLoopBack) {
  8066. std::string body;
  8067. auto res = cli_.Put(
  8068. "/put-loopback", 9,
  8069. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8070. EXPECT_EQ(9u, length);
  8071. sink.write("123", 3);
  8072. sink.write("456", 3);
  8073. sink.write("789", 3);
  8074. return true;
  8075. },
  8076. "text/plain",
  8077. [&body](const char *data, size_t data_length) {
  8078. body.append(data, data_length);
  8079. return true;
  8080. });
  8081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. EXPECT_EQ("123456789", body);
  8084. }
  8085. TEST_F(ServerTest, PatchLoopBack) {
  8086. std::string body;
  8087. auto res = cli_.Patch(
  8088. "/patch-loopback", 9,
  8089. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8090. EXPECT_EQ(9u, length);
  8091. sink.write("123", 3);
  8092. sink.write("456", 3);
  8093. sink.write("789", 3);
  8094. return true;
  8095. },
  8096. "text/plain",
  8097. [&body](const char *data, size_t data_length) {
  8098. body.append(data, data_length);
  8099. return true;
  8100. });
  8101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. EXPECT_EQ("123456789", body);
  8104. }
  8105. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8106. std::string body;
  8107. auto res = cli_.Post(
  8108. "/post-loopback",
  8109. [](size_t /*offset*/, DataSink &sink) {
  8110. sink.write("123", 3);
  8111. sink.write("456", 3);
  8112. sink.write("789", 3);
  8113. sink.done();
  8114. return true;
  8115. },
  8116. "text/plain",
  8117. [&body](const char *data, size_t data_length) {
  8118. body.append(data, data_length);
  8119. return true;
  8120. });
  8121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8122. EXPECT_EQ(StatusCode::OK_200, res->status);
  8123. EXPECT_EQ("123456789", body);
  8124. }
  8125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8126. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8127. cli_.set_compress(true);
  8128. auto res = cli_.Put(
  8129. "/put", 3,
  8130. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8131. sink.os << "PUT";
  8132. return true;
  8133. },
  8134. "text/plain");
  8135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8136. EXPECT_EQ(StatusCode::OK_200, res->status);
  8137. EXPECT_EQ("PUT", res->body);
  8138. }
  8139. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8140. cli_.set_compress(true);
  8141. auto res = cli_.Post(
  8142. "/post", 42,
  8143. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8144. return false;
  8145. },
  8146. "text/plain");
  8147. ASSERT_TRUE(!res);
  8148. EXPECT_EQ(Error::Canceled, res.error());
  8149. }
  8150. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8151. cli_.set_compress(true);
  8152. auto res = cli_.Put(
  8153. "/put",
  8154. [](size_t /*offset*/, DataSink &sink) {
  8155. sink.os << "PUT";
  8156. sink.done();
  8157. return true;
  8158. },
  8159. "text/plain");
  8160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8161. EXPECT_EQ(StatusCode::OK_200, res->status);
  8162. EXPECT_EQ("PUT", res->body);
  8163. }
  8164. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8165. cli_.set_compress(true);
  8166. auto res = cli_.Post(
  8167. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8168. "text/plain");
  8169. ASSERT_TRUE(!res);
  8170. EXPECT_EQ(Error::Canceled, res.error());
  8171. }
  8172. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8173. cli_.set_compress(true);
  8174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::OK_200, res->status);
  8177. EXPECT_EQ(LARGE_DATA, res->body);
  8178. }
  8179. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8180. #ifdef CPPHTTPLIB_SSL_ENABLED
  8181. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8182. Client cli(s.c_str());
  8183. cli.enable_server_certificate_verification(false);
  8184. #else
  8185. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8186. Client cli(s.c_str());
  8187. #endif
  8188. cli.set_compress(true);
  8189. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(StatusCode::OK_200, res->status);
  8192. EXPECT_EQ(LARGE_DATA, res->body);
  8193. // The compressed size should be less than a 10th of the original. May vary
  8194. // depending on the zlib library.
  8195. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8196. static_cast<uint64_t>(10 * 1024 * 1024));
  8197. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8198. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8199. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8200. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8201. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8202. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8203. #endif
  8204. }
  8205. TEST_F(ServerTest, PutContentWithDeflate) {
  8206. cli_.set_compress(false);
  8207. Headers headers;
  8208. headers.emplace("Content-Encoding", "deflate");
  8209. // PUT in deflate format:
  8210. auto res = cli_.Put("/put", headers,
  8211. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. EXPECT_EQ("PUT", res->body);
  8215. }
  8216. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8217. Headers headers;
  8218. headers.emplace("Accept-Encoding", "gzip, deflate");
  8219. auto res = cli_.Get("/streamed-chunked", headers);
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. EXPECT_EQ(std::string("123456789"), res->body);
  8223. }
  8224. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8225. Headers headers;
  8226. headers.emplace("Accept-Encoding", "gzip, deflate");
  8227. auto res = cli_.Get("/streamed-chunked2", headers);
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::OK_200, res->status);
  8230. EXPECT_EQ(std::string("123456789"), res->body);
  8231. }
  8232. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8233. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8235. EXPECT_EQ(StatusCode::OK_200, res->status);
  8236. }
  8237. TEST(GzipDecompressor, ChunkedDecompression) {
  8238. std::string data;
  8239. for (size_t i = 0; i < 32 * 1024; ++i) {
  8240. data.push_back(static_cast<char>('a' + i % 26));
  8241. }
  8242. std::string compressed_data;
  8243. {
  8244. httplib::detail::gzip_compressor compressor;
  8245. bool result = compressor.compress(
  8246. data.data(), data.size(),
  8247. /*last=*/true,
  8248. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8249. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8250. compressed_data_size);
  8251. return true;
  8252. });
  8253. ASSERT_TRUE(result);
  8254. }
  8255. std::string decompressed_data;
  8256. {
  8257. httplib::detail::gzip_decompressor decompressor;
  8258. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8259. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8260. size_t chunk_size = 130;
  8261. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8262. chunk_begin += chunk_size) {
  8263. size_t current_chunk_size =
  8264. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8265. bool result = decompressor.decompress(
  8266. compressed_data.data() + chunk_begin, current_chunk_size,
  8267. [&](const char *decompressed_data_chunk,
  8268. size_t decompressed_data_chunk_size) {
  8269. decompressed_data.insert(decompressed_data.size(),
  8270. decompressed_data_chunk,
  8271. decompressed_data_chunk_size);
  8272. return true;
  8273. });
  8274. ASSERT_TRUE(result);
  8275. }
  8276. }
  8277. ASSERT_EQ(data, decompressed_data);
  8278. }
  8279. TEST(GzipDecompressor, DeflateDecompression) {
  8280. std::string original_text = "Raw deflate without gzip";
  8281. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8282. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8283. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8284. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8285. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8286. std::string decompressed_data;
  8287. {
  8288. httplib::detail::gzip_decompressor decompressor;
  8289. bool result = decompressor.decompress(
  8290. compressed_data.data(), compressed_data.size(),
  8291. [&](const char *decompressed_data_chunk,
  8292. size_t decompressed_data_chunk_size) {
  8293. decompressed_data.insert(decompressed_data.size(),
  8294. decompressed_data_chunk,
  8295. decompressed_data_chunk_size);
  8296. return true;
  8297. });
  8298. ASSERT_TRUE(result);
  8299. }
  8300. ASSERT_EQ(original_text, decompressed_data);
  8301. }
  8302. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8303. std::string original_text = "Raw deflate without gzip";
  8304. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8305. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8306. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8307. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8308. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8309. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8310. std::string decompressed_data;
  8311. {
  8312. httplib::detail::gzip_decompressor decompressor;
  8313. bool result = decompressor.decompress(
  8314. compressed_data.data(), compressed_data.size(),
  8315. [&](const char *decompressed_data_chunk,
  8316. size_t decompressed_data_chunk_size) {
  8317. decompressed_data.insert(decompressed_data.size(),
  8318. decompressed_data_chunk,
  8319. decompressed_data_chunk_size);
  8320. return true;
  8321. });
  8322. ASSERT_TRUE(result);
  8323. }
  8324. ASSERT_EQ(original_text, decompressed_data);
  8325. }
  8326. #endif
  8327. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8328. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8329. Headers headers;
  8330. headers.emplace("Accept-Encoding", "br");
  8331. auto res = cli_.Get("/streamed-chunked", headers);
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ(std::string("123456789"), res->body);
  8335. }
  8336. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8337. Headers headers;
  8338. headers.emplace("Accept-Encoding", "br");
  8339. auto res = cli_.Get("/streamed-chunked2", headers);
  8340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8341. EXPECT_EQ(StatusCode::OK_200, res->status);
  8342. EXPECT_EQ(std::string("123456789"), res->body);
  8343. }
  8344. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8345. cli_.set_compress(true);
  8346. auto res = cli_.Put(
  8347. "/put", 3,
  8348. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8349. sink.os << "PUT";
  8350. return true;
  8351. },
  8352. "text/plain");
  8353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8354. EXPECT_EQ(StatusCode::OK_200, res->status);
  8355. EXPECT_EQ("PUT", res->body);
  8356. }
  8357. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8358. cli_.set_compress(true);
  8359. auto res = cli_.Put(
  8360. "/put",
  8361. [](size_t /*offset*/, DataSink &sink) {
  8362. sink.os << "PUT";
  8363. sink.done();
  8364. return true;
  8365. },
  8366. "text/plain");
  8367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8368. EXPECT_EQ(StatusCode::OK_200, res->status);
  8369. EXPECT_EQ("PUT", res->body);
  8370. }
  8371. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8372. cli_.set_compress(true);
  8373. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8375. EXPECT_EQ(StatusCode::OK_200, res->status);
  8376. EXPECT_EQ(LARGE_DATA, res->body);
  8377. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8378. }
  8379. #endif
  8380. TEST_F(ServerTest, Patch) {
  8381. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. EXPECT_EQ("PATCH", res->body);
  8385. }
  8386. TEST_F(ServerTest, Delete) {
  8387. auto res = cli_.Delete("/delete");
  8388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8389. EXPECT_EQ(StatusCode::OK_200, res->status);
  8390. EXPECT_EQ("DELETE", res->body);
  8391. }
  8392. TEST_F(ServerTest, DeleteContentReceiver) {
  8393. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ(StatusCode::OK_200, res->status);
  8396. EXPECT_EQ("content", res->body);
  8397. }
  8398. TEST_F(ServerTest, Options) {
  8399. auto res = cli_.Options("*");
  8400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8403. EXPECT_TRUE(res->body.empty());
  8404. }
  8405. TEST_F(ServerTest, URL) {
  8406. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8408. EXPECT_EQ(StatusCode::OK_200, res->status);
  8409. }
  8410. TEST_F(ServerTest, ArrayParam) {
  8411. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::OK_200, res->status);
  8414. }
  8415. TEST_F(ServerTest, ArrayParamValues) {
  8416. auto res =
  8417. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ(StatusCode::OK_200, res->status);
  8420. }
  8421. TEST_F(ServerTest, NoMultipleHeaders) {
  8422. Headers headers = {{"Content-Length", "5"}};
  8423. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8424. "text/plain");
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::OK_200, res->status);
  8427. }
  8428. TEST_F(ServerTest, PostContentReceiver) {
  8429. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8431. ASSERT_EQ(StatusCode::OK_200, res->status);
  8432. ASSERT_EQ("content", res->body);
  8433. }
  8434. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8435. UploadFormDataItems items = {
  8436. {"text1", "text default", "", ""},
  8437. {"text2", "aωb", "", ""},
  8438. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8439. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8440. {"file3", "", "", "application/octet-stream"},
  8441. };
  8442. auto res = cli_.Post("/content_receiver", items);
  8443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8444. EXPECT_EQ(StatusCode::OK_200, res->status);
  8445. }
  8446. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8447. UploadFormDataItems items = {
  8448. {"text1", "text default", "", ""},
  8449. {"text2", "aωb", "", ""},
  8450. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8451. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8452. {"file3", "", "", "application/octet-stream"},
  8453. };
  8454. auto boundary = std::string("+++++");
  8455. std::string body;
  8456. for (const auto &item : items) {
  8457. body += "--" + boundary + "\r\n";
  8458. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8459. if (!item.filename.empty()) {
  8460. body += "; filename=\"" + item.filename + "\"";
  8461. }
  8462. body += "\r\n";
  8463. if (!item.content_type.empty()) {
  8464. body += "Content-Type: " + item.content_type + "\r\n";
  8465. }
  8466. body += "\r\n";
  8467. body += item.content + "\r\n";
  8468. }
  8469. body += "--" + boundary + "--\r\n";
  8470. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8471. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. }
  8475. TEST(MultipartFormDataTest, FieldEscaping) {
  8476. Server svr;
  8477. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8478. const ContentReader &content_reader) {
  8479. ASSERT_TRUE(req.is_multipart_form_data());
  8480. std::vector<FormData> received;
  8481. content_reader(
  8482. [&](const FormData &file) {
  8483. received.push_back(file);
  8484. return true;
  8485. },
  8486. [&](const char *data, size_t data_length) {
  8487. received.back().content.append(data, data_length);
  8488. return true;
  8489. });
  8490. // '"', CR and LF in names and filenames are escaped following the
  8491. // WHATWG HTML standard, so each part still parses as a single part
  8492. // with no injected headers. Content types get CR/LF escaped too,
  8493. // while '"' (legal there, e.g. quoted charset) is preserved.
  8494. ASSERT_EQ(4U, received.size());
  8495. EXPECT_EQ("na%22me", received[0].name);
  8496. EXPECT_EQ("quoted name", received[0].content);
  8497. EXPECT_EQ("file", received[1].name);
  8498. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8499. received[1].filename);
  8500. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8501. EXPECT_EQ("injected", received[1].content);
  8502. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8503. EXPECT_EQ("my%22file.txt", received[2].filename);
  8504. EXPECT_EQ("cr lf name", received[2].content);
  8505. EXPECT_EQ("typed", received[3].name);
  8506. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8507. received[3].content_type);
  8508. EXPECT_EQ("typed content", received[3].content);
  8509. });
  8510. auto port = svr.bind_to_any_port("localhost");
  8511. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8512. auto se = detail::scope_exit([&] {
  8513. svr.stop();
  8514. t.join();
  8515. ASSERT_FALSE(svr.is_running());
  8516. });
  8517. svr.wait_until_ready();
  8518. Client cli("localhost", port);
  8519. UploadFormDataItems items = {
  8520. {"na\"me", "quoted name", "", ""},
  8521. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8522. "application/octet-stream"},
  8523. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8524. {"typed", "typed content", "",
  8525. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8526. };
  8527. auto res = cli.Post("/post", items);
  8528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8529. EXPECT_EQ(StatusCode::OK_200, res->status);
  8530. }
  8531. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8532. const UploadFormDataItems items = {
  8533. {"name1", "Content 1", "", ""},
  8534. {"name2", "Content 2", "file2.txt", "text/plain"},
  8535. };
  8536. Server svr;
  8537. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8538. const ContentReader &content_reader) {
  8539. ASSERT_TRUE(req.is_multipart_form_data());
  8540. std::vector<FormData> received;
  8541. content_reader(
  8542. [&](const FormData &file) {
  8543. received.push_back(file);
  8544. return true;
  8545. },
  8546. [&](const char *data, size_t data_length) {
  8547. received.back().content.append(data, data_length);
  8548. return true;
  8549. });
  8550. ASSERT_EQ(2U, received.size());
  8551. EXPECT_EQ("name1", received[0].name);
  8552. EXPECT_EQ("Content 1", received[0].content);
  8553. EXPECT_EQ("name2", received[1].name);
  8554. EXPECT_EQ("Content 2", received[1].content);
  8555. EXPECT_EQ("file2.txt", received[1].filename);
  8556. EXPECT_EQ("text/plain", received[1].content_type);
  8557. });
  8558. auto port = svr.bind_to_any_port("localhost");
  8559. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8560. auto se = detail::scope_exit([&] {
  8561. svr.stop();
  8562. t.join();
  8563. ASSERT_FALSE(svr.is_running());
  8564. });
  8565. svr.wait_until_ready();
  8566. Client cli("localhost", port);
  8567. // Whole-body serialization with a generated boundary
  8568. {
  8569. MultipartFormDataWriter writer;
  8570. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8571. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8572. writer.content_type());
  8573. auto body = writer.serialize(items);
  8574. EXPECT_EQ(body.size(), writer.content_length(items));
  8575. auto res = cli.Post("/post", body, writer.content_type());
  8576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. }
  8579. // Per-part framing with a custom boundary via a content provider
  8580. {
  8581. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8582. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8583. MultipartFormDataWriter writer("custom-boundary_123");
  8584. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8585. std::string body;
  8586. for (const auto &item : items) {
  8587. body += writer.item_begin(item);
  8588. body += item.content;
  8589. body += MultipartFormDataWriter::item_end();
  8590. }
  8591. body += writer.finish();
  8592. EXPECT_EQ(body.size(), writer.content_length(items));
  8593. auto res = cli.Post(
  8594. "/post", body.size(),
  8595. [&](size_t offset, size_t length, DataSink &sink) {
  8596. sink.write(body.data() + offset, length);
  8597. return true;
  8598. },
  8599. writer.content_type());
  8600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8601. EXPECT_EQ(StatusCode::OK_200, res->status);
  8602. }
  8603. }
  8604. TEST_F(ServerTest, PostContentReceiverGzip) {
  8605. cli_.set_compress(true);
  8606. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. ASSERT_EQ(StatusCode::OK_200, res->status);
  8609. ASSERT_EQ("content", res->body);
  8610. }
  8611. TEST_F(ServerTest, PutContentReceiver) {
  8612. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. ASSERT_EQ(StatusCode::OK_200, res->status);
  8615. ASSERT_EQ("content", res->body);
  8616. }
  8617. TEST_F(ServerTest, PatchContentReceiver) {
  8618. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8620. ASSERT_EQ(StatusCode::OK_200, res->status);
  8621. ASSERT_EQ("content", res->body);
  8622. }
  8623. template <typename ClientType>
  8624. void TestWithHeadersAndContentReceiver(
  8625. ClientType &cli,
  8626. std::function<Result(ClientType &, const std::string &, const Headers &,
  8627. const std::string &, const std::string &,
  8628. ContentReceiver, DownloadProgress)>
  8629. request_func) {
  8630. Headers headers;
  8631. headers.emplace("X-Custom-Header", "test-value");
  8632. std::string received_body;
  8633. auto res = request_func(
  8634. cli, "/content_receiver", headers, "content", "application/json",
  8635. [&](const char *data, size_t data_length) {
  8636. received_body.append(data, data_length);
  8637. return true;
  8638. },
  8639. nullptr);
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. EXPECT_EQ("content", received_body);
  8643. }
  8644. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8645. #ifdef CPPHTTPLIB_SSL_ENABLED
  8646. using ClientT = SSLClient;
  8647. #else
  8648. using ClientT = Client;
  8649. #endif
  8650. TestWithHeadersAndContentReceiver<ClientT>(
  8651. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8652. const std::string &body, const std::string &content_type,
  8653. ContentReceiver receiver, DownloadProgress progress) {
  8654. return cli.Post(path, headers, body, content_type, receiver, progress);
  8655. });
  8656. }
  8657. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8658. #ifdef CPPHTTPLIB_SSL_ENABLED
  8659. using ClientT = SSLClient;
  8660. #else
  8661. using ClientT = Client;
  8662. #endif
  8663. TestWithHeadersAndContentReceiver<ClientT>(
  8664. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8665. const std::string &body, const std::string &content_type,
  8666. ContentReceiver receiver, DownloadProgress progress) {
  8667. return cli.Put(path, headers, body, content_type, receiver, progress);
  8668. });
  8669. }
  8670. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8671. #ifdef CPPHTTPLIB_SSL_ENABLED
  8672. using ClientT = SSLClient;
  8673. #else
  8674. using ClientT = Client;
  8675. #endif
  8676. TestWithHeadersAndContentReceiver<ClientT>(
  8677. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8678. const std::string &body, const std::string &content_type,
  8679. ContentReceiver receiver, DownloadProgress progress) {
  8680. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8681. });
  8682. }
  8683. template <typename ClientType>
  8684. void TestWithHeadersAndContentReceiverWithProgress(
  8685. ClientType &cli,
  8686. std::function<Result(ClientType &, const std::string &, const Headers &,
  8687. const std::string &, const std::string &,
  8688. ContentReceiver, DownloadProgress)>
  8689. request_func) {
  8690. Headers headers;
  8691. headers.emplace("X-Test-Header", "progress-test");
  8692. std::string received_body;
  8693. auto progress_called = false;
  8694. auto res = request_func(
  8695. cli, "/content_receiver", headers, "content", "text/plain",
  8696. [&](const char *data, size_t data_length) {
  8697. received_body.append(data, data_length);
  8698. return true;
  8699. },
  8700. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8701. progress_called = true;
  8702. return true;
  8703. });
  8704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8705. EXPECT_EQ(StatusCode::OK_200, res->status);
  8706. EXPECT_EQ("content", received_body);
  8707. EXPECT_TRUE(progress_called);
  8708. }
  8709. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8710. #ifdef CPPHTTPLIB_SSL_ENABLED
  8711. using ClientT = SSLClient;
  8712. #else
  8713. using ClientT = Client;
  8714. #endif
  8715. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8716. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8717. const std::string &body, const std::string &content_type,
  8718. ContentReceiver receiver, DownloadProgress progress) {
  8719. return cli.Post(path, headers, body, content_type, receiver, progress);
  8720. });
  8721. }
  8722. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8723. #ifdef CPPHTTPLIB_SSL_ENABLED
  8724. using ClientT = SSLClient;
  8725. #else
  8726. using ClientT = Client;
  8727. #endif
  8728. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8729. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8730. const std::string &body, const std::string &content_type,
  8731. ContentReceiver receiver, DownloadProgress progress) {
  8732. return cli.Put(path, headers, body, content_type, receiver, progress);
  8733. });
  8734. }
  8735. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8736. #ifdef CPPHTTPLIB_SSL_ENABLED
  8737. using ClientT = SSLClient;
  8738. #else
  8739. using ClientT = Client;
  8740. #endif
  8741. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8742. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8743. const std::string &body, const std::string &content_type,
  8744. ContentReceiver receiver, DownloadProgress progress) {
  8745. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8746. });
  8747. }
  8748. template <typename ClientType>
  8749. void TestWithHeadersAndContentReceiverError(
  8750. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8751. const Headers &, const std::string &,
  8752. const std::string &, ContentReceiver)>
  8753. request_func) {
  8754. Headers headers;
  8755. headers.emplace("X-Error-Test", "true");
  8756. std::string received_body;
  8757. auto receiver_failed = false;
  8758. auto res =
  8759. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8760. [&](const char *data, size_t data_length) {
  8761. received_body.append(data, data_length);
  8762. receiver_failed = true;
  8763. return false;
  8764. });
  8765. ASSERT_FALSE(res);
  8766. EXPECT_TRUE(receiver_failed);
  8767. }
  8768. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8769. #ifdef CPPHTTPLIB_SSL_ENABLED
  8770. using ClientT = SSLClient;
  8771. #else
  8772. using ClientT = Client;
  8773. #endif
  8774. TestWithHeadersAndContentReceiverError<ClientT>(
  8775. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8776. const std::string &body, const std::string &content_type,
  8777. ContentReceiver receiver) {
  8778. return cli.Post(path, headers, body, content_type, receiver);
  8779. });
  8780. }
  8781. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8782. #ifdef CPPHTTPLIB_SSL_ENABLED
  8783. using ClientT = SSLClient;
  8784. #else
  8785. using ClientT = Client;
  8786. #endif
  8787. TestWithHeadersAndContentReceiverError<ClientT>(
  8788. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8789. const std::string &body, const std::string &content_type,
  8790. ContentReceiver receiver) {
  8791. return cli.Put(path, headers, body, content_type, receiver);
  8792. });
  8793. }
  8794. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8795. #ifdef CPPHTTPLIB_SSL_ENABLED
  8796. using ClientT = SSLClient;
  8797. #else
  8798. using ClientT = Client;
  8799. #endif
  8800. TestWithHeadersAndContentReceiverError<ClientT>(
  8801. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8802. const std::string &body, const std::string &content_type,
  8803. ContentReceiver receiver) {
  8804. return cli.Patch(path, headers, body, content_type, receiver);
  8805. });
  8806. }
  8807. TEST_F(ServerTest, PostQueryStringAndBody) {
  8808. auto res =
  8809. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. ASSERT_EQ(StatusCode::OK_200, res->status);
  8812. }
  8813. TEST_F(ServerTest, HTTP2Magic) {
  8814. Request req;
  8815. req.method = "PRI";
  8816. req.path = "*";
  8817. req.body = "SM";
  8818. auto res = std::make_shared<Response>();
  8819. auto error = Error::Success;
  8820. auto ret = cli_.send(req, *res, error);
  8821. ASSERT_TRUE(ret);
  8822. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8823. }
  8824. TEST_F(ServerTest, KeepAlive) {
  8825. auto res = cli_.Get("/hi");
  8826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8829. EXPECT_EQ("Hello World!", res->body);
  8830. res = cli_.Get("/hi");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8834. EXPECT_EQ("Hello World!", res->body);
  8835. res = cli_.Get("/hi");
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_EQ(StatusCode::OK_200, res->status);
  8838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8839. EXPECT_EQ("Hello World!", res->body);
  8840. res = cli_.Get("/not-exist");
  8841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8842. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8843. res = cli_.Post("/empty", "", "text/plain");
  8844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8845. EXPECT_EQ(StatusCode::OK_200, res->status);
  8846. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8847. EXPECT_EQ("empty", res->body);
  8848. EXPECT_EQ("close", res->get_header_value("Connection"));
  8849. res = cli_.Post(
  8850. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8851. "text/plain");
  8852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8853. EXPECT_EQ(StatusCode::OK_200, res->status);
  8854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8855. EXPECT_EQ("empty", res->body);
  8856. cli_.set_keep_alive(false);
  8857. res = cli_.Get("/last-request");
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ(StatusCode::OK_200, res->status);
  8860. EXPECT_EQ("close", res->get_header_value("Connection"));
  8861. }
  8862. TEST_F(ServerTest, TooManyRedirect) {
  8863. cli_.set_follow_location(true);
  8864. auto res = cli_.Get("/redirect/0");
  8865. ASSERT_TRUE(!res);
  8866. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8867. }
  8868. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8869. Request req;
  8870. req.method = "FOOBAR";
  8871. req.path = "/hi";
  8872. cli_.set_keep_alive(true);
  8873. auto res = cli_.send(req);
  8874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8875. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8876. EXPECT_EQ("close", res->get_header_value("Connection"));
  8877. EXPECT_FALSE(cli_.is_socket_open());
  8878. }
  8879. TEST_F(ServerTest, CustomRouteReadsBody) {
  8880. const std::string xml =
  8881. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8882. Request req;
  8883. req.method = "PROPFIND";
  8884. req.path = "/dav/dir";
  8885. req.set_header("Depth", "1");
  8886. req.body = xml;
  8887. auto res = cli_.send(req);
  8888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8889. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8890. EXPECT_EQ(xml, res->body);
  8891. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8892. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8893. }
  8894. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8895. Request req;
  8896. req.method = "PROPFIND";
  8897. req.path = "/dav/42";
  8898. auto res = cli_.send(req);
  8899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8900. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8901. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8902. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8903. }
  8904. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8905. Request req;
  8906. req.method = "PROPFIND";
  8907. req.path = "/dav-re/123";
  8908. auto res = cli_.send(req);
  8909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8910. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8911. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8912. }
  8913. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8914. Request req;
  8915. req.method = "MKCOL";
  8916. req.path = "/dav-mkcol";
  8917. auto res = cli_.send(req);
  8918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8919. EXPECT_EQ(StatusCode::Created_201, res->status);
  8920. }
  8921. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8922. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8923. Request req;
  8924. req.method = "REPORT";
  8925. req.path = "/dav-report";
  8926. req.body = xml;
  8927. auto res = cli_.send(req);
  8928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8929. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8930. EXPECT_EQ(xml, res->body);
  8931. }
  8932. // A content reader route must fire even when the request carries no body,
  8933. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8934. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8935. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8936. Request req;
  8937. req.method = "REPORT";
  8938. req.path = "/dav-report";
  8939. auto res = cli_.send(req);
  8940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8941. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8942. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8943. }
  8944. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8945. Request req;
  8946. req.method = "PROPFIND";
  8947. req.path = "/not-dav";
  8948. auto res = cli_.send(req);
  8949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8950. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8951. }
  8952. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8953. Request req;
  8954. req.method = "UNLOCK";
  8955. req.path = "/dav/dir";
  8956. cli_.set_keep_alive(true);
  8957. auto res = cli_.send(req);
  8958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8959. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8960. EXPECT_EQ("close", res->get_header_value("Connection"));
  8961. EXPECT_FALSE(cli_.is_socket_open());
  8962. }
  8963. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8964. // The mount point serves this path, but only for GET and HEAD.
  8965. auto get_res = cli_.Get("/dir/index.html");
  8966. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8967. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8968. Request req;
  8969. req.method = "PROPFIND";
  8970. req.path = "/dir/index.html";
  8971. auto res = cli_.send(req);
  8972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8973. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8974. }
  8975. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8976. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8977. cli_.set_keep_alive(true);
  8978. for (auto i = 0; i < 2; i++) {
  8979. Request req;
  8980. req.method = "PROPFIND";
  8981. req.path = "/dav/dir";
  8982. req.body = xml;
  8983. auto res = cli_.send(req);
  8984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8985. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8986. EXPECT_EQ(xml, res->body);
  8987. EXPECT_TRUE(cli_.is_socket_open());
  8988. }
  8989. // A built-in method must still be served on the same connection.
  8990. cli_.set_keep_alive(false);
  8991. auto res = cli_.Get("/hi");
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ(StatusCode::OK_200, res->status);
  8994. EXPECT_EQ("close", res->get_header_value("Connection"));
  8995. }
  8996. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8997. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8998. Request req;
  8999. req.method = "PROPFIND";
  9000. req.path = "/dav/dir";
  9001. req.set_header("Expect", "100-continue");
  9002. req.body = xml;
  9003. auto res = cli_.send(req);
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9006. EXPECT_EQ(xml, res->body);
  9007. }
  9008. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9009. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9010. TEST_F(ServerTest, Gzip) {
  9011. Headers headers;
  9012. headers.emplace("Accept-Encoding", "gzip, deflate");
  9013. auto res = cli_.Get("/compress", headers);
  9014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9015. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9016. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9017. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9018. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9019. "7890123456789012345678901234567890",
  9020. res->body);
  9021. EXPECT_EQ(StatusCode::OK_200, res->status);
  9022. }
  9023. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9024. Headers headers;
  9025. headers.emplace("Accept-Encoding", "gzip, deflate");
  9026. auto res = cli_.Get("/compress-with-charset", headers);
  9027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9028. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9029. EXPECT_EQ("application/json; charset=utf-8",
  9030. res->get_header_value("Content-Type"));
  9031. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9032. "7890123456789012345678901234567890",
  9033. res->body);
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. }
  9036. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9037. Headers headers;
  9038. headers.emplace("Accept-Encoding", "");
  9039. auto res = cli_.Get("/compress", headers);
  9040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9041. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9042. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9043. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9044. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9045. "7890123456789012345678901234567890",
  9046. res->body);
  9047. EXPECT_EQ(StatusCode::OK_200, res->status);
  9048. }
  9049. TEST_F(ServerTest, GzipWithContentReceiver) {
  9050. Headers headers;
  9051. headers.emplace("Accept-Encoding", "gzip, deflate");
  9052. std::string body;
  9053. auto res =
  9054. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9055. EXPECT_EQ(100U, data_length);
  9056. body.append(data, data_length);
  9057. return true;
  9058. });
  9059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9060. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9061. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9062. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9063. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9064. "7890123456789012345678901234567890",
  9065. body);
  9066. EXPECT_EQ(StatusCode::OK_200, res->status);
  9067. }
  9068. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9069. Headers headers;
  9070. headers.emplace("Accept-Encoding", "gzip, deflate");
  9071. cli_.set_decompress(false);
  9072. auto res = cli_.Get("/compress", headers);
  9073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9074. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9076. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9077. EXPECT_EQ(33U, res->body.size());
  9078. EXPECT_EQ(StatusCode::OK_200, res->status);
  9079. }
  9080. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9081. Headers headers;
  9082. headers.emplace("Accept-Encoding", "");
  9083. std::string body;
  9084. auto res =
  9085. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9086. EXPECT_EQ(100U, data_length);
  9087. body.append(data, data_length);
  9088. return true;
  9089. });
  9090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9091. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9093. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9094. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9095. "7890123456789012345678901234567890",
  9096. body);
  9097. EXPECT_EQ(StatusCode::OK_200, res->status);
  9098. }
  9099. TEST_F(ServerTest, NoGzip) {
  9100. Headers headers;
  9101. headers.emplace("Accept-Encoding", "gzip, deflate");
  9102. auto res = cli_.Get("/nocompress", headers);
  9103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9104. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9105. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9106. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9107. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9108. "7890123456789012345678901234567890",
  9109. res->body);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. }
  9112. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9113. Headers headers;
  9114. headers.emplace("Accept-Encoding", "gzip, deflate");
  9115. std::string body;
  9116. auto res = cli_.Get("/nocompress", headers,
  9117. [&](const char *data, size_t data_length) {
  9118. EXPECT_EQ(100U, data_length);
  9119. body.append(data, data_length);
  9120. return true;
  9121. });
  9122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9123. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9124. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9125. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9126. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9127. "7890123456789012345678901234567890",
  9128. body);
  9129. EXPECT_EQ(StatusCode::OK_200, res->status);
  9130. }
  9131. TEST_F(ServerTest, MultipartFormDataGzip) {
  9132. UploadFormDataItems items = {
  9133. {"key1", "test", "", ""},
  9134. {"key2", "--abcdefg123", "", ""},
  9135. };
  9136. cli_.set_compress(true);
  9137. auto res = cli_.Post("/compress-multipart", items);
  9138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9139. EXPECT_EQ(StatusCode::OK_200, res->status);
  9140. }
  9141. #endif
  9142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9143. // Static file compression is opt-in, so these run their own server rather than
  9144. // flipping it on for the shared ServerTest fixture, which would silently
  9145. // rewrite what every other static file test is asserting.
  9146. class StaticFileCompressionTest : public ::testing::Test {
  9147. protected:
  9148. void TearDown() override {
  9149. if (t_.joinable()) {
  9150. svr_.stop();
  9151. t_.join();
  9152. }
  9153. }
  9154. int start(const std::function<void(Server &)> &configure = nullptr) {
  9155. // Serves the same tree as a directory of build-time compressed assets
  9156. // would be served: the mount point names the coding the files are already
  9157. // stored in. Registered before "/" so it is the one that matches.
  9158. svr_.set_mount_point("/pre-encoded", "./www",
  9159. {{"Content-Encoding", "gzip"}});
  9160. svr_.set_mount_point("/", "./www");
  9161. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9162. res.set_file_content("./www/dir/index.html", "text/html");
  9163. });
  9164. svr_.Get("/pre-encoded-file-content",
  9165. [](const Request & /*req*/, Response &res) {
  9166. res.set_header("Content-Encoding", "gzip");
  9167. res.set_file_content("./www/dir/index.html", "text/html");
  9168. });
  9169. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9170. res.set_content_provider(
  9171. 6, "text/plain",
  9172. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9173. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9174. return true;
  9175. });
  9176. });
  9177. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9178. res.set_content_provider(
  9179. 1000, "text/plain",
  9180. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9181. if (offset < 100) {
  9182. std::string data(100, 'A');
  9183. sink.write(data.data(), data.size());
  9184. return true;
  9185. }
  9186. std::this_thread::sleep_for(std::chrono::seconds(2));
  9187. std::string data(900, 'B');
  9188. sink.write(data.data(), data.size());
  9189. return true;
  9190. });
  9191. });
  9192. if (configure) { configure(svr_); }
  9193. auto port = svr_.bind_to_any_port(HOST);
  9194. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9195. svr_.wait_until_ready();
  9196. return port;
  9197. }
  9198. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9199. // Every file under ./www except 1MB.txt is smaller than the default
  9200. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9201. // it out of the way.
  9202. static void enable_without_floor(Server &svr) {
  9203. svr.set_static_file_compression(true);
  9204. svr.set_static_file_compression_min_length(0);
  9205. }
  9206. Server svr_;
  9207. std::thread t_;
  9208. };
  9209. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9210. auto port = start();
  9211. Client cli(HOST, port);
  9212. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9214. EXPECT_EQ(StatusCode::OK_200, res->status);
  9215. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9216. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9217. EXPECT_EQ(1048576U, res->body.size());
  9218. }
  9219. TEST_F(StaticFileCompressionTest, MountPoint) {
  9220. auto port = start(enable);
  9221. Client cli(HOST, port);
  9222. cli.set_decompress(false);
  9223. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9225. EXPECT_EQ(StatusCode::OK_200, res->status);
  9226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9227. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9228. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9229. // The response stays self-delimiting: a length, not a chunked body.
  9230. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9231. EXPECT_EQ(std::to_string(res->body.size()),
  9232. res->get_header_value("Content-Length"));
  9233. EXPECT_LT(res->body.size(), 1048576U);
  9234. EXPECT_FALSE(res->body.empty());
  9235. }
  9236. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9237. auto port = start(enable);
  9238. Client cli(HOST, port);
  9239. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9243. EXPECT_EQ(1048576U, res->body.size());
  9244. }
  9245. TEST_F(StaticFileCompressionTest, FileContent) {
  9246. auto port = start(enable_without_floor);
  9247. Client cli(HOST, port);
  9248. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9250. EXPECT_EQ(StatusCode::OK_200, res->status);
  9251. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9252. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9253. EXPECT_EQ(104U, res->body.size());
  9254. }
  9255. // A handler that serves an already-encoded file names the coding itself. The
  9256. // file-backed path decided its coding from Accept-Encoding and the content
  9257. // type alone, so it compressed the stored bytes a second time and appended a
  9258. // second Content-Encoding field line.
  9259. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9260. auto port = start(enable_without_floor);
  9261. Client cli(HOST, port);
  9262. cli.set_decompress(false);
  9263. auto res = cli.Get("/pre-encoded-file-content",
  9264. Headers{{"Accept-Encoding", "gzip"}});
  9265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9266. EXPECT_EQ(StatusCode::OK_200, res->status);
  9267. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9268. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9269. // Vary belongs to a coding the server chose, and it chose none here.
  9270. EXPECT_FALSE(res->has_header("Vary"));
  9271. // The file travels exactly as it is stored on disk.
  9272. EXPECT_EQ(104U, res->body.size());
  9273. }
  9274. // The 1MB file clears the default floor, so this one runs the configuration a
  9275. // deployment would actually have.
  9276. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9277. auto port = start(enable);
  9278. Client cli(HOST, port);
  9279. cli.set_decompress(false);
  9280. auto res =
  9281. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9283. EXPECT_EQ(StatusCode::OK_200, res->status);
  9284. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9285. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9286. EXPECT_FALSE(res->has_header("Vary"));
  9287. EXPECT_EQ(1048576U, res->body.size());
  9288. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9289. }
  9290. TEST_F(StaticFileCompressionTest, Head) {
  9291. auto port = start(enable);
  9292. Client cli(HOST, port);
  9293. cli.set_decompress(false);
  9294. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9295. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9296. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9298. EXPECT_EQ(StatusCode::OK_200, res->status);
  9299. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9300. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9301. // HEAD still reports the size a GET would return.
  9302. EXPECT_EQ(get->get_header_value("Content-Length"),
  9303. res->get_header_value("Content-Length"));
  9304. EXPECT_TRUE(res->body.empty());
  9305. }
  9306. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9307. auto port = start(enable);
  9308. Client cli(HOST, port);
  9309. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9310. {"Accept-Encoding", "gzip"}});
  9311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9313. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9314. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9315. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9316. EXPECT_EQ("cd", res->body);
  9317. }
  9318. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9319. auto port = start(enable);
  9320. Client cli(HOST, port);
  9321. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(StatusCode::OK_200, res->status);
  9324. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9325. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9326. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9327. }
  9328. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9329. auto port = start(enable);
  9330. Client cli(HOST, port);
  9331. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9333. EXPECT_EQ(StatusCode::OK_200, res->status);
  9334. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9335. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9336. EXPECT_TRUE(res->body.empty());
  9337. }
  9338. TEST_F(StaticFileCompressionTest, MinLength) {
  9339. auto port = start(enable);
  9340. Client cli(HOST, port);
  9341. // 104 bytes, well under the default floor. Compressing it would add the
  9342. // gzip header and trailer to a body that already fits in one packet.
  9343. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9345. EXPECT_EQ(StatusCode::OK_200, res->status);
  9346. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9347. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9348. }
  9349. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9350. auto port = start([](Server &svr) {
  9351. svr.set_static_file_compression(true);
  9352. svr.set_static_file_compression_min_length(1);
  9353. });
  9354. Client cli(HOST, port);
  9355. cli.set_decompress(false);
  9356. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9359. // A 9-byte file comes back larger than it went in, because gzip's header and
  9360. // trailer outweigh anything deflate can save. That is the end of the range
  9361. // the floor exists to keep out.
  9362. EXPECT_GT(res->body.size(), 9U);
  9363. }
  9364. TEST_F(StaticFileCompressionTest, MaxLength) {
  9365. auto port = start([](Server &svr) {
  9366. svr.set_static_file_compression(true);
  9367. svr.set_static_file_compression_min_length(0);
  9368. svr.set_static_file_compression_max_length(1024);
  9369. });
  9370. Client cli(HOST, port);
  9371. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9372. // defines `small` as a macro on Windows.
  9373. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9374. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9375. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9376. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9377. // Under it: compressed.
  9378. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9379. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9380. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9381. }
  9382. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9383. auto port = start(enable_without_floor);
  9384. Client cli(HOST, port);
  9385. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9386. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9387. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9388. auto identity_etag = identity->get_header_value("ETag");
  9389. ASSERT_FALSE(identity_etag.empty());
  9390. auto gzipped =
  9391. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9392. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9393. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9394. auto gzip_etag = gzipped->get_header_value("ETag");
  9395. ASSERT_FALSE(gzip_etag.empty());
  9396. // Two representations, two validators.
  9397. EXPECT_NE(identity_etag, gzip_etag);
  9398. // Each one revalidates against the request that would produce it...
  9399. auto fresh =
  9400. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9401. {"If-None-Match", gzip_etag}});
  9402. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9403. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9404. auto fresh_identity =
  9405. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9406. {"If-None-Match", identity_etag}});
  9407. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9408. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9409. // ...and not against the other representation.
  9410. auto crossed =
  9411. cli.Get("/dir/index.html",
  9412. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9413. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9414. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9415. }
  9416. // The opt-in covers responses the server reads off disk itself. A caller's own
  9417. // known-length provider keeps its Content-Length and, more importantly, keeps
  9418. // delivering incrementally: routing it through a compressor would hold every
  9419. // write back until zlib's window filled.
  9420. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9421. auto port = start(enable);
  9422. Client cli(HOST, port);
  9423. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9425. EXPECT_EQ(StatusCode::OK_200, res->status);
  9426. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9427. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9428. EXPECT_EQ("aaabbb", res->body);
  9429. }
  9430. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9431. auto port = start(enable);
  9432. Client cli(HOST, port);
  9433. cli.set_read_timeout(1, 0);
  9434. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9435. Headers{{"Accept-Encoding", "gzip"}});
  9436. ASSERT_TRUE(handle.is_valid());
  9437. // The provider writes 100 bytes and then stalls for longer than the read
  9438. // timeout. Those first bytes have to arrive anyway: run the response through
  9439. // a compressor and zlib holds them until its window fills, so the read would
  9440. // come back empty instead.
  9441. char buf[256];
  9442. auto n = handle.read(buf, sizeof(buf));
  9443. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9444. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9445. }
  9446. #endif
  9447. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9448. TEST_F(ServerTest, Brotli) {
  9449. Headers headers;
  9450. headers.emplace("Accept-Encoding", "br");
  9451. auto res = cli_.Get("/compress", headers);
  9452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9453. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9454. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9455. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9456. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9457. "7890123456789012345678901234567890",
  9458. res->body);
  9459. EXPECT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. #endif
  9462. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9463. TEST_F(ServerTest, Zstd) {
  9464. Headers headers;
  9465. headers.emplace("Accept-Encoding", "zstd");
  9466. auto res = cli_.Get("/compress", headers);
  9467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9468. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9470. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9471. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9472. "7890123456789012345678901234567890",
  9473. res->body);
  9474. EXPECT_EQ(StatusCode::OK_200, res->status);
  9475. }
  9476. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9477. Headers headers;
  9478. headers.emplace("Accept-Encoding", "");
  9479. auto res = cli_.Get("/compress", headers);
  9480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9481. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9483. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9484. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9485. "7890123456789012345678901234567890",
  9486. res->body);
  9487. EXPECT_EQ(StatusCode::OK_200, res->status);
  9488. }
  9489. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9490. Headers headers;
  9491. headers.emplace("Accept-Encoding", "zstd");
  9492. std::string body;
  9493. auto res =
  9494. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9495. EXPECT_EQ(100U, data_length);
  9496. body.append(data, data_length);
  9497. return true;
  9498. });
  9499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9500. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9502. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9503. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9504. "7890123456789012345678901234567890",
  9505. body);
  9506. EXPECT_EQ(StatusCode::OK_200, res->status);
  9507. }
  9508. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9509. Headers headers;
  9510. headers.emplace("Accept-Encoding", "zstd");
  9511. cli_.set_decompress(false);
  9512. auto res = cli_.Get("/compress", headers);
  9513. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9514. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9515. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9516. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9518. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9519. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9520. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9521. EXPECT_EQ(StatusCode::OK_200, res->status);
  9522. ASSERT_EQ(26U, res->body.size());
  9523. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9524. 0);
  9525. }
  9526. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9527. Headers headers;
  9528. headers.emplace("Accept-Encoding", "");
  9529. std::string body;
  9530. auto res =
  9531. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9532. EXPECT_EQ(100U, data_length);
  9533. body.append(data, data_length);
  9534. return true;
  9535. });
  9536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9537. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9539. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9540. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9541. "7890123456789012345678901234567890",
  9542. body);
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. }
  9545. TEST_F(ServerTest, NoZstd) {
  9546. Headers headers;
  9547. headers.emplace("Accept-Encoding", "zstd");
  9548. auto res = cli_.Get("/nocompress", headers);
  9549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9550. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9551. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9552. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9553. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9554. "7890123456789012345678901234567890",
  9555. res->body);
  9556. EXPECT_EQ(StatusCode::OK_200, res->status);
  9557. }
  9558. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9559. Headers headers;
  9560. headers.emplace("Accept-Encoding", "zstd");
  9561. std::string body;
  9562. auto res = cli_.Get("/nocompress", headers,
  9563. [&](const char *data, size_t data_length) {
  9564. EXPECT_EQ(100U, data_length);
  9565. body.append(data, data_length);
  9566. return true;
  9567. });
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9570. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9573. "7890123456789012345678901234567890",
  9574. body);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. }
  9577. // TODO: How to enable zstd ??
  9578. TEST_F(ServerTest, MultipartFormDataZstd) {
  9579. UploadFormDataItems items = {
  9580. {"key1", "test", "", ""},
  9581. {"key2", "--abcdefg123", "", ""},
  9582. };
  9583. Headers headers;
  9584. headers.emplace("Accept-Encoding", "zstd");
  9585. cli_.set_compress(true);
  9586. auto res = cli_.Post("/compress-multipart", headers, items);
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ(StatusCode::OK_200, res->status);
  9589. }
  9590. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9591. Headers headers;
  9592. headers.emplace("Accept-Encoding", "zstd");
  9593. cli_.set_compress(true);
  9594. auto res = cli_.Put(
  9595. "/put", headers, 3,
  9596. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9597. sink.os << "PUT";
  9598. return true;
  9599. },
  9600. "text/plain");
  9601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9602. EXPECT_EQ(StatusCode::OK_200, res->status);
  9603. EXPECT_EQ("PUT", res->body);
  9604. }
  9605. // Pre-compression logging tests
  9606. TEST_F(ServerTest, PreCompressionLogging) {
  9607. // Test data for compression (matches the actual /compress endpoint content)
  9608. const std::string test_content =
  9609. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9610. "3456789012345678901234567890";
  9611. // Variables to capture logging data
  9612. std::string pre_compression_body;
  9613. std::string pre_compression_content_type;
  9614. std::string pre_compression_content_encoding;
  9615. std::string post_compression_body;
  9616. std::string post_compression_content_type;
  9617. std::string post_compression_content_encoding;
  9618. // Set up pre-compression logger
  9619. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9620. const Response &res) {
  9621. pre_compression_body = res.body;
  9622. pre_compression_content_type = res.get_header_value("Content-Type");
  9623. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9624. });
  9625. // Set up post-compression logger
  9626. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9627. post_compression_body = res.body;
  9628. post_compression_content_type = res.get_header_value("Content-Type");
  9629. post_compression_content_encoding =
  9630. res.get_header_value("Content-Encoding");
  9631. });
  9632. // Test with gzip compression
  9633. Headers headers;
  9634. headers.emplace("Accept-Encoding", "gzip");
  9635. auto res = cli_.Get("/compress", headers);
  9636. // Verify response was compressed
  9637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9638. EXPECT_EQ(StatusCode::OK_200, res->status);
  9639. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9640. // Verify pre-compression logger captured uncompressed content
  9641. EXPECT_EQ(test_content, pre_compression_body);
  9642. EXPECT_EQ("text/plain", pre_compression_content_type);
  9643. EXPECT_TRUE(pre_compression_content_encoding
  9644. .empty()); // No encoding header before compression
  9645. // Verify post-compression logger captured compressed content
  9646. EXPECT_NE(test_content,
  9647. post_compression_body); // Should be different after compression
  9648. EXPECT_EQ("text/plain", post_compression_content_type);
  9649. EXPECT_EQ("gzip", post_compression_content_encoding);
  9650. // Verify compressed content is smaller
  9651. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9652. }
  9653. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9654. const std::string test_content =
  9655. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9656. "3456789012345678901234567890";
  9657. std::string pre_compression_body;
  9658. std::string post_compression_body;
  9659. svr_.set_pre_compression_logger(
  9660. [&](const Request & /*req*/, const Response &res) {
  9661. pre_compression_body = res.body;
  9662. });
  9663. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9664. post_compression_body = res.body;
  9665. });
  9666. Headers headers;
  9667. headers.emplace("Accept-Encoding", "br");
  9668. auto res = cli_.Get("/compress", headers);
  9669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9670. EXPECT_EQ(StatusCode::OK_200, res->status);
  9671. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9672. // Verify pre-compression content is uncompressed
  9673. EXPECT_EQ(test_content, pre_compression_body);
  9674. // Verify post-compression content is compressed
  9675. EXPECT_NE(test_content, post_compression_body);
  9676. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9677. }
  9678. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9679. const std::string test_content =
  9680. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9681. "3456789012345678901234567890";
  9682. std::string pre_compression_body;
  9683. std::string post_compression_body;
  9684. svr_.set_pre_compression_logger(
  9685. [&](const Request & /*req*/, const Response &res) {
  9686. pre_compression_body = res.body;
  9687. });
  9688. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9689. post_compression_body = res.body;
  9690. });
  9691. // Request without compression (use /nocompress endpoint)
  9692. Headers headers;
  9693. auto res = cli_.Get("/nocompress", headers);
  9694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9695. EXPECT_EQ(StatusCode::OK_200, res->status);
  9696. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9697. // Pre-compression logger should not be called when no compression is applied
  9698. EXPECT_TRUE(
  9699. pre_compression_body.empty()); // Pre-compression logger not called
  9700. EXPECT_EQ(
  9701. test_content,
  9702. post_compression_body); // Post-compression logger captures final content
  9703. }
  9704. TEST_F(ServerTest, LoggerSeesContentLength) {
  9705. size_t logged_content_length = 0;
  9706. std::string logged_content_length_header;
  9707. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9708. logged_content_length = res.content_length_;
  9709. logged_content_length_header = res.get_header_value("Content-Length");
  9710. });
  9711. auto res = cli_.Get("/nocompress");
  9712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9713. EXPECT_EQ(StatusCode::OK_200, res->status);
  9714. EXPECT_EQ(res->body.size(), logged_content_length);
  9715. EXPECT_EQ(std::to_string(logged_content_length),
  9716. logged_content_length_header);
  9717. }
  9718. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9719. const std::string test_content =
  9720. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9721. "3456789012345678901234567890";
  9722. std::string pre_compression_body;
  9723. bool pre_logger_called = false;
  9724. // Set only pre-compression logger
  9725. svr_.set_pre_compression_logger(
  9726. [&](const Request & /*req*/, const Response &res) {
  9727. pre_compression_body = res.body;
  9728. pre_logger_called = true;
  9729. });
  9730. Headers headers;
  9731. headers.emplace("Accept-Encoding", "gzip");
  9732. auto res = cli_.Get("/compress", headers);
  9733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9734. EXPECT_EQ(StatusCode::OK_200, res->status);
  9735. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9736. // Verify pre-compression logger was called
  9737. EXPECT_TRUE(pre_logger_called);
  9738. EXPECT_EQ(test_content, pre_compression_body);
  9739. }
  9740. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9741. {
  9742. // Test with Expect: 100-continue header - success case
  9743. // Server returns 100 Continue, client sends body, server returns 200 OK
  9744. Request req;
  9745. req.method = "POST";
  9746. req.path = "/post-large";
  9747. req.set_header("Expect", "100-continue");
  9748. req.body = LARGE_DATA;
  9749. Response res;
  9750. auto error = Error::Success;
  9751. cli_.set_keep_alive(true);
  9752. auto ret = cli_.send(req, res, error);
  9753. EXPECT_TRUE(ret);
  9754. EXPECT_EQ(StatusCode::OK_200, res.status);
  9755. EXPECT_EQ(LARGE_DATA, res.body);
  9756. }
  9757. {
  9758. // Test with Expect: 100-continue header - error case
  9759. // Client should not send the body when server returns an error
  9760. Request req;
  9761. req.method = "POST";
  9762. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9763. req.set_header("Expect", "100-continue");
  9764. req.body = LARGE_DATA;
  9765. Response res;
  9766. auto error = Error::Success;
  9767. auto start = std::chrono::high_resolution_clock::now();
  9768. cli_.set_keep_alive(true);
  9769. auto ret = cli_.send(req, res, error);
  9770. auto end = std::chrono::high_resolution_clock::now();
  9771. auto elapsed =
  9772. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9773. .count();
  9774. // With Expect: 100-continue, request completes successfully but with error
  9775. EXPECT_TRUE(ret);
  9776. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9777. EXPECT_EQ("close", res.get_header_value("Connection"));
  9778. EXPECT_FALSE(cli_.is_socket_open());
  9779. EXPECT_LE(elapsed, 2000);
  9780. }
  9781. {
  9782. // Send an extra GET request to ensure error recovery without hanging
  9783. Request req;
  9784. req.method = "GET";
  9785. req.path = "/hi";
  9786. auto start = std::chrono::high_resolution_clock::now();
  9787. auto res = cli_.send(req);
  9788. auto end = std::chrono::high_resolution_clock::now();
  9789. auto elapsed =
  9790. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9791. .count();
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. EXPECT_EQ("Hello World!", res->body);
  9795. EXPECT_LE(elapsed, 500);
  9796. }
  9797. }
  9798. TEST(ZstdDecompressor, ChunkedDecompression) {
  9799. std::string data;
  9800. for (size_t i = 0; i < 32 * 1024; ++i) {
  9801. data.push_back(static_cast<char>('a' + i % 26));
  9802. }
  9803. std::string compressed_data;
  9804. {
  9805. httplib::detail::zstd_compressor compressor;
  9806. bool result = compressor.compress(
  9807. data.data(), data.size(),
  9808. /*last=*/true,
  9809. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9810. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9811. compressed_data_size);
  9812. return true;
  9813. });
  9814. ASSERT_TRUE(result);
  9815. }
  9816. std::string decompressed_data;
  9817. {
  9818. httplib::detail::zstd_decompressor decompressor;
  9819. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9820. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9821. size_t chunk_size = 130;
  9822. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9823. chunk_begin += chunk_size) {
  9824. size_t current_chunk_size =
  9825. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9826. bool result = decompressor.decompress(
  9827. compressed_data.data() + chunk_begin, current_chunk_size,
  9828. [&](const char *decompressed_data_chunk,
  9829. size_t decompressed_data_chunk_size) {
  9830. decompressed_data.insert(decompressed_data.size(),
  9831. decompressed_data_chunk,
  9832. decompressed_data_chunk_size);
  9833. return true;
  9834. });
  9835. ASSERT_TRUE(result);
  9836. }
  9837. }
  9838. ASSERT_EQ(data, decompressed_data);
  9839. }
  9840. TEST(ZstdDecompressor, Decompress) {
  9841. std::string original_text = "Compressed with ZSTD";
  9842. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9843. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9844. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9845. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9846. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9847. std::string decompressed_data;
  9848. {
  9849. httplib::detail::zstd_decompressor decompressor;
  9850. bool result = decompressor.decompress(
  9851. compressed_data.data(), compressed_data.size(),
  9852. [&](const char *decompressed_data_chunk,
  9853. size_t decompressed_data_chunk_size) {
  9854. decompressed_data.insert(decompressed_data.size(),
  9855. decompressed_data_chunk,
  9856. decompressed_data_chunk_size);
  9857. return true;
  9858. });
  9859. ASSERT_TRUE(result);
  9860. }
  9861. ASSERT_EQ(original_text, decompressed_data);
  9862. }
  9863. #endif
  9864. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9865. // separate chunks so that the server sees each part in its own read(). Used to
  9866. // place a read boundary at a specific offset of a request body.
  9867. static bool send_request_in_parts(time_t read_timeout_sec,
  9868. const std::vector<std::string> &parts,
  9869. std::string *resp = nullptr,
  9870. int port = PORT) {
  9871. auto error = Error::Success;
  9872. auto client_sock = detail::create_client_socket(
  9873. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9874. /*connection_timeout_sec=*/5, 0,
  9875. /*read_timeout_sec=*/5, 0,
  9876. /*write_timeout_sec=*/5, 0, std::string(), error);
  9877. if (client_sock == INVALID_SOCKET) { return false; }
  9878. auto ret = detail::process_client_socket(
  9879. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9880. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9881. for (size_t i = 0; i < parts.size(); i++) {
  9882. const auto &part = parts[i];
  9883. if (part.size() !=
  9884. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9885. return false;
  9886. }
  9887. if (i + 1 < parts.size()) {
  9888. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9889. }
  9890. }
  9891. char buf[512];
  9892. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9893. while (line_reader.getline()) {
  9894. if (resp) { *resp += line_reader.ptr(); }
  9895. }
  9896. return true;
  9897. });
  9898. detail::close_socket(client_sock);
  9899. return ret;
  9900. }
  9901. // Sends a raw request to a server listening at HOST:PORT.
  9902. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9903. std::string *resp = nullptr, int port = PORT) {
  9904. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9905. }
  9906. #ifdef CPPHTTPLIB_SSL_ENABLED
  9907. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9909. ASSERT_TRUE(svr.is_valid());
  9910. svr.set_read_timeout(1, 0);
  9911. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9912. auto se = detail::scope_exit([&] {
  9913. svr.stop();
  9914. t.join();
  9915. ASSERT_FALSE(svr.is_running());
  9916. });
  9917. svr.wait_until_ready();
  9918. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9919. // keeps each wait well within the read timeout. The server gives up a
  9920. // second in, so the bytes sent after that fail.
  9921. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9922. parts.resize(26, std::string(1, '\0'));
  9923. EXPECT_FALSE(send_request_in_parts(5, parts));
  9924. }
  9925. #endif
  9926. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9927. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9928. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9929. const std::vector<std::string> &parts,
  9930. std::string *resp = nullptr,
  9931. int port = PORT) {
  9932. auto error = Error::Success;
  9933. auto sock = detail::create_client_socket(
  9934. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9935. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9936. /*write_timeout_sec=*/5, 0, std::string(), error);
  9937. if (sock == INVALID_SOCKET) { return false; }
  9938. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9939. auto ctx = SSL_CTX_new(TLS_client_method());
  9940. auto ssl = SSL_new(ctx);
  9941. auto ssl_se = detail::scope_exit([&] {
  9942. SSL_free(ssl);
  9943. SSL_CTX_free(ctx);
  9944. });
  9945. SSL_set_fd(ssl, static_cast<int>(sock));
  9946. if (SSL_connect(ssl) != 1) { return false; }
  9947. for (size_t i = 0; i < parts.size(); i++) {
  9948. const auto &part = parts[i];
  9949. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9950. static_cast<int>(part.size())) {
  9951. return false;
  9952. }
  9953. if (i + 1 < parts.size()) {
  9954. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9955. }
  9956. }
  9957. char buf[512];
  9958. int n;
  9959. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9960. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9961. }
  9962. return true;
  9963. }
  9964. #endif
  9965. // The request line, then a header value a byte at a time.
  9966. static std::vector<std::string> slow_request_head_parts() {
  9967. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9968. parts.resize(26, "a");
  9969. parts.emplace_back("\r\n\r\n");
  9970. return parts;
  9971. }
  9972. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9973. // within the one-second read timeout. The server gives up a second in, before
  9974. // the head is complete.
  9975. static void
  9976. expect_slow_request_head_dropped(Server &svr,
  9977. const std::function<std::string()> &send) {
  9978. std::atomic<bool> handled(false);
  9979. svr.Get("/", [&](const Request &, Response &res) {
  9980. handled = true;
  9981. res.set_content("ok", "text/plain");
  9982. });
  9983. svr.set_read_timeout(1, 0);
  9984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9985. auto se = detail::scope_exit([&] {
  9986. svr.stop();
  9987. t.join();
  9988. ASSERT_FALSE(svr.is_running());
  9989. });
  9990. svr.wait_until_ready();
  9991. auto resp = send();
  9992. EXPECT_FALSE(handled);
  9993. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9994. }
  9995. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9996. Server svr;
  9997. expect_slow_request_head_dropped(svr, [] {
  9998. std::string resp;
  9999. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10000. return resp;
  10001. });
  10002. }
  10003. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10004. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10006. ASSERT_TRUE(svr.is_valid());
  10007. expect_slow_request_head_dropped(svr, [] {
  10008. std::string resp;
  10009. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10010. return resp;
  10011. });
  10012. }
  10013. #endif
  10014. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10015. Server svr;
  10016. std::string header_value;
  10017. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10018. header_value = req.get_header_value("foo");
  10019. res.set_content("ok", "text/plain");
  10020. });
  10021. thread t = thread([&] { svr.listen(HOST, PORT); });
  10022. auto se = detail::scope_exit([&] {
  10023. svr.stop();
  10024. t.join();
  10025. ASSERT_FALSE(svr.is_running());
  10026. });
  10027. svr.wait_until_ready();
  10028. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10029. // like characters are not treated the same - use vertical tab and escape.
  10030. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10031. "foo: \t \v bar \x1B\t \r\n"
  10032. "Connection: close\r\n"
  10033. "\r\n";
  10034. std::string res;
  10035. ASSERT_TRUE(send_request(5, req, &res));
  10036. EXPECT_EQ(header_value, "");
  10037. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10038. }
  10039. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10040. Server svr;
  10041. std::string received;
  10042. svr.Get("/order", [&](const Request &req, Response &res) {
  10043. received = entries_to_string(req.headers);
  10044. res.set_content("ok", "text/plain");
  10045. });
  10046. auto port = svr.bind_to_any_port(HOST);
  10047. thread t = thread([&] { svr.listen_after_bind(); });
  10048. auto se = detail::scope_exit([&] {
  10049. svr.stop();
  10050. t.join();
  10051. ASSERT_FALSE(svr.is_running());
  10052. });
  10053. svr.wait_until_ready();
  10054. const std::string req = "GET /order HTTP/1.1\r\n"
  10055. "Host: localhost\r\n"
  10056. "X-First: 1\r\n"
  10057. "X-Dup: a\r\n"
  10058. "X-Second: 2\r\n"
  10059. "X-Dup: b\r\n"
  10060. "Connection: close\r\n"
  10061. "\r\n";
  10062. std::string res;
  10063. ASSERT_TRUE(send_request(5, req, &res, port));
  10064. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10065. EXPECT_EQ(
  10066. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10067. received);
  10068. }
  10069. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10070. Server svr;
  10071. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10072. res.set_header("Set-Cookie", "first=1");
  10073. res.set_header("X-Between", "y");
  10074. res.set_header("Set-Cookie", "second=2");
  10075. res.set_content("ok", "text/plain");
  10076. });
  10077. auto port = svr.bind_to_any_port(HOST);
  10078. thread t = thread([&] { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. t.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. });
  10084. svr.wait_until_ready();
  10085. Client cli(HOST, port);
  10086. auto res = cli.Get("/cookies");
  10087. ASSERT_TRUE(res);
  10088. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10089. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10090. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10091. }
  10092. // A stream may send a byte at a time with a small extension on each chunk,
  10093. // however long it runs
  10094. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10095. Server svr;
  10096. svr.Post("/count", [](const Request &req, Response &res) {
  10097. res.set_content(std::to_string(req.body.size()), "text/plain");
  10098. });
  10099. auto port = svr.bind_to_any_port(HOST);
  10100. ASSERT_LT(0, port);
  10101. thread t = thread([&] { svr.listen_after_bind(); });
  10102. auto se = detail::scope_exit([&] {
  10103. svr.stop();
  10104. t.join();
  10105. ASSERT_FALSE(svr.is_running());
  10106. });
  10107. svr.wait_until_ready();
  10108. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10109. "\r\nTransfer-Encoding: chunked\r\n"
  10110. "Connection: close\r\n\r\n";
  10111. for (auto i = 0; i < 4096; i++) {
  10112. req += "1;a=b\r\nx\r\n";
  10113. }
  10114. req += "0\r\n\r\n";
  10115. std::string res;
  10116. ASSERT_TRUE(send_request(5, req, &res, port));
  10117. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10118. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10119. }
  10120. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10121. Server svr;
  10122. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10123. auto i = new int(0);
  10124. res.set_header("Trailer", "X-Safe, X-Reflected");
  10125. res.set_chunked_content_provider(
  10126. "text/plain",
  10127. [i](size_t /*offset*/, DataSink &sink) {
  10128. if (*i == 0) {
  10129. sink.os << "body";
  10130. } else {
  10131. Headers trailer;
  10132. // A valid trailer that must survive.
  10133. trailer.emplace("X-Safe", "safe");
  10134. // Attacker-controlled value carrying CR/LF (response splitting).
  10135. trailer.emplace("X-Reflected",
  10136. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10137. // Attacker-controlled name carrying CR/LF.
  10138. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10139. sink.done_with_trailer(trailer);
  10140. }
  10141. (*i)++;
  10142. return true;
  10143. },
  10144. [i](bool /*success*/) { delete i; });
  10145. });
  10146. thread t = thread([&] { svr.listen(HOST, PORT); });
  10147. auto se = detail::scope_exit([&] {
  10148. svr.stop();
  10149. t.join();
  10150. ASSERT_FALSE(svr.is_running());
  10151. });
  10152. svr.wait_until_ready();
  10153. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10154. "Host: " + HOST +
  10155. "\r\n"
  10156. "Connection: close\r\n"
  10157. "\r\n";
  10158. std::string res;
  10159. ASSERT_TRUE(send_request(5, req, &res));
  10160. // The injected fields must not appear anywhere in the raw response.
  10161. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10162. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10163. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10164. // Invalid trailers are dropped entirely, matching set_header().
  10165. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10166. // The valid trailer still passes through.
  10167. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10168. }
  10169. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10170. // A custom header writer gets only the fields the default one writes
  10171. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10172. std::string s;
  10173. for (const auto &h : hdrs) {
  10174. s += h.first + ": " + h.second + "\r\n";
  10175. }
  10176. s += "\r\n";
  10177. return strm.write(s.data(), s.size());
  10178. };
  10179. for (auto custom_writer : {false, true}) {
  10180. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10181. Server svr;
  10182. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10183. svr.set_post_routing_handler([](const Request &, Response &res) {
  10184. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10185. });
  10186. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10187. // res.headers is a public field an application can populate directly,
  10188. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10189. // A valid header that must survive.
  10190. res.headers.emplace("X-Safe", "safe");
  10191. // Attacker-controlled value carrying CR/LF (response splitting).
  10192. res.headers.emplace("X-Reflected",
  10193. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10194. // Attacker-controlled name carrying CR/LF.
  10195. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10196. res.set_content("body", "text/plain");
  10197. });
  10198. thread t = thread([&] { svr.listen(HOST, PORT); });
  10199. auto se = detail::scope_exit([&] {
  10200. svr.stop();
  10201. t.join();
  10202. ASSERT_FALSE(svr.is_running());
  10203. });
  10204. svr.wait_until_ready();
  10205. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10206. "Host: " + HOST +
  10207. "\r\n"
  10208. "Connection: close\r\n"
  10209. "\r\n";
  10210. std::string res;
  10211. ASSERT_TRUE(send_request(5, req, &res));
  10212. // The injected fields must not appear anywhere in the raw response.
  10213. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10214. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10215. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10216. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10217. // Invalid headers are dropped entirely, matching set_header().
  10218. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10219. // The valid header still passes through.
  10220. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10221. }
  10222. }
  10223. // Forward declaration: in split builds split.py strips `inline` and moves the
  10224. // definition into httplib.cc, so detail::write_request_line is not visible from
  10225. // the public httplib.h. Re-declaring it here lets the tests link against the
  10226. // symbol in both header-only and split builds.
  10227. namespace httplib {
  10228. namespace detail {
  10229. ssize_t write_request_line(Stream &strm, const std::string &method,
  10230. const std::string &path);
  10231. } // namespace detail
  10232. } // namespace httplib
  10233. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10234. // A well-formed target is written verbatim.
  10235. {
  10236. detail::BufferStream strm;
  10237. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10238. EXPECT_GT(n, 0);
  10239. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10240. }
  10241. // A target carrying CR/LF, SP or other control octets must be rejected
  10242. // before anything reaches the wire, otherwise it splits the request line and
  10243. // injects a header or a whole request.
  10244. const std::string evil_targets[] = {
  10245. "/a\r\nInjected: pwned",
  10246. "/a\rInjected",
  10247. "/a\nInjected",
  10248. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10249. "/a b",
  10250. "/a\tb",
  10251. "/a\x7f",
  10252. };
  10253. for (const auto &evil : evil_targets) {
  10254. detail::BufferStream strm;
  10255. auto n = detail::write_request_line(strm, "GET", evil);
  10256. EXPECT_LT(n, 0);
  10257. EXPECT_TRUE(strm.get_buffer().empty());
  10258. }
  10259. }
  10260. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10261. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10262. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10263. // target reaches write_request. The client must fail cleanly with
  10264. // Error::Write instead of putting a request-line-less, header-injecting
  10265. // request on the wire.
  10266. Server svr;
  10267. svr.Get("/a", [](const Request &, Response &res) {
  10268. res.set_content("ok", "text/plain");
  10269. });
  10270. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10271. auto se = detail::scope_exit([&] {
  10272. svr.stop();
  10273. thread.join();
  10274. ASSERT_FALSE(svr.is_running());
  10275. });
  10276. svr.wait_until_ready();
  10277. {
  10278. Client cli(HOST, PORT);
  10279. cli.set_path_encode(false);
  10280. // The request is rejected before anything is written, so the connection
  10281. // stays silent and the subsequent response read would otherwise block for
  10282. // the full default read timeout. Shorten it -- the assertion is on the
  10283. // error, not the timeout.
  10284. cli.set_read_timeout(1, 0);
  10285. auto res = cli.Get("/a\r\nInjected: pwned");
  10286. EXPECT_FALSE(res);
  10287. EXPECT_EQ(Error::Write, res.error());
  10288. }
  10289. }
  10290. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10291. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10292. // including extension methods.
  10293. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10294. for (const auto &method : good_methods) {
  10295. detail::BufferStream strm;
  10296. auto n = detail::write_request_line(strm, method, "/");
  10297. EXPECT_GT(n, 0);
  10298. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10299. }
  10300. // A method carrying CR/LF would split the request line and smuggle a whole
  10301. // request ahead of the real one. A space or an empty method corrupts the
  10302. // request line. All must be rejected before anything reaches the wire.
  10303. const std::string evil_methods[] = {
  10304. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10305. "GET\r\nInjected: pwned",
  10306. "GET\r",
  10307. "GET\n",
  10308. "GE T",
  10309. "",
  10310. };
  10311. for (const auto &evil : evil_methods) {
  10312. detail::BufferStream strm;
  10313. auto n = detail::write_request_line(strm, evil, "/");
  10314. EXPECT_LT(n, 0);
  10315. EXPECT_TRUE(strm.get_buffer().empty());
  10316. }
  10317. }
  10318. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10319. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10320. // through Client::send must fail with Error::Write and no request, neither
  10321. // the smuggled one nor the real one, may reach the server.
  10322. Server svr;
  10323. std::atomic<int> request_count(0);
  10324. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10325. request_count++;
  10326. res.status = StatusCode::OK_200;
  10327. return Server::HandlerResponse::Handled;
  10328. });
  10329. auto port = svr.bind_to_any_port(HOST);
  10330. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10331. auto se = detail::scope_exit([&] {
  10332. svr.stop();
  10333. thread.join();
  10334. ASSERT_FALSE(svr.is_running());
  10335. });
  10336. svr.wait_until_ready();
  10337. {
  10338. Client cli(HOST, port);
  10339. const std::string evil_methods[] = {
  10340. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10341. "GE T",
  10342. "",
  10343. };
  10344. for (const auto &evil : evil_methods) {
  10345. Request req;
  10346. req.method = evil;
  10347. req.path = "/";
  10348. auto res = cli.send(req);
  10349. EXPECT_FALSE(res);
  10350. EXPECT_EQ(Error::Write, res.error());
  10351. }
  10352. auto handle =
  10353. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10354. EXPECT_FALSE(handle.is_valid());
  10355. EXPECT_EQ(Error::Write, handle.error);
  10356. // A valid request on the same client still goes through.
  10357. auto res = cli.Get("/");
  10358. ASSERT_TRUE(res);
  10359. EXPECT_EQ(StatusCode::OK_200, res->status);
  10360. }
  10361. EXPECT_EQ(1, request_count.load());
  10362. }
  10363. // Sends a raw request and verifies that there isn't a crash or exception.
  10364. static void test_raw_request(const std::string &req,
  10365. std::string *out = nullptr) {
  10366. Server svr;
  10367. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10368. res.set_content("ok", "text/plain");
  10369. });
  10370. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10371. res.set_content("ok", "text/plain");
  10372. });
  10373. svr.Get("/header_field_value_check",
  10374. [&](const Request & /*req*/, Response &res) {
  10375. res.set_content("ok", "text/plain");
  10376. });
  10377. svr.CustomRoute("PROPFIND", "/dav",
  10378. [&](const Request & /*req*/, Response &res) {
  10379. res.status = StatusCode::MultiStatus_207;
  10380. });
  10381. // Server read timeout must be longer than the client read timeout for the
  10382. // bug to reproduce, probably to force the server to process a request
  10383. // without a trailing blank line.
  10384. const time_t client_read_timeout_sec = 1;
  10385. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10386. bool listen_thread_ok = false;
  10387. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. t.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. EXPECT_TRUE(listen_thread_ok);
  10393. });
  10394. svr.wait_until_ready();
  10395. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10396. }
  10397. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10398. // A certain header line causes an exception if the header property is parsed
  10399. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10400. test_raw_request(
  10401. "GET /hi HTTP/1.1\r\n"
  10402. " : "
  10403. " "
  10404. " ");
  10405. }
  10406. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10407. // A certain header line causes an exception if the header property *name* is
  10408. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10409. // greedy matcher and requires backtracking when there are a lot of ":"
  10410. // characters.
  10411. // This occurs with libc++ but not libstdc++.
  10412. test_raw_request(
  10413. "GET /hi HTTP/1.1\r\n"
  10414. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10415. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10416. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10417. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10418. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10419. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10420. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10421. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10422. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10423. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10424. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10425. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10426. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10427. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10428. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10429. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10430. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10431. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10432. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10433. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10434. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10435. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10436. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10437. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10438. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10439. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10440. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10441. "&&&%%%");
  10442. }
  10443. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10444. // Make sure this doesn't crash the server.
  10445. // In a previous version of the header line regex, the "\r" rendered the line
  10446. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10447. // a new position where the leading white space ended and the field value
  10448. // began.
  10449. // The crash occurs with libc++ but not libstdc++.
  10450. test_raw_request("GET /hi HTTP/1.1\r\n"
  10451. "a:" +
  10452. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10453. "\r\n"
  10454. "\r\n");
  10455. }
  10456. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10457. const char *rejected[] = {
  10458. // RFC 9112 §3: one SP between the parts, and nothing else
  10459. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10460. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10461. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10462. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10463. // A request-target has no fragment
  10464. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10465. // An HTTP/1.1 request needs a Host
  10466. "GET /hi HTTP/1.1\r\n\r\n",
  10467. };
  10468. for (auto request : rejected) {
  10469. std::string out;
  10470. test_raw_request(request, &out);
  10471. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10472. }
  10473. std::string out;
  10474. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10475. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10476. }
  10477. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10478. // RFC 9112 §6.1
  10479. const char *requests[] = {
  10480. "PUT /put_hi HTTP/1.1\r\n"
  10481. "Host: localhost\r\n"
  10482. "Content-Length: 0\r\n"
  10483. "Transfer-Encoding: chunked\r\n"
  10484. "\r\n"
  10485. "0\r\n\r\n",
  10486. "PUT /put_hi HTTP/1.0\r\n"
  10487. "Connection: keep-alive\r\n"
  10488. "Transfer-Encoding: chunked\r\n"
  10489. "\r\n"
  10490. "0\r\n\r\n",
  10491. };
  10492. for (auto request : requests) {
  10493. std::string out;
  10494. test_raw_request(request, &out);
  10495. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10496. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10497. }
  10498. }
  10499. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10500. std::string out;
  10501. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10502. "Content-Type: text/plain\r\n"
  10503. "Transfer-Encoding: chunked\r\n"
  10504. "\r\n"
  10505. "nothex\r\n",
  10506. &out);
  10507. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10508. }
  10509. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10510. std::string out;
  10511. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10512. "Content-Type: text/plain\r\n"
  10513. "Transfer-Encoding: chunked\r\n"
  10514. "\r\n"
  10515. "3\r\n"
  10516. "xyz\r\n"
  10517. "NaN\r\n",
  10518. &out);
  10519. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10520. }
  10521. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10522. std::string out;
  10523. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10524. "Content-Type: text/plain\r\n"
  10525. "Transfer-Encoding: chunked\r\n"
  10526. "\r\n"
  10527. // Length is too large for 64 bits.
  10528. "1ffffffffffffffff\r\n"
  10529. "xyz\r\n",
  10530. &out);
  10531. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10532. }
  10533. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10534. test_raw_request("GET /hi HTTP/1.1\r\n"
  10535. "Content-Type: text/plain\r\n\r");
  10536. }
  10537. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10538. std::string out;
  10539. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10540. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10541. }
  10542. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10543. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10544. std::string out;
  10545. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10546. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10547. }
  10548. }
  10549. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10550. std::string out;
  10551. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10552. "Host: localhost\r\n"
  10553. "Connection: close\r\n\r\n",
  10554. &out);
  10555. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10556. }
  10557. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10558. Server svr;
  10559. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10560. EXPECT_TRUE(!req.remote_addr.empty());
  10561. });
  10562. thread t = thread([&] { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. t.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.wait_until_ready();
  10569. // Send an invalid request line to trigger Bad Request
  10570. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10571. std::string out;
  10572. ASSERT_TRUE(send_request(5, bad_req, &out));
  10573. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10574. }
  10575. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10576. // answered right away rather than blocking on a read that waits for EOF.
  10577. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10578. std::string out;
  10579. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10580. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10581. }
  10582. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10583. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10584. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10585. for (const auto *method : methods) {
  10586. Server svr;
  10587. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10588. EXPECT_FALSE(svr.is_valid()) << method;
  10589. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10590. }
  10591. }
  10592. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10593. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10594. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10595. for (const auto *method : methods) {
  10596. Server svr;
  10597. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10598. EXPECT_FALSE(svr.is_valid()) << method;
  10599. }
  10600. }
  10601. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10602. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10603. "COPY", "MOVE", "LOCK",
  10604. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10605. Server svr;
  10606. for (const auto *method : methods) {
  10607. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10608. }
  10609. EXPECT_TRUE(svr.is_valid());
  10610. }
  10611. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10612. Server svr;
  10613. svr.CustomRoute("POST", "/x",
  10614. [](const Request &, Response &, const ContentReader &) {});
  10615. EXPECT_FALSE(svr.is_valid());
  10616. }
  10617. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10618. Server svr;
  10619. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10620. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10621. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10622. EXPECT_FALSE(svr.is_valid());
  10623. }
  10624. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10625. Server svr;
  10626. auto captured = Error::Success;
  10627. svr.set_error_logger(
  10628. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10629. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10630. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10631. }
  10632. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10633. std::string out;
  10634. std::string request(
  10635. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10636. test_raw_request(request, &out);
  10637. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10638. }
  10639. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10640. std::string out;
  10641. std::string request(
  10642. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10643. test_raw_request(request, &out);
  10644. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10645. }
  10646. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10647. std::string out;
  10648. std::string request(
  10649. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10650. test_raw_request(request, &out);
  10651. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10652. }
  10653. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10654. std::string out;
  10655. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10656. "Host: localhost\r\n"
  10657. "Test: \r\n\r\n",
  10658. &out);
  10659. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10660. }
  10661. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10662. Server svr;
  10663. std::string x_custom;
  10664. std::string cookie;
  10665. std::string xff;
  10666. std::string x_unicode;
  10667. std::string x_iis;
  10668. svr.Get("/check", [&](const Request &req, Response &res) {
  10669. x_custom = req.get_header_value("X-Custom");
  10670. cookie = req.get_header_value("Cookie");
  10671. xff = req.get_header_value("X-Forwarded-For");
  10672. x_unicode = req.get_header_value("X-Unicode");
  10673. x_iis = req.get_header_value("X-IIS");
  10674. res.set_content("ok", "text/plain");
  10675. });
  10676. thread t = thread([&] { svr.listen(HOST, PORT); });
  10677. auto se = detail::scope_exit([&] {
  10678. svr.stop();
  10679. t.join();
  10680. ASSERT_FALSE(svr.is_running());
  10681. });
  10682. svr.wait_until_ready();
  10683. const std::string req = "GET /check HTTP/1.1\r\n"
  10684. "Host: localhost\r\n"
  10685. "X-Custom: a%0D%0AInjected: b\r\n"
  10686. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10687. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10688. "X-Unicode: %E3%81%82\r\n"
  10689. "X-IIS: %u00E9\r\n"
  10690. "Connection: close\r\n"
  10691. "\r\n";
  10692. std::string res;
  10693. ASSERT_TRUE(send_request(5, req, &res));
  10694. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10695. // Every value must be returned verbatim (wire form), with no decoding.
  10696. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10697. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10698. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10699. EXPECT_EQ("%E3%81%82", x_unicode);
  10700. EXPECT_EQ("%u00E9", x_iis);
  10701. }
  10702. // Applications that previously relied on automatic percent-decoding can
  10703. // reproduce the old behavior by explicitly calling decode_path_component()
  10704. // or, for RFC 3986 conformance, decode_uri_component().
  10705. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10706. Server svr;
  10707. std::string decoded;
  10708. svr.Get("/check", [&](const Request &req, Response &res) {
  10709. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10710. res.set_content("ok", "text/plain");
  10711. });
  10712. thread t = thread([&] { svr.listen(HOST, PORT); });
  10713. auto se = detail::scope_exit([&] {
  10714. svr.stop();
  10715. t.join();
  10716. ASSERT_FALSE(svr.is_running());
  10717. });
  10718. svr.wait_until_ready();
  10719. const std::string req = "GET /check HTTP/1.1\r\n"
  10720. "Host: localhost\r\n"
  10721. "X-Custom: hello%20world\r\n"
  10722. "Connection: close\r\n"
  10723. "\r\n";
  10724. std::string res;
  10725. ASSERT_TRUE(send_request(5, req, &res));
  10726. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10727. EXPECT_EQ("hello world", decoded);
  10728. }
  10729. // Regression test for #2033. Browsers send Referer values that include
  10730. // percent-encoded characters such as %0A inside the URL. Decoding the
  10731. // header value would either trip the post-decode CR/LF/NUL guard (the
  10732. // original bug, returning 400) or, after that guard was relaxed, silently
  10733. // store a literal LF — both unacceptable. The wire form must round-trip.
  10734. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10735. Server svr;
  10736. std::string referer;
  10737. svr.Get("/check", [&](const Request &req, Response &res) {
  10738. referer = req.get_header_value("Referer");
  10739. res.set_content("ok", "text/plain");
  10740. });
  10741. thread t = thread([&] { svr.listen(HOST, PORT); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. t.join();
  10745. ASSERT_FALSE(svr.is_running());
  10746. });
  10747. svr.wait_until_ready();
  10748. const std::string req = "GET /check HTTP/1.1\r\n"
  10749. "Host: localhost\r\n"
  10750. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10751. "Connection: close\r\n"
  10752. "\r\n";
  10753. std::string res;
  10754. ASSERT_TRUE(send_request(5, req, &res));
  10755. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10756. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10757. }
  10758. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10759. Server svr;
  10760. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10761. res.set_header("Cache-Control", "no-cache");
  10762. res.set_chunked_content_provider(
  10763. "text/event-stream", [](size_t offset, DataSink &sink) {
  10764. std::string s = "data:";
  10765. s += std::to_string(offset);
  10766. s += "\n\n";
  10767. auto ret = sink.write(s.data(), s.size());
  10768. EXPECT_TRUE(ret);
  10769. std::this_thread::sleep_for(std::chrono::seconds(1));
  10770. return true;
  10771. });
  10772. });
  10773. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10774. svr.wait_until_ready();
  10775. Client client(HOST, PORT);
  10776. const Headers headers = {{"Accept", "text/event-stream"}};
  10777. auto get_thread = std::thread([&client, &headers]() {
  10778. auto res = client.Get(
  10779. "/events", headers,
  10780. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10781. });
  10782. auto se = detail::scope_exit([&] {
  10783. svr.stop();
  10784. get_thread.join();
  10785. listen_thread.join();
  10786. ASSERT_FALSE(svr.is_running());
  10787. });
  10788. // Give GET time to get a few messages.
  10789. std::this_thread::sleep_for(std::chrono::seconds(2));
  10790. }
  10791. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10792. httplib::Server svr;
  10793. svr.Post("/hi",
  10794. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10795. res.status = StatusCode::OK_200;
  10796. });
  10797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10798. svr.wait_until_ready();
  10799. Client cli(HOST, PORT);
  10800. auto res = cli.Post("/hi", "data", "text/plain");
  10801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10802. EXPECT_EQ(StatusCode::OK_200, res->status);
  10803. svr.stop();
  10804. thread.join();
  10805. ASSERT_FALSE(svr.is_running());
  10806. res = cli.Post("/hi", "data", "text/plain");
  10807. ASSERT_FALSE(res);
  10808. }
  10809. TEST(ServerStopTest, ListenFailure) {
  10810. Server svr;
  10811. auto t = thread([&]() {
  10812. auto ret = svr.listen("????", PORT);
  10813. EXPECT_FALSE(ret);
  10814. });
  10815. svr.wait_until_ready();
  10816. svr.stop();
  10817. t.join();
  10818. }
  10819. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10820. TEST(ServerStopTest, Decommision) {
  10821. Server svr;
  10822. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10823. for (int i = 0; i < 4; i++) {
  10824. auto is_even = !(i % 2);
  10825. std::thread t{[&] {
  10826. try {
  10827. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10828. if (is_even) {
  10829. throw std::runtime_error("Some thing that happens to go wrong.");
  10830. }
  10831. svr.listen(HOST, PORT);
  10832. } catch (...) { svr.decommission(); }
  10833. }};
  10834. svr.wait_until_ready();
  10835. // Server is up
  10836. {
  10837. Client cli(HOST, PORT);
  10838. auto res = cli.Get("/hi");
  10839. if (is_even) {
  10840. EXPECT_FALSE(res);
  10841. } else {
  10842. EXPECT_TRUE(res);
  10843. EXPECT_EQ("hi...", res->body);
  10844. }
  10845. }
  10846. svr.stop();
  10847. t.join();
  10848. // Server is down...
  10849. {
  10850. Client cli(HOST, PORT);
  10851. auto res = cli.Get("/hi");
  10852. EXPECT_FALSE(res);
  10853. }
  10854. }
  10855. }
  10856. #endif
  10857. // Helper function for string body upload progress tests
  10858. template <typename SetupHandler, typename ClientCall>
  10859. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10860. ClientCall &&client_call,
  10861. const string &body) {
  10862. Server svr;
  10863. setup_handler(svr);
  10864. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. t.join();
  10868. });
  10869. svr.wait_until_ready();
  10870. Client cli(HOST, PORT);
  10871. vector<uint64_t> progress_values;
  10872. bool progress_called = false;
  10873. auto res =
  10874. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10875. progress_values.push_back(current);
  10876. progress_called = true;
  10877. return true;
  10878. });
  10879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10880. EXPECT_EQ(200, res->status);
  10881. EXPECT_TRUE(progress_called);
  10882. }
  10883. TEST(UploadProgressTest, PostStringBodyBasic) {
  10884. TestStringBodyUploadProgress(
  10885. [](Server &svr) {
  10886. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10887. res.set_content("received", "text/plain");
  10888. });
  10889. },
  10890. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10891. return cli.Post("/test", body, "text/plain", progress_callback);
  10892. },
  10893. "test data for upload progress");
  10894. }
  10895. TEST(UploadProgressTest, PutStringBodyBasic) {
  10896. TestStringBodyUploadProgress(
  10897. [](Server &svr) {
  10898. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10899. res.set_content("put received", "text/plain");
  10900. });
  10901. },
  10902. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10903. return cli.Put("/test", body, "text/plain", progress_callback);
  10904. },
  10905. "put test data for upload progress");
  10906. }
  10907. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10908. TestStringBodyUploadProgress(
  10909. [](Server &svr) {
  10910. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10911. res.set_content("patch received", "text/plain");
  10912. });
  10913. },
  10914. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10915. return cli.Patch("/test", body, "text/plain", progress_callback);
  10916. },
  10917. "patch test data for upload progress");
  10918. }
  10919. // Helper function for content provider upload progress tests
  10920. template <typename SetupHandler, typename ClientCall>
  10921. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10922. ClientCall &&client_call) {
  10923. Server svr;
  10924. setup_handler(svr);
  10925. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. t.join();
  10929. });
  10930. svr.wait_until_ready();
  10931. Client cli(HOST, PORT);
  10932. vector<uint64_t> progress_values;
  10933. auto res =
  10934. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10935. progress_values.push_back(current);
  10936. return true;
  10937. });
  10938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10939. EXPECT_EQ(200, res->status);
  10940. EXPECT_FALSE(progress_values.empty());
  10941. }
  10942. TEST(UploadProgressTest, PostContentProviderProgress) {
  10943. TestContentProviderUploadProgress(
  10944. [](Server &svr) {
  10945. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10946. res.set_content("provider received", "text/plain");
  10947. });
  10948. },
  10949. [](Client &cli, UploadProgress progress_callback) {
  10950. return cli.Post(
  10951. "/test", 9,
  10952. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10953. sink.os << "test data";
  10954. return true;
  10955. },
  10956. "text/plain", progress_callback);
  10957. });
  10958. }
  10959. // Helper function for multipart upload progress tests
  10960. template <typename SetupHandler, typename ClientCall>
  10961. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10962. ClientCall &&client_call,
  10963. const string &endpoint) {
  10964. Server svr;
  10965. setup_handler(svr);
  10966. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10967. auto se = detail::scope_exit([&] {
  10968. svr.stop();
  10969. t.join();
  10970. });
  10971. svr.wait_until_ready();
  10972. Client cli(HOST, PORT);
  10973. vector<uint64_t> progress_values;
  10974. UploadFormDataItems items = {
  10975. {"field1", "value1", "", ""},
  10976. {"field2", "longer value for progress tracking test", "", ""},
  10977. {"file1", "file content data for upload progress", "test.txt",
  10978. "text/plain"}};
  10979. auto res = client_call(cli, endpoint, items,
  10980. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10981. progress_values.push_back(current);
  10982. return true;
  10983. });
  10984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10985. EXPECT_EQ(200, res->status);
  10986. EXPECT_FALSE(progress_values.empty());
  10987. }
  10988. TEST(UploadProgressTest, PostMultipartProgress) {
  10989. TestMultipartUploadProgress(
  10990. [](Server &svr) {
  10991. svr.Post("/multipart", [](const Request &req, Response &res) {
  10992. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10993. res.set_content("multipart received", "text/plain");
  10994. });
  10995. },
  10996. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10997. UploadProgress progress_callback) {
  10998. return cli.Post(endpoint, items, progress_callback);
  10999. },
  11000. "/multipart");
  11001. }
  11002. // Helper function for basic download progress tests
  11003. template <typename SetupHandler, typename ClientCall>
  11004. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11005. ClientCall &&client_call, const string &endpoint,
  11006. size_t expected_content_size) {
  11007. Server svr;
  11008. setup_handler(svr);
  11009. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. t.join();
  11013. });
  11014. svr.wait_until_ready();
  11015. Client cli(HOST, PORT);
  11016. vector<uint64_t> progress_values;
  11017. auto res = client_call(cli, endpoint,
  11018. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11019. progress_values.push_back(current);
  11020. return true;
  11021. });
  11022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11023. EXPECT_EQ(200, res->status);
  11024. EXPECT_FALSE(progress_values.empty());
  11025. EXPECT_EQ(expected_content_size, res->body.size());
  11026. }
  11027. TEST(DownloadProgressTest, GetBasic) {
  11028. TestBasicDownloadProgress(
  11029. [](Server &svr) {
  11030. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11031. string content(1000, 'D');
  11032. res.set_content(content, "text/plain");
  11033. });
  11034. },
  11035. [](Client &cli, const string &endpoint,
  11036. DownloadProgress progress_callback) {
  11037. return cli.Get(endpoint, progress_callback);
  11038. },
  11039. "/download", 1000u);
  11040. }
  11041. // Helper function for content receiver download progress tests
  11042. template <typename SetupHandler, typename ClientCall>
  11043. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11044. ClientCall &&client_call,
  11045. const string &endpoint,
  11046. size_t expected_content_size) {
  11047. Server svr;
  11048. setup_handler(svr);
  11049. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. t.join();
  11053. });
  11054. svr.wait_until_ready();
  11055. Client cli(HOST, PORT);
  11056. vector<uint64_t> progress_values;
  11057. string received_body;
  11058. auto res = client_call(
  11059. cli, endpoint,
  11060. [&](const char *data, size_t data_length) -> bool {
  11061. received_body.append(data, data_length);
  11062. return true;
  11063. },
  11064. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11065. progress_values.push_back(current);
  11066. return true;
  11067. });
  11068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11069. EXPECT_EQ(200, res->status);
  11070. EXPECT_FALSE(progress_values.empty());
  11071. EXPECT_EQ(expected_content_size, received_body.size());
  11072. EXPECT_TRUE(res->body.empty());
  11073. }
  11074. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11075. TestContentReceiverDownloadProgress(
  11076. [](Server &svr) {
  11077. svr.Get("/download-receiver",
  11078. [](const Request & /*req*/, Response &res) {
  11079. string content(2000, 'R');
  11080. res.set_content(content, "text/plain");
  11081. });
  11082. },
  11083. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11084. DownloadProgress progress_callback) {
  11085. return cli.Get(endpoint, content_receiver, progress_callback);
  11086. },
  11087. "/download-receiver", 2000u);
  11088. }
  11089. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11090. // A provider reaching a pass with nothing to hand over - an empty buffer
  11091. // popped off a queue, say - must not be taken to mean the body is finished.
  11092. // It used to end the loop with the terminating chunk unwritten while the
  11093. // server still considered the response complete, so the peer waited for an
  11094. // end that never arrived.
  11095. Server svr;
  11096. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11097. auto step = std::make_shared<int>(0);
  11098. res.set_chunked_content_provider("text/plain",
  11099. [step](size_t /*offset*/, DataSink &sink) {
  11100. switch ((*step)++) {
  11101. case 0: sink.write("", 0); break;
  11102. case 1: sink.write("hello", 5); break;
  11103. default: sink.done(); break;
  11104. }
  11105. return true;
  11106. });
  11107. });
  11108. auto port = svr.bind_to_any_port(HOST);
  11109. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11110. auto listen_se = detail::scope_exit([&] {
  11111. svr.stop();
  11112. listen_thread.join();
  11113. ASSERT_FALSE(svr.is_running());
  11114. });
  11115. svr.wait_until_ready();
  11116. Client cli(HOST, port);
  11117. // Without the fix the body is never terminated, so bound the wait rather
  11118. // than letting the test hang on the default read timeout.
  11119. cli.set_read_timeout(5, 0);
  11120. auto res = cli.Get("/stream");
  11121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11122. EXPECT_EQ(StatusCode::OK_200, res->status);
  11123. EXPECT_EQ("hello", res->body);
  11124. }
  11125. TEST(StreamingTest, NoContentLengthStreaming) {
  11126. Server svr;
  11127. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11128. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11129. if (offset < 6) {
  11130. sink.os << (offset < 3 ? "a" : "b");
  11131. } else {
  11132. sink.done();
  11133. }
  11134. return true;
  11135. });
  11136. });
  11137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11138. auto listen_se = detail::scope_exit([&] {
  11139. svr.stop();
  11140. listen_thread.join();
  11141. ASSERT_FALSE(svr.is_running());
  11142. });
  11143. svr.wait_until_ready();
  11144. Client client(HOST, PORT);
  11145. auto get_thread = std::thread([&client]() {
  11146. std::string s;
  11147. auto res =
  11148. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11149. s += std::string(data, len);
  11150. return true;
  11151. });
  11152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11153. EXPECT_EQ(StatusCode::OK_200, res->status);
  11154. EXPECT_EQ("aaabbb", s);
  11155. });
  11156. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11157. // Give GET time to get a few messages.
  11158. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11159. }
  11160. TEST(MountTest, Unmount) {
  11161. Server svr;
  11162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11163. auto se = detail::scope_exit([&] {
  11164. svr.stop();
  11165. listen_thread.join();
  11166. ASSERT_FALSE(svr.is_running());
  11167. });
  11168. svr.wait_until_ready();
  11169. Client cli("localhost", PORT);
  11170. svr.set_mount_point("/mount2", "./www2");
  11171. auto res = cli.Get("/");
  11172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11173. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11174. res = cli.Get("/mount2/dir/test.html");
  11175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11176. EXPECT_EQ(StatusCode::OK_200, res->status);
  11177. svr.set_mount_point("/", "./www");
  11178. res = cli.Get("/dir/");
  11179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11180. EXPECT_EQ(StatusCode::OK_200, res->status);
  11181. svr.remove_mount_point("/");
  11182. res = cli.Get("/dir/");
  11183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11184. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11185. svr.remove_mount_point("/mount2");
  11186. res = cli.Get("/mount2/dir/test.html");
  11187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11188. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11189. }
  11190. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11191. Server svr;
  11192. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11193. svr.Get("/api/hello", [](const Request &, Response &res) {
  11194. res.set_content("api", "text/plain");
  11195. });
  11196. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11197. auto se = detail::scope_exit([&] {
  11198. svr.stop();
  11199. listen_thread.join();
  11200. ASSERT_FALSE(svr.is_running());
  11201. });
  11202. svr.wait_until_ready();
  11203. Client cli(HOST, PORT);
  11204. auto res = cli.Get("/dir/test.html");
  11205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11206. EXPECT_EQ(StatusCode::OK_200, res->status);
  11207. res = cli.Get("/api/hello");
  11208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11209. EXPECT_EQ(StatusCode::OK_200, res->status);
  11210. EXPECT_EQ("api", res->body);
  11211. }
  11212. TEST(MountTest, PathSegmentBoundary) {
  11213. Server svr;
  11214. svr.set_mount_point("/mount2", "./www2");
  11215. svr.set_mount_point("/", "./www");
  11216. auto port = svr.bind_to_any_port(HOST);
  11217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11218. auto se = detail::scope_exit([&] {
  11219. svr.stop();
  11220. listen_thread.join();
  11221. ASSERT_FALSE(svr.is_running());
  11222. });
  11223. svr.wait_until_ready();
  11224. Client cli(HOST, port);
  11225. auto res = cli.Get("/mount2/dir/test.html");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::OK_200, res->status);
  11228. // "/mount2" must not match part-way through a path segment.
  11229. res = cli.Get("/mount2dir/test.html");
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11232. // A mount point ending in '/' keeps matching every path below it.
  11233. res = cli.Get("/dir/test.html");
  11234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11235. EXPECT_EQ(StatusCode::OK_200, res->status);
  11236. }
  11237. TEST(MountTest, Redicect) {
  11238. Server svr;
  11239. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11240. auto se = detail::scope_exit([&] {
  11241. svr.stop();
  11242. listen_thread.join();
  11243. ASSERT_FALSE(svr.is_running());
  11244. });
  11245. svr.set_mount_point("/", "./www");
  11246. svr.wait_until_ready();
  11247. Client cli("localhost", PORT);
  11248. auto res = cli.Get("/dir/");
  11249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11250. EXPECT_EQ(StatusCode::OK_200, res->status);
  11251. res = cli.Get("/dir");
  11252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11253. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11254. res = cli.Get("/file");
  11255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11256. EXPECT_EQ(StatusCode::OK_200, res->status);
  11257. res = cli.Get("/file/");
  11258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11259. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11260. cli.set_follow_location(true);
  11261. res = cli.Get("/dir");
  11262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11263. EXPECT_EQ(StatusCode::OK_200, res->status);
  11264. }
  11265. TEST(MountTest, MultibytesPathName) {
  11266. Server svr;
  11267. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11268. auto se = detail::scope_exit([&] {
  11269. svr.stop();
  11270. listen_thread.join();
  11271. ASSERT_FALSE(svr.is_running());
  11272. });
  11273. svr.set_mount_point("/", "./www");
  11274. svr.wait_until_ready();
  11275. Client cli("localhost", PORT);
  11276. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11278. EXPECT_EQ(StatusCode::OK_200, res->status);
  11279. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11280. }
  11281. // A mount point serves no path with an empty segment or one ending in '.' or
  11282. // a space, so a guard in the pre-routing handler sees the path of every file
  11283. // that is served
  11284. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11285. Server svr;
  11286. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11287. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11288. if (req.path == "/dir/test.html") {
  11289. res.status = StatusCode::Unauthorized_401;
  11290. return Server::HandlerResponse::Handled;
  11291. }
  11292. return Server::HandlerResponse::Unhandled;
  11293. });
  11294. auto port = svr.bind_to_any_port(HOST);
  11295. ASSERT_LT(0, port);
  11296. thread t = thread([&] { svr.listen_after_bind(); });
  11297. auto se = detail::scope_exit([&] {
  11298. svr.stop();
  11299. t.join();
  11300. ASSERT_FALSE(svr.is_running());
  11301. });
  11302. svr.wait_until_ready();
  11303. Client cli(HOST, port);
  11304. for (auto path :
  11305. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11306. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11307. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11308. "/dir/test.html%3A%3A$DATA"}) {
  11309. SCOPED_TRACE(path);
  11310. auto res = cli.Get(path);
  11311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11312. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11313. }
  11314. }
  11315. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11316. Server svr;
  11317. svr.set_mount_point("/", "./www");
  11318. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11319. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11320. auto port = svr.bind_to_any_port(HOST);
  11321. ASSERT_GT(port, 0);
  11322. thread t = thread([&] { svr.listen_after_bind(); });
  11323. auto se = detail::scope_exit([&] {
  11324. svr.stop();
  11325. t.join();
  11326. ASSERT_FALSE(svr.is_running());
  11327. });
  11328. svr.wait_until_ready();
  11329. Client cli(HOST, port);
  11330. auto res = cli.Get("/dir/test.abcde");
  11331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11332. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11333. res = cli.Get("/dir/test.html");
  11334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11335. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11336. }
  11337. #ifdef _WIN32
  11338. // Issue #2435: mmap::open() must succeed even when another handle holds
  11339. // the file open for writing (e.g. an active log file).
  11340. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11341. const char *path = "mmap_concurrent_writer_test.txt";
  11342. const char *content = "hello";
  11343. {
  11344. std::ofstream f(path, std::ios::binary);
  11345. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11346. }
  11347. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11348. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11349. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11350. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11351. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11352. detail::mmap m(path);
  11353. ASSERT_TRUE(m.is_open());
  11354. EXPECT_EQ(strlen(content), m.size());
  11355. char buf[8];
  11356. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11357. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11358. }
  11359. #endif
  11360. #ifndef _WIN32
  11361. // A directory or a device has no size to serve.
  11362. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11363. const char *path = "./mmap_not_regular_test_dir";
  11364. ASSERT_EQ(0, ::mkdir(path, 0755));
  11365. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11366. for (auto p : {path, "/dev/null"}) {
  11367. detail::mmap m(p);
  11368. EXPECT_FALSE(m.is_open()) << p;
  11369. EXPECT_EQ(0U, m.size()) << p;
  11370. }
  11371. Server svr;
  11372. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11373. res.set_file_content("/dev/null");
  11374. });
  11375. auto port = svr.bind_to_any_port(HOST);
  11376. thread t = thread([&] { svr.listen_after_bind(); });
  11377. auto se = detail::scope_exit([&] {
  11378. svr.stop();
  11379. t.join();
  11380. });
  11381. svr.wait_until_ready();
  11382. auto res = Client(HOST, port).Get("/null");
  11383. ASSERT_TRUE(res);
  11384. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11385. }
  11386. #endif
  11387. #ifdef __linux__
  11388. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11389. TEST(MmapTest, FileIsNotMapped) {
  11390. const char *path = "mmap_not_mapped_test.txt";
  11391. {
  11392. std::ofstream f(path, std::ios::binary);
  11393. f << "hello";
  11394. }
  11395. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11396. detail::mmap m(path);
  11397. ASSERT_TRUE(m.is_open());
  11398. std::ifstream maps("/proc/self/maps");
  11399. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11400. std::istreambuf_iterator<char>());
  11401. EXPECT_EQ(std::string::npos, mappings.find(path));
  11402. }
  11403. #endif
  11404. TEST(KeepAliveTest, ReadTimeout) {
  11405. Server svr;
  11406. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11407. std::this_thread::sleep_for(std::chrono::seconds(2));
  11408. res.set_content("a", "text/plain");
  11409. });
  11410. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11411. res.set_content("b", "text/plain");
  11412. });
  11413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11414. auto se = detail::scope_exit([&] {
  11415. svr.stop();
  11416. listen_thread.join();
  11417. ASSERT_FALSE(svr.is_running());
  11418. });
  11419. svr.wait_until_ready();
  11420. Client cli("localhost", PORT);
  11421. cli.set_keep_alive(true);
  11422. cli.set_read_timeout(std::chrono::seconds(1));
  11423. auto resa = cli.Get("/a");
  11424. ASSERT_FALSE(resa);
  11425. EXPECT_EQ(Error::Read, resa.error());
  11426. auto resb = cli.Get("/b");
  11427. ASSERT_TRUE(resb);
  11428. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11429. EXPECT_EQ("b", resb->body);
  11430. }
  11431. TEST(KeepAliveTest, MaxCount) {
  11432. size_t keep_alive_max_count = 3;
  11433. Server svr;
  11434. svr.set_keep_alive_max_count(keep_alive_max_count);
  11435. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11436. res.set_content("Hello World!", "text/plain");
  11437. });
  11438. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11439. auto se = detail::scope_exit([&] {
  11440. svr.stop();
  11441. listen_thread.join();
  11442. ASSERT_FALSE(svr.is_running());
  11443. });
  11444. svr.wait_until_ready();
  11445. Client cli(HOST, PORT);
  11446. cli.set_keep_alive(true);
  11447. for (size_t i = 0; i < 5; i++) {
  11448. auto result = cli.Get("/hi");
  11449. ASSERT_TRUE(result);
  11450. EXPECT_EQ(StatusCode::OK_200, result->status);
  11451. if (i == keep_alive_max_count - 1) {
  11452. EXPECT_EQ("close", result->get_header_value("Connection"));
  11453. } else {
  11454. EXPECT_FALSE(result->has_header("Connection"));
  11455. }
  11456. }
  11457. }
  11458. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11459. // can pull the next one into the server's buffer. The server must serve it
  11460. // without waiting for the socket to become readable again. The keep-alive
  11461. // timeout outlasts the client's read timeout, so a request left waiting for it
  11462. // shows up as a missing response.
  11463. static void serve_pipelining_routes(Server &svr,
  11464. const std::function<void(int)> &client) {
  11465. svr.set_keep_alive_timeout(5);
  11466. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11467. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11468. });
  11469. svr.Post("/echo", [](const Request &req, Response &res) {
  11470. res.set_content("echo " + req.body, "text/plain");
  11471. });
  11472. auto port = svr.bind_to_any_port(HOST);
  11473. thread t = thread([&] { svr.listen_after_bind(); });
  11474. auto se = detail::scope_exit([&] {
  11475. svr.stop();
  11476. t.join();
  11477. });
  11478. svr.wait_until_ready();
  11479. client(port);
  11480. }
  11481. static std::string
  11482. send_pipelined_requests(const std::vector<std::string> &parts) {
  11483. Server svr;
  11484. std::string res;
  11485. serve_pipelining_routes(svr, [&](int port) {
  11486. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11487. });
  11488. return res;
  11489. }
  11490. static void expect_in_order(const std::string &res,
  11491. const std::vector<std::string> &bodies) {
  11492. size_t pos = 0;
  11493. for (const auto &body : bodies) {
  11494. pos = res.find(body, pos);
  11495. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11496. pos += body.size();
  11497. }
  11498. }
  11499. TEST(KeepAliveTest, PipelinedRequests) {
  11500. auto res = send_pipelined_requests(
  11501. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11502. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11503. "Content-Length: 4\r\n\r\nbody"
  11504. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11505. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11506. }
  11507. // The second request starts in the server's buffer and ends on the socket.
  11508. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11509. auto res =
  11510. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11511. "GET /hi/2 HTTP/1.1\r\nHo",
  11512. "st: localhost\r\nConnection: close\r\n\r\n"});
  11513. expect_in_order(res, {"hi 1", "hi 2"});
  11514. }
  11515. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11516. // CRLF after a body does not turn into a 400 for the next request.
  11517. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11518. auto res = send_pipelined_requests(
  11519. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11520. "Content-Length: 4\r\n\r\nbody\r\n"
  11521. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11522. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11523. expect_in_order(res, {"echo body", "hi 2"});
  11524. }
  11525. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11526. // must not be served as the next request.
  11527. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11528. auto res = send_pipelined_requests(
  11529. {"INVALID REQUEST LINE\r\n\r\n"
  11530. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11531. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11532. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11533. }
  11534. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11535. // Over TLS, the next request is held by the TLS library as already decrypted
  11536. // data rather than on the socket.
  11537. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11539. std::string res;
  11540. serve_pipelining_routes(svr, [&](int port) {
  11541. // One part, so all three requests arrive in one TLS record
  11542. EXPECT_TRUE(send_ssl_request_in_parts(
  11543. 2,
  11544. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11545. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11546. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11547. &res, port));
  11548. });
  11549. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11550. }
  11551. #endif
  11552. TEST(KeepAliveTest, Issue1041) {
  11553. Server svr;
  11554. svr.set_keep_alive_timeout(3);
  11555. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11556. res.set_content("Hello World!", "text/plain");
  11557. });
  11558. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11559. auto se = detail::scope_exit([&] {
  11560. svr.stop();
  11561. listen_thread.join();
  11562. ASSERT_FALSE(svr.is_running());
  11563. });
  11564. svr.wait_until_ready();
  11565. Client cli(HOST, PORT);
  11566. cli.set_keep_alive(true);
  11567. auto result = cli.Get("/hi");
  11568. ASSERT_TRUE(result);
  11569. EXPECT_EQ(StatusCode::OK_200, result->status);
  11570. std::this_thread::sleep_for(std::chrono::seconds(5));
  11571. result = cli.Get("/hi");
  11572. ASSERT_TRUE(result);
  11573. EXPECT_EQ(StatusCode::OK_200, result->status);
  11574. }
  11575. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11576. Server svr;
  11577. svr.set_keep_alive_max_count(0);
  11578. std::set<int> remote_ports;
  11579. svr.Get("/hi", [&](const Request &req, Response &res) {
  11580. remote_ports.insert(req.remote_port);
  11581. res.set_content("hi", "text/plain");
  11582. });
  11583. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. listen_thread.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. });
  11589. svr.wait_until_ready();
  11590. Client cli(HOST, PORT);
  11591. cli.set_keep_alive(true);
  11592. for (int i = 0; i < 3; i++) {
  11593. auto res = cli.Get("/hi");
  11594. ASSERT_TRUE(res);
  11595. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11596. }
  11597. // All three over one connection
  11598. EXPECT_EQ(1u, remote_ports.size());
  11599. }
  11600. // Forward declaration (see the base64_encode note).
  11601. namespace httplib {
  11602. namespace detail {
  11603. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11604. } // namespace detail
  11605. } // namespace httplib
  11606. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11607. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11608. #ifndef _WIN32
  11609. signal(SIGPIPE, SIG_IGN);
  11610. #endif
  11611. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11612. ASSERT_NE(INVALID_SOCKET, srv);
  11613. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11614. default_socket_options(srv);
  11615. sockaddr_in addr{};
  11616. addr.sin_family = AF_INET;
  11617. addr.sin_port = 0;
  11618. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11619. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11620. ASSERT_EQ(0, ::listen(srv, 2));
  11621. socklen_t addr_len = sizeof(addr);
  11622. ASSERT_EQ(0,
  11623. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11624. auto port = ntohs(addr.sin_port);
  11625. struct Peer {
  11626. socket_t sock = INVALID_SOCKET;
  11627. #ifdef CPPHTTPLIB_SSL_ENABLED
  11628. tls::session_t session = nullptr;
  11629. #endif
  11630. };
  11631. #ifdef CPPHTTPLIB_SSL_ENABLED
  11632. tls::ctx_t ctx = nullptr;
  11633. if (use_tls) {
  11634. ctx = tls::create_server_context();
  11635. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11636. nullptr);
  11637. }
  11638. auto ctx_se = detail::scope_exit([&] {
  11639. if (ctx) { tls::free_context(ctx); }
  11640. });
  11641. #endif
  11642. auto close_peer = [](Peer &peer) {
  11643. #ifdef CPPHTTPLIB_SSL_ENABLED
  11644. if (peer.session) { tls::free_session(peer.session); }
  11645. #endif
  11646. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11647. };
  11648. auto accept_peer = [&]() {
  11649. Peer peer;
  11650. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11651. peer.sock = ::accept(srv, nullptr, nullptr);
  11652. if (peer.sock == INVALID_SOCKET) { return peer; }
  11653. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11654. #ifdef CPPHTTPLIB_SSL_ENABLED
  11655. if (use_tls) {
  11656. peer.session = tls::create_session(ctx, peer.sock);
  11657. tls::TlsError err;
  11658. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11659. close_peer(peer);
  11660. return Peer();
  11661. }
  11662. }
  11663. #endif
  11664. return peer;
  11665. };
  11666. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11667. #ifdef CPPHTTPLIB_SSL_ENABLED
  11668. tls::TlsError err;
  11669. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11670. #endif
  11671. return detail::read_socket(peer.sock, buf, len, 0);
  11672. };
  11673. auto read_head = [&](const Peer &peer) {
  11674. std::string head;
  11675. char buf[1024];
  11676. while (head.find("\r\n\r\n") == std::string::npos) {
  11677. auto n = read_some(peer, buf, sizeof(buf));
  11678. if (n <= 0) { break; }
  11679. head.append(buf, static_cast<size_t>(n));
  11680. }
  11681. };
  11682. auto send_text = [](const Peer &peer, const std::string &text) {
  11683. #ifdef CPPHTTPLIB_SSL_ENABLED
  11684. tls::TlsError err;
  11685. if (peer.session) {
  11686. tls::write(peer.session, text.data(), text.size(), err);
  11687. return;
  11688. }
  11689. #endif
  11690. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11691. };
  11692. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11693. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11694. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11695. // Sent once the first response is read, so that it lands on an idle socket
  11696. std::promise<void> first_response_read;
  11697. auto first_response_read_future = first_response_read.get_future();
  11698. auto server_thread = std::thread([&] {
  11699. auto peer1 = accept_peer();
  11700. if (peer1.sock == INVALID_SOCKET) { return; }
  11701. read_head(peer1);
  11702. if (same_write) {
  11703. send_text(peer1, first + stray);
  11704. } else {
  11705. send_text(peer1, first);
  11706. first_response_read_future.wait_for(std::chrono::seconds(5));
  11707. send_text(peer1, stray);
  11708. }
  11709. // peer1 stays open, so only the unread data can tell the client
  11710. auto peer2 = accept_peer();
  11711. if (peer2.sock != INVALID_SOCKET) {
  11712. read_head(peer2);
  11713. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11714. "Connection: close\r\n\r\nsecond");
  11715. close_peer(peer2);
  11716. }
  11717. close_peer(peer1);
  11718. });
  11719. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11720. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11721. std::to_string(port));
  11722. #ifdef CPPHTTPLIB_SSL_ENABLED
  11723. cli.enable_server_certificate_verification(false);
  11724. #endif
  11725. cli.set_keep_alive(true);
  11726. cli.set_read_timeout(5, 0);
  11727. auto res = cli.Get("/1");
  11728. first_response_read.set_value();
  11729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11730. EXPECT_EQ("first", res->body);
  11731. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11732. res = cli.Get("/2");
  11733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11734. EXPECT_EQ(StatusCode::OK_200, res->status);
  11735. EXPECT_EQ("second", res->body);
  11736. }
  11737. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11738. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11739. }
  11740. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11741. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11742. }
  11743. #ifdef CPPHTTPLIB_SSL_ENABLED
  11744. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11745. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11746. }
  11747. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11748. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11749. }
  11750. #endif
  11751. TEST(KeepAliveTest, Issue1959) {
  11752. Server svr;
  11753. svr.set_keep_alive_timeout(5);
  11754. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11755. res.set_content("a", "text/plain");
  11756. });
  11757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11758. auto se = detail::scope_exit([&] {
  11759. if (!svr.is_running()) return;
  11760. svr.stop();
  11761. listen_thread.join();
  11762. ASSERT_FALSE(svr.is_running());
  11763. });
  11764. svr.wait_until_ready();
  11765. Client cli("localhost", PORT);
  11766. cli.set_keep_alive(true);
  11767. using namespace std::chrono;
  11768. auto start = steady_clock::now();
  11769. cli.Get("/a");
  11770. svr.stop();
  11771. listen_thread.join();
  11772. auto end = steady_clock::now();
  11773. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11774. EXPECT_LT(elapsed, 5000);
  11775. }
  11776. #ifdef CPPHTTPLIB_SSL_ENABLED
  11777. TEST(KeepAliveTest, SSLClientReconnection) {
  11778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11779. ASSERT_TRUE(svr.is_valid());
  11780. svr.set_keep_alive_timeout(1);
  11781. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11782. res.set_content("Hello World!", "text/plain");
  11783. });
  11784. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11785. auto se = detail::scope_exit([&] {
  11786. svr.stop();
  11787. listen_thread.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. });
  11790. svr.wait_until_ready();
  11791. SSLClient cli(HOST, PORT);
  11792. cli.enable_server_certificate_verification(false);
  11793. cli.set_keep_alive(true);
  11794. auto result = cli.Get("/hi");
  11795. ASSERT_TRUE(result);
  11796. EXPECT_EQ(StatusCode::OK_200, result->status);
  11797. result = cli.Get("/hi");
  11798. ASSERT_TRUE(result);
  11799. EXPECT_EQ(StatusCode::OK_200, result->status);
  11800. std::this_thread::sleep_for(std::chrono::seconds(2));
  11801. // Recoonect
  11802. result = cli.Get("/hi");
  11803. ASSERT_TRUE(result);
  11804. EXPECT_EQ(StatusCode::OK_200, result->status);
  11805. result = cli.Get("/hi");
  11806. ASSERT_TRUE(result);
  11807. EXPECT_EQ(StatusCode::OK_200, result->status);
  11808. }
  11809. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11811. ASSERT_TRUE(svr.is_valid());
  11812. svr.set_keep_alive_timeout(1);
  11813. std::string content = "reconnect";
  11814. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11815. res.set_content("Hello World!", "text/plain");
  11816. });
  11817. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. listen_thread.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. });
  11823. svr.wait_until_ready();
  11824. SSLClient cli(HOST, PORT);
  11825. cli.enable_server_certificate_verification(false);
  11826. cli.set_keep_alive(true);
  11827. auto result = cli.Post(
  11828. "/hi", content.size(),
  11829. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11830. sink.write(content.c_str(), content.size());
  11831. return true;
  11832. },
  11833. "text/plain");
  11834. ASSERT_TRUE(result);
  11835. EXPECT_EQ(200, result->status);
  11836. std::this_thread::sleep_for(std::chrono::seconds(2));
  11837. // Recoonect
  11838. result = cli.Post(
  11839. "/hi", content.size(),
  11840. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11841. sink.write(content.c_str(), content.size());
  11842. return true;
  11843. },
  11844. "text/plain");
  11845. ASSERT_TRUE(result);
  11846. EXPECT_EQ(200, result->status);
  11847. result = cli.Post(
  11848. "/hi", content.size(),
  11849. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11850. sink.write(content.c_str(), content.size());
  11851. return true;
  11852. },
  11853. "text/plain");
  11854. ASSERT_TRUE(result);
  11855. EXPECT_EQ(200, result->status);
  11856. }
  11857. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11858. using namespace httplib::tls;
  11859. {
  11860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11861. ASSERT_TRUE(svr.is_valid());
  11862. svr.Get("/sni", [&](const Request &req, Response &res) {
  11863. std::string expected = req.sni();
  11864. EXPECT_EQ(expected, req.get_param_value("expected"));
  11865. res.set_content("ok", "text/plain");
  11866. });
  11867. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11868. auto se = detail::scope_exit([&] {
  11869. svr.stop();
  11870. listen_thread.join();
  11871. ASSERT_FALSE(svr.is_running());
  11872. });
  11873. svr.wait_until_ready();
  11874. {
  11875. SSLClient cli("localhost", PORT);
  11876. cli.enable_server_certificate_verification(false);
  11877. auto res = cli.Get("/sni?expected=localhost");
  11878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11879. }
  11880. {
  11881. SSLClient cli("::1", PORT);
  11882. cli.enable_server_certificate_verification(false);
  11883. auto res = cli.Get("/sni?expected=");
  11884. // NOTE: This may fail if the server is listening on IPv4 only
  11885. // (e.g., when localhost resolves to 127.0.0.1 only)
  11886. if (res) {
  11887. EXPECT_EQ(StatusCode::OK_200, res->status);
  11888. } else {
  11889. EXPECT_EQ(Error::Connection, res.error());
  11890. }
  11891. }
  11892. }
  11893. }
  11894. // The SNI of a failed handshake does not reach the next connection that the
  11895. // same worker thread serves
  11896. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11898. ASSERT_TRUE(svr.is_valid());
  11899. svr.new_task_queue = [] { return new ThreadPool(1); };
  11900. svr.Get("/sni", [](const Request &req, Response &res) {
  11901. res.set_content(req.sni(), "text/plain");
  11902. });
  11903. auto port = svr.bind_to_any_port("127.0.0.1");
  11904. ASSERT_LT(0, port);
  11905. thread t = thread([&] { svr.listen_after_bind(); });
  11906. auto se = detail::scope_exit([&] {
  11907. svr.stop();
  11908. t.join();
  11909. ASSERT_FALSE(svr.is_running());
  11910. });
  11911. svr.wait_until_ready();
  11912. {
  11913. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11914. SSLClient cli("localhost", port);
  11915. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11916. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11917. auto res = cli.Get("/sni");
  11918. ASSERT_FALSE(res);
  11919. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11920. }
  11921. // An IP host sends no SNI (RFC 6066)
  11922. SSLClient cli("127.0.0.1", port);
  11923. cli.enable_server_certificate_verification(false);
  11924. auto res = cli.Get("/sni");
  11925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11926. EXPECT_EQ("", res->body);
  11927. }
  11928. #endif
  11929. TEST(ClientProblemDetectionTest, ContentProvider) {
  11930. Server svr;
  11931. size_t content_length = 1024 * 1024;
  11932. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11933. res.set_content_provider(
  11934. content_length, "text/plain",
  11935. [&](size_t offset, size_t length, DataSink &sink) {
  11936. auto out_len = std::min(length, static_cast<size_t>(1024));
  11937. std::string out(out_len, '@');
  11938. sink.write(out.data(), out_len);
  11939. return offset < 4096;
  11940. },
  11941. [](bool success) { ASSERT_FALSE(success); });
  11942. });
  11943. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11944. res.set_content_provider(
  11945. 0, "text/plain",
  11946. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11947. EXPECT_TRUE(false);
  11948. return true;
  11949. },
  11950. [](bool success) { ASSERT_FALSE(success); });
  11951. });
  11952. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. listen_thread.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. Client cli("localhost", PORT);
  11960. {
  11961. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11962. size_t /*data_length*/) { return false; });
  11963. ASSERT_FALSE(res);
  11964. }
  11965. {
  11966. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11967. size_t /*data_length*/) { return false; });
  11968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11969. }
  11970. }
  11971. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11972. // A provider that reports success without writing anything and without
  11973. // calling done() used to be handed the same offset and length again on every
  11974. // pass, so it spun for as long as the peer stayed connected.
  11975. Server svr;
  11976. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11977. res.set_content("ok", "text/plain");
  11978. });
  11979. auto port = svr.bind_to_any_port(HOST);
  11980. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11981. auto se = detail::scope_exit([&] {
  11982. svr.stop();
  11983. listen_thread.join();
  11984. ASSERT_FALSE(svr.is_running());
  11985. });
  11986. svr.wait_until_ready();
  11987. std::atomic<int> call_count{0};
  11988. Client cli(HOST, port);
  11989. auto res = cli.Post(
  11990. "/", 1024,
  11991. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11992. // Give up after enough passes to show the spin, so that losing the
  11993. // check below fails this test instead of hanging it.
  11994. return ++call_count < 100;
  11995. },
  11996. "text/plain");
  11997. ASSERT_FALSE(res);
  11998. EXPECT_EQ(Error::Write, res.error());
  11999. EXPECT_EQ(1, call_count.load());
  12000. }
  12001. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12002. // A writer only has to assign `write`. The other three used to be left as
  12003. // empty std::functions, so a provider calling one threw
  12004. // std::bad_function_call out of the thread running it and took the whole
  12005. // process down.
  12006. DataSink sink;
  12007. std::string written;
  12008. sink.write = [&](const char *data, size_t data_len) {
  12009. written.append(data, data_len);
  12010. return true;
  12011. };
  12012. EXPECT_TRUE(sink.is_writable());
  12013. sink.done();
  12014. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12015. EXPECT_TRUE(written.empty());
  12016. }
  12017. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12018. // A sink that cannot carry trailers still has to finish.
  12019. DataSink sink;
  12020. auto done_count = 0;
  12021. sink.done = [&]() { done_count++; };
  12022. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12023. EXPECT_EQ(1, done_count);
  12024. }
  12025. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12026. Server svr;
  12027. const std::string body(4096, 'x');
  12028. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12029. res.set_content_provider(body.size(), "text/plain",
  12030. [&](size_t offset, size_t length, DataSink &sink) {
  12031. sink.write(body.data() + offset, length);
  12032. sink.done();
  12033. return true;
  12034. });
  12035. });
  12036. auto port = svr.bind_to_any_port(HOST);
  12037. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12038. auto se = detail::scope_exit([&] {
  12039. svr.stop();
  12040. listen_thread.join();
  12041. ASSERT_FALSE(svr.is_running());
  12042. });
  12043. svr.wait_until_ready();
  12044. Client cli(HOST, port);
  12045. auto res = cli.Get("/");
  12046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12047. EXPECT_EQ(StatusCode::OK_200, res->status);
  12048. EXPECT_EQ(body, res->body);
  12049. }
  12050. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12051. Server svr;
  12052. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12053. res.set_content_provider(
  12054. 1024, "text/plain",
  12055. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12056. sink.write("hello", 5);
  12057. sink.done(); // short of the 1024 bytes the response promised
  12058. return true;
  12059. });
  12060. });
  12061. auto port = svr.bind_to_any_port(HOST);
  12062. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12063. auto se = detail::scope_exit([&] {
  12064. svr.stop();
  12065. listen_thread.join();
  12066. ASSERT_FALSE(svr.is_running());
  12067. });
  12068. svr.wait_until_ready();
  12069. Client cli(HOST, port);
  12070. cli.set_read_timeout(5, 0);
  12071. // The response is short of its Content-Length, so the client cannot read a
  12072. // complete body. What matters is that this returns at all: a no-op done()
  12073. // would leave the writer looping over a provider that never makes progress.
  12074. auto res = cli.Get("/");
  12075. EXPECT_FALSE(res);
  12076. }
  12077. // Read as the next response by a peer that sees it after a framed body.
  12078. static const std::string smuggled_response =
  12079. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12080. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12081. Server svr;
  12082. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12083. res.set_content_provider(
  12084. 5, "text/plain",
  12085. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12086. auto data = "AAAAA" + smuggled_response;
  12087. sink.write(data.data(), data.size());
  12088. return true;
  12089. });
  12090. });
  12091. thread t = thread([&] { svr.listen(HOST, PORT); });
  12092. auto se = detail::scope_exit([&] {
  12093. svr.stop();
  12094. t.join();
  12095. ASSERT_FALSE(svr.is_running());
  12096. });
  12097. svr.wait_until_ready();
  12098. std::string resp;
  12099. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12100. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12101. resp.clear();
  12102. ASSERT_TRUE(send_request(
  12103. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12104. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12105. }
  12106. TEST(NoContentTest, BodyIsNotSent) {
  12107. Server svr;
  12108. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12109. res.status = StatusCode::NoContent_204;
  12110. res.set_content(smuggled_response, "text/plain");
  12111. });
  12112. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12113. res.status = StatusCode::NotModified_304;
  12114. res.set_chunked_content_provider(
  12115. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12116. sink.write(smuggled_response.data(), smuggled_response.size());
  12117. sink.done();
  12118. return true;
  12119. });
  12120. });
  12121. thread t = thread([&] { svr.listen(HOST, PORT); });
  12122. auto se = detail::scope_exit([&] {
  12123. svr.stop();
  12124. t.join();
  12125. ASSERT_FALSE(svr.is_running());
  12126. });
  12127. svr.wait_until_ready();
  12128. for (auto path : {"/204", "/304"}) {
  12129. std::string resp;
  12130. ASSERT_TRUE(send_request(
  12131. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12132. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12133. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12134. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12135. }
  12136. }
  12137. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12138. Server svr;
  12139. std::atomic<bool> smuggled(false);
  12140. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12141. res.set_content("ok", "text/plain");
  12142. });
  12143. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12144. smuggled = true;
  12145. });
  12146. auto port = svr.bind_to_any_port(HOST);
  12147. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12148. auto se = detail::scope_exit([&] {
  12149. svr.stop();
  12150. listen_thread.join();
  12151. ASSERT_FALSE(svr.is_running());
  12152. });
  12153. svr.wait_until_ready();
  12154. // What follows the body would be read as the next request.
  12155. Client cli(HOST, port);
  12156. auto res = cli.Post(
  12157. "/", 5,
  12158. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12159. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12160. sink.write(data.data(), data.size());
  12161. return true;
  12162. },
  12163. "text/plain");
  12164. ASSERT_FALSE(res);
  12165. EXPECT_EQ(Error::Write, res.error());
  12166. EXPECT_FALSE(smuggled);
  12167. }
  12168. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12169. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12170. // The compressed path builds the whole body before connecting, so this
  12171. // fails client-side and never reaches a server.
  12172. Client cli(HOST, PORT);
  12173. cli.set_compress(true);
  12174. auto res = cli.Post(
  12175. "/", 1024,
  12176. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12177. sink.write("hello", 5);
  12178. sink.done(); // short of the 1024 bytes the request announced
  12179. return true;
  12180. },
  12181. "text/plain");
  12182. ASSERT_FALSE(res);
  12183. EXPECT_EQ(Error::Write, res.error());
  12184. }
  12185. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12186. Server svr;
  12187. std::string received;
  12188. size_t content_length_count = 0;
  12189. bool has_transfer_encoding = true;
  12190. svr.Post("/echo", [&](const Request &req, Response &res) {
  12191. received = req.body;
  12192. content_length_count = req.get_header_value_count("Content-Length");
  12193. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12194. res.set_content("ok", "text/plain");
  12195. });
  12196. svr.Get("/next", [](const Request &, Response &res) {
  12197. res.set_content("next", "text/plain");
  12198. });
  12199. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12200. auto se = detail::scope_exit([&] {
  12201. svr.stop();
  12202. listen_thread.join();
  12203. ASSERT_FALSE(svr.is_running());
  12204. });
  12205. svr.wait_until_ready();
  12206. Client cli(HOST, PORT);
  12207. cli.set_keep_alive(true);
  12208. cli.set_compress(true);
  12209. const std::string body = "hello world";
  12210. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12211. auto res = cli.Post("/echo", headers, body, "text/plain");
  12212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12213. EXPECT_EQ(StatusCode::OK_200, res->status);
  12214. EXPECT_EQ(body, received);
  12215. EXPECT_EQ(1u, content_length_count);
  12216. EXPECT_FALSE(has_transfer_encoding);
  12217. // The rest of a truncated body would be read as this request
  12218. auto res2 = cli.Get("/next");
  12219. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12220. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12221. EXPECT_EQ("next", res2->body);
  12222. }
  12223. #endif
  12224. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12225. Server svr;
  12226. std::string received;
  12227. size_t content_length_count = 1;
  12228. bool has_transfer_encoding = false;
  12229. svr.Post("/echo", [&](const Request &req, Response &res) {
  12230. received = req.body;
  12231. content_length_count = req.get_header_value_count("Content-Length");
  12232. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12233. res.set_content("ok", "text/plain");
  12234. });
  12235. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. listen_thread.join();
  12239. ASSERT_FALSE(svr.is_running());
  12240. });
  12241. svr.wait_until_ready();
  12242. Client cli(HOST, PORT);
  12243. cli.set_keep_alive(true);
  12244. const std::string body = "hello world";
  12245. Headers headers = {{"Content-Length", "5"}};
  12246. auto res = cli.Post(
  12247. "/echo", headers,
  12248. [&](size_t /*offset*/, DataSink &sink) {
  12249. sink.write(body.data(), body.size());
  12250. sink.done();
  12251. return true;
  12252. },
  12253. "text/plain");
  12254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12255. EXPECT_EQ(StatusCode::OK_200, res->status);
  12256. EXPECT_EQ(body, received);
  12257. EXPECT_EQ(0u, content_length_count);
  12258. EXPECT_TRUE(has_transfer_encoding);
  12259. }
  12260. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12261. Server svr;
  12262. svr.set_error_handler([](Request const &, Response &res) -> void {
  12263. res.set_chunked_content_provider(
  12264. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12265. sink.os << "hello";
  12266. sink.os << "world";
  12267. sink.done();
  12268. return true;
  12269. });
  12270. });
  12271. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12272. auto se = detail::scope_exit([&] {
  12273. svr.stop();
  12274. listen_thread.join();
  12275. ASSERT_FALSE(svr.is_running());
  12276. });
  12277. svr.wait_until_ready();
  12278. Client cli("localhost", PORT);
  12279. auto res = cli.Get("/");
  12280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12282. EXPECT_EQ("helloworld", res->body);
  12283. }
  12284. // A body set after a content provider must replace it, not be sent through it.
  12285. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12286. Server svr;
  12287. svr.set_mount_point("/", "./www");
  12288. svr.set_file_request_handler([](const Request &req, Response &res) {
  12289. if (req.path == "/dir/test.html") {
  12290. res.status = StatusCode::Forbidden_403;
  12291. res.set_content(std::string(5000, 'D'), "text/plain");
  12292. } else if (req.path == "/file") {
  12293. res.status = StatusCode::Forbidden_403;
  12294. res.body = "Denied";
  12295. }
  12296. });
  12297. auto port = svr.bind_to_any_port(HOST);
  12298. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12299. auto se = detail::scope_exit([&] {
  12300. svr.stop();
  12301. t.join();
  12302. ASSERT_FALSE(svr.is_running());
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, port);
  12306. {
  12307. auto res = cli.Get("/dir/test.html");
  12308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12309. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12310. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12311. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12312. }
  12313. {
  12314. auto res = cli.Get("/file");
  12315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12316. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12317. EXPECT_EQ("Denied", res->body);
  12318. }
  12319. {
  12320. auto res = cli.Get("/dir/index.html");
  12321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12322. EXPECT_EQ(StatusCode::OK_200, res->status);
  12323. EXPECT_EQ(0U, res->body.find("<html>"));
  12324. }
  12325. }
  12326. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12327. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12328. Server svr;
  12329. std::vector<bool> released;
  12330. std::mutex released_mutex;
  12331. auto releaser = [&](bool success) {
  12332. std::lock_guard<std::mutex> guard(released_mutex);
  12333. released.push_back(success);
  12334. };
  12335. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12336. return sink.write(&"hello"[offset], length);
  12337. };
  12338. svr.Get("/sized", [&](const Request &, Response &res) {
  12339. res.status = StatusCode::NotFound_404;
  12340. res.set_content_provider(5, "text/plain", provider, releaser);
  12341. });
  12342. svr.Get("/chunked", [&](const Request &, Response &res) {
  12343. res.status = StatusCode::ServiceUnavailable_503;
  12344. res.set_chunked_content_provider(
  12345. "text/plain",
  12346. [](size_t, DataSink &sink) {
  12347. sink.os << "chunk";
  12348. sink.done();
  12349. return true;
  12350. },
  12351. releaser);
  12352. });
  12353. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12354. res.set_content_provider(5, "text/plain", provider, releaser);
  12355. throw std::runtime_error("after the provider");
  12356. });
  12357. svr.set_error_handler([](const Request &req, Response &res) {
  12358. // Leave the exception handler's content to it.
  12359. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12360. res.set_content(std::string(1000, 'E'), "text/html");
  12361. return Server::HandlerResponse::Handled;
  12362. });
  12363. svr.set_exception_handler(
  12364. [](const Request &, Response &res, std::exception_ptr) {
  12365. res.status = StatusCode::InternalServerError_500;
  12366. res.set_content(std::string(1000, 'X'), "text/html");
  12367. });
  12368. auto port = svr.bind_to_any_port(HOST);
  12369. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12370. auto se = detail::scope_exit([&] {
  12371. svr.stop();
  12372. t.join();
  12373. ASSERT_FALSE(svr.is_running());
  12374. });
  12375. svr.wait_until_ready();
  12376. Client cli(HOST, port);
  12377. {
  12378. auto res = cli.Get("/sized");
  12379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12380. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12381. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12382. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12383. }
  12384. {
  12385. auto res = cli.Get("/chunked");
  12386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12387. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12388. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12389. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12390. }
  12391. {
  12392. auto res = cli.Get("/throw");
  12393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12394. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12395. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12396. }
  12397. std::lock_guard<std::mutex> guard(released_mutex);
  12398. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12399. }
  12400. #endif
  12401. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12402. Server svr;
  12403. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12404. return sink.write(&"abc"[offset], length);
  12405. };
  12406. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12407. res.set_file_content("./www/dir/test.html");
  12408. res.set_content("body", "text/plain");
  12409. });
  12410. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12411. res.set_content(std::string(100, 'B'), "text/plain");
  12412. res.set_file_content("./www/dir/test.html");
  12413. });
  12414. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12415. res.set_content(std::string(100, 'B'), "text/plain");
  12416. res.set_content_provider(3, "text/x-provider", abc);
  12417. });
  12418. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12419. res.set_content_provider(3, "text/x-provider", abc);
  12420. res.set_content(std::string(100, 'B'), "text/plain");
  12421. });
  12422. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12423. res.set_content_provider(3, "text/x-provider", abc);
  12424. res.set_file_content("./www/dir/test.html", "text/x-file");
  12425. });
  12426. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12427. res.set_file_content("./www/dir/test.html");
  12428. res.set_header("Content-Type", "text/x-handler");
  12429. });
  12430. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12431. res.set_content_provider(3, "text/plain", abc);
  12432. res.body = "direct";
  12433. });
  12434. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12435. res.set_file_content("./www/dir/test.html");
  12436. res.body = "direct";
  12437. });
  12438. auto port = svr.bind_to_any_port(HOST);
  12439. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. t.join();
  12443. ASSERT_FALSE(svr.is_running());
  12444. });
  12445. svr.wait_until_ready();
  12446. Client cli(HOST, port);
  12447. auto expect_body = [&](const char *path, const std::string &body,
  12448. const std::string &type) {
  12449. // Uncompressed, so Content-Length can be compared with the body.
  12450. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12451. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12453. EXPECT_EQ(body, res->body) << path;
  12454. EXPECT_EQ(std::to_string(body.size()),
  12455. res->get_header_value("Content-Length"))
  12456. << path;
  12457. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12458. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12459. };
  12460. expect_body("/file-then-body", "body", "text/plain");
  12461. expect_body("/body-then-file", "test.html", "text/html");
  12462. expect_body("/body-then-provider", "abc", "text/x-provider");
  12463. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12464. expect_body("/provider-then-file", "test.html", "text/x-file");
  12465. expect_body("/file-then-header", "test.html", "text/x-handler");
  12466. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12467. expect_body("/file-then-direct-body", "direct", "text/plain");
  12468. // Ranges are checked against the body, not the dropped provider.
  12469. {
  12470. auto res = cli.Get("/provider-then-direct-body",
  12471. Headers{{make_range_header({{1, 2}})}});
  12472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12473. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12474. EXPECT_EQ("ir", res->body);
  12475. }
  12476. {
  12477. auto res = cli.Get("/file-then-direct-body",
  12478. Headers{{make_range_header({{7, 8}})}});
  12479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12480. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12481. }
  12482. }
  12483. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12484. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12485. const char *path = "./truncated_while_served.txt";
  12486. const size_t size = 32 * 1024 * 1024;
  12487. {
  12488. std::ofstream f(path, std::ios::binary);
  12489. f << std::string(size, 'x');
  12490. }
  12491. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12492. // Over TLS, where the bytes are encrypted in this process rather than
  12493. // copied by send().
  12494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12495. svr.Get("/file", [&](const Request &, Response &res) {
  12496. res.set_file_content(path, "text/plain");
  12497. });
  12498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12499. auto se = detail::scope_exit([&] {
  12500. svr.stop();
  12501. thread.join();
  12502. ASSERT_FALSE(svr.is_running());
  12503. });
  12504. svr.wait_until_ready();
  12505. // The file shrinks once the first bytes are in, as a rewrite in place
  12506. // would, and reading the mapping past its new end used to raise SIGBUS.
  12507. SSLClient cli(HOST, PORT);
  12508. cli.enable_server_certificate_verification(false);
  12509. size_t received = 0;
  12510. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12511. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12512. received += len;
  12513. return true;
  12514. });
  12515. EXPECT_FALSE(res);
  12516. EXPECT_LT(received, size);
  12517. }
  12518. #endif
  12519. // Forward declaration (see the base64_encode note).
  12520. namespace httplib {
  12521. namespace detail {
  12522. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12523. const std::string &content_type,
  12524. EncodingType encoding);
  12525. } // namespace detail
  12526. } // namespace httplib
  12527. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12528. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12529. ASSERT_TRUE(mm->is_open());
  12530. Response res;
  12531. detail::set_file_content_provider(res, mm, "text/html",
  12532. detail::EncodingType::None);
  12533. std::string out;
  12534. DataSink sink;
  12535. sink.write = [&](const char *d, size_t l) {
  12536. out.append(d, l);
  12537. return true;
  12538. };
  12539. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12540. EXPECT_EQ("test.html", out);
  12541. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12542. EXPECT_EQ("test.html", out);
  12543. }
  12544. TEST(LongPollingTest, ClientCloseDetection) {
  12545. Server svr;
  12546. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12547. res.set_chunked_content_provider(
  12548. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12549. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12550. sink.os << "hello";
  12551. auto count = 10;
  12552. while (count > 0 && sink.is_writable()) {
  12553. this_thread::sleep_for(chrono::milliseconds(10));
  12554. count--;
  12555. }
  12556. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12557. return true;
  12558. });
  12559. });
  12560. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12561. auto se = detail::scope_exit([&] {
  12562. svr.stop();
  12563. listen_thread.join();
  12564. ASSERT_FALSE(svr.is_running());
  12565. });
  12566. svr.wait_until_ready();
  12567. Client cli("localhost", PORT);
  12568. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12569. EXPECT_EQ("hello", string(data, data_length));
  12570. return false; // close the socket immediately.
  12571. });
  12572. ASSERT_FALSE(res);
  12573. }
  12574. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12575. Server svr;
  12576. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12577. res.set_chunked_content_provider(
  12578. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12579. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12580. sink.os << "hello";
  12581. EXPECT_TRUE(sink.os.good());
  12582. // Wait for the client to close the connection
  12583. auto count = 10;
  12584. while (count > 0 && sink.is_writable()) {
  12585. this_thread::sleep_for(chrono::milliseconds(10));
  12586. count--;
  12587. }
  12588. // After client disconnect, write repeatedly until the socket
  12589. // write actually fails (small writes may be absorbed by the
  12590. // kernel buffer)
  12591. std::string chunk(1024, 'x');
  12592. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12593. sink.os << chunk;
  12594. }
  12595. EXPECT_TRUE(sink.os.fail());
  12596. return true;
  12597. });
  12598. });
  12599. auto port = svr.bind_to_any_port("localhost");
  12600. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. listen_thread.join();
  12604. ASSERT_FALSE(svr.is_running());
  12605. });
  12606. svr.wait_until_ready();
  12607. Client cli("localhost", port);
  12608. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12609. EXPECT_EQ("hello", string(data, data_length));
  12610. return false; // close the socket immediately.
  12611. });
  12612. ASSERT_FALSE(res);
  12613. }
  12614. TEST(GetWithParametersTest, GetWithParameters) {
  12615. Server svr;
  12616. svr.Get("/", [&](const Request &req, Response &) {
  12617. EXPECT_EQ("world", req.get_param_value("hello"));
  12618. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12619. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12620. });
  12621. svr.Get("/params", [&](const Request &req, Response &) {
  12622. EXPECT_EQ("world", req.get_param_value("hello"));
  12623. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12624. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12625. });
  12626. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12627. EXPECT_EQ("resource-id", req.matches[1]);
  12628. EXPECT_EQ("foo", req.get_param_value("param1"));
  12629. EXPECT_EQ("bar", req.get_param_value("param2"));
  12630. });
  12631. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12632. EXPECT_EQ("user-id", req.path_params.at("id"));
  12633. EXPECT_EQ("foo", req.get_param_value("param1"));
  12634. EXPECT_EQ("bar", req.get_param_value("param2"));
  12635. });
  12636. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12637. auto se = detail::scope_exit([&] {
  12638. svr.stop();
  12639. listen_thread.join();
  12640. ASSERT_FALSE(svr.is_running());
  12641. });
  12642. svr.wait_until_ready();
  12643. {
  12644. Client cli(HOST, PORT);
  12645. Params params;
  12646. params.emplace("hello", "world");
  12647. params.emplace("hello2", "world2");
  12648. params.emplace("hello3", "world3");
  12649. auto res = cli.Get("/", params, Headers{});
  12650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12651. EXPECT_EQ(StatusCode::OK_200, res->status);
  12652. }
  12653. {
  12654. Client cli(HOST, PORT);
  12655. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12657. EXPECT_EQ(StatusCode::OK_200, res->status);
  12658. }
  12659. {
  12660. Client cli(HOST, PORT);
  12661. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12663. EXPECT_EQ(StatusCode::OK_200, res->status);
  12664. }
  12665. {
  12666. Client cli(HOST, PORT);
  12667. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12669. EXPECT_EQ(StatusCode::OK_200, res->status);
  12670. }
  12671. }
  12672. TEST(GetWithParametersTest, GetWithParameters2) {
  12673. Server svr;
  12674. svr.Get("/", [&](const Request &req, Response &res) {
  12675. auto text = req.get_param_value("hello");
  12676. res.set_content(text, "text/plain");
  12677. });
  12678. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12679. auto se = detail::scope_exit([&] {
  12680. svr.stop();
  12681. listen_thread.join();
  12682. ASSERT_FALSE(svr.is_running());
  12683. });
  12684. svr.wait_until_ready();
  12685. Client cli("localhost", PORT);
  12686. Params params;
  12687. params.emplace("hello", "world");
  12688. std::string body;
  12689. auto res = cli.Get("/", params, Headers{},
  12690. [&](const char *data, size_t data_length) {
  12691. body.append(data, data_length);
  12692. return true;
  12693. });
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. EXPECT_EQ(StatusCode::OK_200, res->status);
  12696. EXPECT_EQ("world", body);
  12697. }
  12698. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12699. Server svr;
  12700. svr.Get("/search", [&](const Request &req, Response &res) {
  12701. auto q = req.get_param_value("q");
  12702. res.set_content(q, "text/plain");
  12703. });
  12704. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12705. auto se = detail::scope_exit([&] {
  12706. svr.stop();
  12707. listen_thread.join();
  12708. ASSERT_FALSE(svr.is_running());
  12709. });
  12710. svr.wait_until_ready();
  12711. Client cli("localhost", PORT);
  12712. // Verify that Get(path, params) works without requiring Headers argument
  12713. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12715. EXPECT_EQ(StatusCode::OK_200, res->status);
  12716. EXPECT_EQ("cpp-httplib", res->body);
  12717. }
  12718. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12719. auto host = "httpbingo.org";
  12720. auto path = std::string{"/range/32"};
  12721. #ifdef CPPHTTPLIB_SSL_ENABLED
  12722. SSLClient cli(host);
  12723. #else
  12724. Client cli(host);
  12725. #endif
  12726. cli.set_default_headers({make_range_header({{1, 10}})});
  12727. cli.set_connection_timeout(5);
  12728. {
  12729. auto res = cli.Get(path);
  12730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12731. EXPECT_EQ("bcdefghijk", res->body);
  12732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12733. }
  12734. {
  12735. auto res = cli.Get(path);
  12736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12737. EXPECT_EQ("bcdefghijk", res->body);
  12738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12739. }
  12740. }
  12741. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12742. Server svr;
  12743. svr.set_default_headers({{"Hello", "World"}});
  12744. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12745. res.set_content("ok", "text/plain");
  12746. });
  12747. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12748. auto se = detail::scope_exit([&] {
  12749. svr.stop();
  12750. listen_thread.join();
  12751. ASSERT_FALSE(svr.is_running());
  12752. });
  12753. svr.wait_until_ready();
  12754. Client cli("localhost", PORT);
  12755. auto res = cli.Get("/");
  12756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12757. EXPECT_EQ(StatusCode::OK_200, res->status);
  12758. EXPECT_EQ("ok", res->body);
  12759. EXPECT_EQ("World", res->get_header_value("Hello"));
  12760. }
  12761. #ifdef CPPHTTPLIB_SSL_ENABLED
  12762. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12764. ASSERT_TRUE(svr.is_valid());
  12765. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12766. std::this_thread::sleep_for(std::chrono::seconds(2));
  12767. res.set_content("a", "text/plain");
  12768. });
  12769. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12770. res.set_content("b", "text/plain");
  12771. });
  12772. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12773. auto se = detail::scope_exit([&] {
  12774. svr.stop();
  12775. listen_thread.join();
  12776. ASSERT_FALSE(svr.is_running());
  12777. });
  12778. svr.wait_until_ready();
  12779. SSLClient cli("localhost", PORT);
  12780. cli.enable_server_certificate_verification(false);
  12781. cli.set_keep_alive(true);
  12782. cli.set_read_timeout(std::chrono::seconds(1));
  12783. auto resa = cli.Get("/a");
  12784. ASSERT_TRUE(!resa);
  12785. EXPECT_EQ(Error::Read, resa.error());
  12786. auto resb = cli.Get("/b");
  12787. ASSERT_TRUE(resb);
  12788. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12789. EXPECT_EQ("b", resb->body);
  12790. }
  12791. // Closing an idle keep-alive connection sends close_notify and returns. The
  12792. // server must not wait for the client's close_notify: an idle client never
  12793. // sends one, so the worker would be held until the read timeout expires, and
  12794. // stop() would wait for it.
  12795. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12797. ASSERT_TRUE(svr.is_valid());
  12798. svr.set_keep_alive_timeout(1);
  12799. svr.set_read_timeout(10, 0);
  12800. svr.Get("/", [](const Request &, Response &res) {
  12801. res.set_content("ok", "text/plain");
  12802. });
  12803. auto port = svr.bind_to_any_port(HOST);
  12804. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12805. auto se = detail::scope_exit([&] {
  12806. if (listen_thread.joinable()) {
  12807. svr.stop();
  12808. listen_thread.join();
  12809. }
  12810. });
  12811. svr.wait_until_ready();
  12812. SSLClient cli(HOST, port);
  12813. cli.enable_server_certificate_verification(false);
  12814. cli.set_keep_alive(true);
  12815. auto res = cli.Get("/");
  12816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12817. EXPECT_EQ(StatusCode::OK_200, res->status);
  12818. // Stay idle past the keep-alive timeout so the server closes the connection.
  12819. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12820. auto start = std::chrono::steady_clock::now();
  12821. svr.stop();
  12822. listen_thread.join();
  12823. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12824. std::chrono::steady_clock::now() - start)
  12825. .count();
  12826. EXPECT_LT(elapsed, 3000);
  12827. }
  12828. #endif
  12829. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12830. protected:
  12831. ServerTestWithAI_PASSIVE()
  12832. : cli_(HOST, PORT)
  12833. #ifdef CPPHTTPLIB_SSL_ENABLED
  12834. ,
  12835. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12836. #endif
  12837. {
  12838. #ifdef CPPHTTPLIB_SSL_ENABLED
  12839. cli_.enable_server_certificate_verification(false);
  12840. #endif
  12841. }
  12842. virtual void SetUp() {
  12843. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12844. res.set_content("Hello World!", "text/plain");
  12845. });
  12846. t_ = thread(
  12847. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12848. svr_.wait_until_ready();
  12849. }
  12850. virtual void TearDown() {
  12851. svr_.stop();
  12852. t_.join();
  12853. }
  12854. #ifdef CPPHTTPLIB_SSL_ENABLED
  12855. SSLClient cli_;
  12856. SSLServer svr_;
  12857. #else
  12858. Client cli_;
  12859. Server svr_;
  12860. #endif
  12861. thread t_;
  12862. };
  12863. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12864. auto res = cli_.Get("/hi");
  12865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12866. EXPECT_EQ(StatusCode::OK_200, res->status);
  12867. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12868. EXPECT_EQ("Hello World!", res->body);
  12869. }
  12870. class ServerUpDownTest : public ::testing::Test {
  12871. protected:
  12872. ServerUpDownTest() : cli_(HOST, PORT) {}
  12873. virtual void SetUp() {
  12874. t_ = thread([&]() {
  12875. svr_.bind_to_any_port(HOST);
  12876. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12877. ASSERT_TRUE(svr_.listen_after_bind());
  12878. });
  12879. svr_.wait_until_ready();
  12880. }
  12881. virtual void TearDown() {
  12882. svr_.stop();
  12883. t_.join();
  12884. }
  12885. Client cli_;
  12886. Server svr_;
  12887. thread t_;
  12888. };
  12889. TEST_F(ServerUpDownTest, QuickStartStop) {
  12890. // Should not crash, especially when run with
  12891. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12892. }
  12893. class PayloadMaxLengthTest : public ::testing::Test {
  12894. protected:
  12895. PayloadMaxLengthTest()
  12896. : cli_(HOST, PORT)
  12897. #ifdef CPPHTTPLIB_SSL_ENABLED
  12898. ,
  12899. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12900. #endif
  12901. {
  12902. #ifdef CPPHTTPLIB_SSL_ENABLED
  12903. cli_.enable_server_certificate_verification(false);
  12904. #endif
  12905. }
  12906. virtual void SetUp() {
  12907. svr_.set_payload_max_length(8);
  12908. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12909. res.set_content("test", "text/plain");
  12910. });
  12911. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12912. svr_.wait_until_ready();
  12913. }
  12914. virtual void TearDown() {
  12915. svr_.stop();
  12916. t_.join();
  12917. }
  12918. #ifdef CPPHTTPLIB_SSL_ENABLED
  12919. SSLClient cli_;
  12920. SSLServer svr_;
  12921. #else
  12922. Client cli_;
  12923. Server svr_;
  12924. #endif
  12925. thread t_;
  12926. };
  12927. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12928. auto res = cli_.Post("/test", "123456789", "text/plain");
  12929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12930. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12931. res = cli_.Post("/test", "12345678", "text/plain");
  12932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12933. EXPECT_EQ(StatusCode::OK_200, res->status);
  12934. }
  12935. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12936. // Test chunked encoding with payload exceeding the 8-byte limit
  12937. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12938. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12940. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12941. }
  12942. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12943. // Test chunked encoding with payload within the 8-byte limit
  12944. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12945. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12947. EXPECT_EQ(StatusCode::OK_200, res->status);
  12948. }
  12949. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12950. // Test using send_request to send chunked data exceeding payload limit
  12951. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12952. "Host: " +
  12953. std::string(HOST) + ":" + std::to_string(PORT) +
  12954. "\r\n"
  12955. "Transfer-Encoding: chunked\r\n"
  12956. "Connection: close\r\n"
  12957. "\r\n"
  12958. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12959. "0123456789\r\n"
  12960. "0\r\n" // End chunk
  12961. "\r\n";
  12962. std::string response;
  12963. bool result = send_request(1, chunked_request, &response);
  12964. if (!result) {
  12965. // If send_request fails, it might be because the server closed the
  12966. // connection due to payload limit enforcement, which is acceptable
  12967. SUCCEED()
  12968. << "Server rejected oversized chunked request (connection closed)";
  12969. } else {
  12970. // If we got a response, check if it's an error response or connection was
  12971. // closed early Short response length indicates connection was closed due to
  12972. // payload limit
  12973. if (response.length() <= 10) {
  12974. SUCCEED() << "Server closed connection for oversized chunked request";
  12975. } else {
  12976. // Check for error status codes
  12977. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12978. response.find("Payload Too Large") != std::string::npos ||
  12979. response.find("400") != std::string::npos);
  12980. }
  12981. }
  12982. }
  12983. class LargePayloadMaxLengthTest : public ::testing::Test {
  12984. protected:
  12985. LargePayloadMaxLengthTest()
  12986. : cli_(HOST, PORT)
  12987. #ifdef CPPHTTPLIB_SSL_ENABLED
  12988. ,
  12989. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12990. #endif
  12991. {
  12992. #ifdef CPPHTTPLIB_SSL_ENABLED
  12993. cli_.enable_server_certificate_verification(false);
  12994. #endif
  12995. }
  12996. virtual void SetUp() {
  12997. // Set 10MB payload limit
  12998. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12999. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13000. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13001. res.set_content("Large payload test", "text/plain");
  13002. });
  13003. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13004. svr_.wait_until_ready();
  13005. }
  13006. virtual void TearDown() {
  13007. svr_.stop();
  13008. t_.join();
  13009. }
  13010. #ifdef CPPHTTPLIB_SSL_ENABLED
  13011. SSLClient cli_;
  13012. SSLServer svr_;
  13013. #else
  13014. Client cli_;
  13015. Server svr_;
  13016. #endif
  13017. thread t_;
  13018. };
  13019. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13020. // Test chunked encoding with payload within 10MB limit
  13021. std::string medium_payload(5 * 1024 * 1024,
  13022. 'A'); // 5MB payload, within 10MB limit
  13023. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13025. EXPECT_EQ(StatusCode::OK_200, res->status);
  13026. }
  13027. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13028. // Test chunked encoding with payload exceeding 10MB limit
  13029. std::string large_payload(12 * 1024 * 1024,
  13030. 'B'); // 12MB payload, exceeds 10MB limit
  13031. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13032. // Server may either return 413 or close the connection
  13033. if (res) {
  13034. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13035. } else {
  13036. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13037. }
  13038. }
  13039. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13040. Server svr;
  13041. svr.Get("/", [](const Request &, Response &res) {
  13042. // Claims the most the client accepts, far more than it sends, then drops
  13043. // the connection.
  13044. res.set_content_provider(std::string().max_size(), "text/plain",
  13045. [](size_t, size_t, DataSink &sink) {
  13046. sink.write("abc", 3);
  13047. return false;
  13048. });
  13049. });
  13050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13051. auto se = detail::scope_exit([&] {
  13052. svr.stop();
  13053. thread.join();
  13054. ASSERT_FALSE(svr.is_running());
  13055. });
  13056. svr.wait_until_ready();
  13057. Client cli(HOST, PORT);
  13058. cli.set_payload_max_length(0);
  13059. EXPECT_FALSE(cli.Get("/"));
  13060. }
  13061. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13062. // Stream API does, not as a plain read failure
  13063. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13064. Server svr;
  13065. svr.Get("/big", [](const Request &, Response &res) {
  13066. res.set_content(std::string(100000, 'b'), "text/plain");
  13067. });
  13068. auto port = svr.bind_to_any_port(HOST);
  13069. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13070. auto se = detail::scope_exit([&] {
  13071. svr.stop();
  13072. thread.join();
  13073. });
  13074. svr.wait_until_ready();
  13075. Client cli(HOST, port);
  13076. cli.set_payload_max_length(1000);
  13077. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13078. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13079. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13080. [](const char *, size_t) { return true; });
  13081. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13082. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13083. // Small on the wire, over the limit once decompressed
  13084. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13085. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13086. #endif
  13087. }
  13088. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13089. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13090. // path.
  13091. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13092. Server svr;
  13093. const size_t LIMIT = 64 * 1024; // 64KB
  13094. svr.set_payload_max_length(LIMIT);
  13095. size_t total = 0;
  13096. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13097. const ContentReader &content_reader) {
  13098. content_reader([&](const char * /*data*/, size_t len) {
  13099. total += len;
  13100. return true;
  13101. });
  13102. res.status = 200;
  13103. res.set_content("stream_ok", "text/plain");
  13104. });
  13105. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13106. auto se = detail::scope_exit([&] {
  13107. svr.stop();
  13108. thread.join();
  13109. ASSERT_FALSE(svr.is_running());
  13110. });
  13111. svr.wait_until_ready();
  13112. // Prepare 256KB raw data and gzip-compress it
  13113. std::string raw(256 * 1024, 'A');
  13114. std::string gz;
  13115. {
  13116. z_stream zs{};
  13117. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13118. Z_DEFAULT_STRATEGY);
  13119. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13120. zs.avail_in = static_cast<uInt>(raw.size());
  13121. char outbuf[4096];
  13122. int ret;
  13123. do {
  13124. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13125. zs.avail_out = sizeof(outbuf);
  13126. ret = deflate(&zs, Z_FINISH);
  13127. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13128. } while (ret != Z_STREAM_END);
  13129. deflateEnd(&zs);
  13130. }
  13131. Client cli(HOST, PORT);
  13132. cli.set_connection_timeout(std::chrono::seconds(5));
  13133. Headers headers = {{"Content-Encoding", "gzip"}};
  13134. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13135. "application/octet-stream");
  13136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13137. // Server must reject oversized decompressed payloads with 413.
  13138. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13139. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13140. EXPECT_LE(total, LIMIT);
  13141. }
  13142. #endif
  13143. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13144. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13145. // the payload must be passed through untouched instead of being rejected.
  13146. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13147. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13148. Server svr;
  13149. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13150. res.set_content(body, "image/jpeg");
  13151. res.set_header("Content-Encoding", "UTF-8");
  13152. });
  13153. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13154. res.set_content(body, "image/jpeg");
  13155. res.set_header("Content-Encoding", "identity");
  13156. });
  13157. svr.Post("/echo", [](const Request &req, Response &res) {
  13158. res.set_content(req.body, "image/jpeg");
  13159. });
  13160. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13161. auto se = detail::scope_exit([&] {
  13162. svr.stop();
  13163. t.join();
  13164. ASSERT_FALSE(svr.is_running());
  13165. });
  13166. svr.wait_until_ready();
  13167. Client cli(HOST, PORT);
  13168. {
  13169. auto res = cli.Get("/image");
  13170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13171. EXPECT_EQ(StatusCode::OK_200, res->status);
  13172. EXPECT_EQ(body, res->body);
  13173. }
  13174. {
  13175. auto res = cli.Get("/identity");
  13176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13177. EXPECT_EQ(StatusCode::OK_200, res->status);
  13178. EXPECT_EQ(body, res->body);
  13179. }
  13180. {
  13181. // The same applies to a request body reaching the server.
  13182. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13183. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13185. EXPECT_EQ(StatusCode::OK_200, res->status);
  13186. EXPECT_EQ(body, res->body);
  13187. }
  13188. }
  13189. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13190. // gzip-encoded response even when the build has no zlib support.
  13191. static const char GZIPPED_HELLO_WORLD[] = {
  13192. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13193. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13194. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13195. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13196. // A content coding is a whole token, not something the field value merely
  13197. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13198. // as "fibre" look like Brotli, and turned a multi-coding value like
  13199. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13200. // it was never meant to see.
  13201. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13202. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13203. Server svr;
  13204. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13205. res.set_content(body, "image/jpeg");
  13206. res.set_header("Content-Encoding", "fibre");
  13207. });
  13208. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13209. res.set_content(body, "image/jpeg");
  13210. res.set_header("Content-Encoding", "gzip, br");
  13211. });
  13212. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13213. res.set_content(body, "image/jpeg");
  13214. res.set_header("Content-Encoding", "x-zstd-ish");
  13215. });
  13216. auto port = svr.bind_to_any_port(HOST);
  13217. thread t = thread([&]() { svr.listen_after_bind(); });
  13218. auto se = detail::scope_exit([&] {
  13219. svr.stop();
  13220. t.join();
  13221. ASSERT_FALSE(svr.is_running());
  13222. });
  13223. svr.wait_until_ready();
  13224. Client cli(HOST, port);
  13225. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13226. auto res = cli.Get(path);
  13227. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13228. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13229. // Not a coding we recognize, so the payload comes back untouched
  13230. EXPECT_EQ(body, res->body) << path;
  13231. }
  13232. }
  13233. // A content coding cpp-httplib recognizes but was not built with must be
  13234. // reported as such. Handing the still-compressed payload back to the caller
  13235. // would silently corrupt it.
  13236. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13237. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13238. Server svr;
  13239. // "image/jpeg" keeps the server from applying a content coding of its own,
  13240. // so the hand-crafted Content-Encoding below survives.
  13241. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13242. res.set_content(gzipped, "image/jpeg");
  13243. res.set_header("Content-Encoding", "gzip");
  13244. });
  13245. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13246. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13247. res.set_content(gzipped, "image/jpeg");
  13248. res.set_header("Content-Encoding", "GZIP");
  13249. });
  13250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13251. auto se = detail::scope_exit([&] {
  13252. svr.stop();
  13253. t.join();
  13254. ASSERT_FALSE(svr.is_running());
  13255. });
  13256. svr.wait_until_ready();
  13257. Client cli(HOST, PORT);
  13258. {
  13259. auto res = cli.Get("/gzipped");
  13260. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13262. EXPECT_EQ("Hello World!", res->body);
  13263. #else
  13264. ASSERT_FALSE(res);
  13265. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13266. #endif
  13267. }
  13268. {
  13269. // open_stream() must behave the same way.
  13270. auto handle = cli.open_stream("GET", "/gzipped");
  13271. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13272. ASSERT_TRUE(handle.is_valid());
  13273. std::string received;
  13274. char buf[256];
  13275. ssize_t n;
  13276. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13277. received.append(buf, static_cast<size_t>(n));
  13278. }
  13279. EXPECT_EQ("Hello World!", received);
  13280. #else
  13281. EXPECT_FALSE(handle.is_valid());
  13282. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13283. #endif
  13284. }
  13285. {
  13286. // A differently-cased coding must not be mistaken for an unknown one, or
  13287. // the body would be handed back still compressed.
  13288. auto res = cli.Get("/gzipped-uppercase");
  13289. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13291. EXPECT_EQ("Hello World!", res->body);
  13292. #else
  13293. ASSERT_FALSE(res);
  13294. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13295. #endif
  13296. }
  13297. }
  13298. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13299. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13300. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13301. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13302. // body a second time and appending a second Content-Encoding field line, so
  13303. // clients that decode one coding per listed value handed back raw gzip bytes.
  13304. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13305. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13306. Server svr;
  13307. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13308. // keeps the server from applying a coding of its own.
  13309. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13310. res.set_content(gzipped, "text/plain");
  13311. res.set_header("Content-Encoding", "gzip");
  13312. });
  13313. auto port = svr.bind_to_any_port(HOST);
  13314. thread t = thread([&]() { svr.listen_after_bind(); });
  13315. auto se = detail::scope_exit([&] {
  13316. svr.stop();
  13317. t.join();
  13318. ASSERT_FALSE(svr.is_running());
  13319. });
  13320. svr.wait_until_ready();
  13321. Client cli(HOST, port);
  13322. Headers headers = {{"Accept-Encoding", "gzip"}};
  13323. auto res = cli.Get("/pre-gzipped", headers);
  13324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13325. EXPECT_EQ(StatusCode::OK_200, res->status);
  13326. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13327. EXPECT_EQ("Hello World!", res->body);
  13328. }
  13329. // set_compress(false) sends every handler response as it is, buffered or
  13330. // streamed
  13331. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13332. const std::string text(1000, 'a');
  13333. Server svr;
  13334. svr.set_compress(false);
  13335. svr.Get("/buffered", [&](const Request &, Response &res) {
  13336. res.set_content(text, "text/plain");
  13337. });
  13338. svr.Get("/streamed", [&](const Request &, Response &res) {
  13339. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13340. sink.write(text.data(), text.size());
  13341. sink.done();
  13342. return true;
  13343. });
  13344. });
  13345. auto port = svr.bind_to_any_port(HOST);
  13346. ASSERT_LT(0, port);
  13347. thread t = thread([&] { svr.listen_after_bind(); });
  13348. auto se = detail::scope_exit([&] {
  13349. svr.stop();
  13350. t.join();
  13351. ASSERT_FALSE(svr.is_running());
  13352. });
  13353. svr.wait_until_ready();
  13354. Client cli(HOST, port);
  13355. cli.set_decompress(false);
  13356. for (auto path : {"/buffered", "/streamed"}) {
  13357. SCOPED_TRACE(path);
  13358. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13360. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13361. EXPECT_EQ(text, res->body);
  13362. }
  13363. }
  13364. // A chunked provider settles its coding where the headers are written and
  13365. // reuses it at write time. Both ends of that have to hold: a handler's own
  13366. // Content-Encoding suppresses the coding, and a response without one is still
  13367. // compressed as it always was.
  13368. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13369. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13370. const std::string plain = "Hello World! Hello World! Hello World!";
  13371. Server svr;
  13372. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13373. res.set_header("Content-Encoding", "gzip");
  13374. res.set_chunked_content_provider(
  13375. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13376. sink.write(gzipped.data(), gzipped.size());
  13377. sink.done();
  13378. return true;
  13379. });
  13380. });
  13381. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13382. res.set_chunked_content_provider(
  13383. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13384. sink.write(plain.data(), plain.size());
  13385. sink.done();
  13386. return true;
  13387. });
  13388. });
  13389. auto port = svr.bind_to_any_port(HOST);
  13390. thread t = thread([&]() { svr.listen_after_bind(); });
  13391. auto se = detail::scope_exit([&] {
  13392. svr.stop();
  13393. t.join();
  13394. ASSERT_FALSE(svr.is_running());
  13395. });
  13396. svr.wait_until_ready();
  13397. Client cli(HOST, port);
  13398. Headers headers = {{"Accept-Encoding", "gzip"}};
  13399. {
  13400. auto res = cli.Get("/pre-gzipped", headers);
  13401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13402. EXPECT_EQ(StatusCode::OK_200, res->status);
  13403. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13404. EXPECT_EQ("Hello World!", res->body);
  13405. }
  13406. {
  13407. auto res = cli.Get("/negotiated", headers);
  13408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13409. EXPECT_EQ(StatusCode::OK_200, res->status);
  13410. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13411. EXPECT_EQ(plain, res->body);
  13412. }
  13413. }
  13414. #endif
  13415. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13416. // the same message as the comma-joined one, so both have to be read the same
  13417. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13418. // single gzip coding, and a body the sender says was encoded twice was handed
  13419. // back after one pass, still compressed but presented as decoded.
  13420. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13421. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13422. Server svr;
  13423. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13424. res.set_content(body, "image/jpeg");
  13425. res.headers.emplace("Content-Encoding", "gzip");
  13426. res.headers.emplace("Content-Encoding", "gzip");
  13427. });
  13428. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13429. res.set_content(body, "image/jpeg");
  13430. res.set_header("Content-Encoding", "gzip, gzip");
  13431. });
  13432. auto port = svr.bind_to_any_port(HOST);
  13433. thread t = thread([&]() { svr.listen_after_bind(); });
  13434. auto se = detail::scope_exit([&] {
  13435. svr.stop();
  13436. t.join();
  13437. ASSERT_FALSE(svr.is_running());
  13438. });
  13439. svr.wait_until_ready();
  13440. Client cli(HOST, port);
  13441. // Two codings is not something cpp-httplib decodes, so both representations
  13442. // take the pass-through path rather than one of them being gunzipped once.
  13443. for (const char *path : {"/split", "/joined"}) {
  13444. auto res = cli.Get(path);
  13445. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13446. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13447. EXPECT_EQ(body, res->body) << path;
  13448. }
  13449. }
  13450. // Regression test for DoS vulnerability: a malicious server sending a response
  13451. // without Content-Length header must not cause unbounded memory consumption on
  13452. // the client side. The client should stop reading after a reasonable limit,
  13453. // similar to the server-side set_payload_max_length protection.
  13454. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13455. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13456. #ifndef _WIN32
  13457. signal(SIGPIPE, SIG_IGN);
  13458. #endif
  13459. auto server_thread = std::thread([] {
  13460. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13461. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13462. default_socket_options(srv);
  13463. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13464. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13465. sockaddr_in addr{};
  13466. addr.sin_family = AF_INET;
  13467. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13468. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13469. int opt = 1;
  13470. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13471. #ifdef _WIN32
  13472. reinterpret_cast<const char *>(&opt),
  13473. #else
  13474. &opt,
  13475. #endif
  13476. sizeof(opt));
  13477. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13478. ::listen(srv, 1);
  13479. sockaddr_in cli_addr{};
  13480. socklen_t cli_len = sizeof(cli_addr);
  13481. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13482. if (cli != INVALID_SOCKET) {
  13483. char buf[4096];
  13484. ::recv(cli, buf, sizeof(buf), 0);
  13485. // Malicious response: no Content-Length, no chunked encoding
  13486. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13487. "Connection: close\r\n"
  13488. "\r\n";
  13489. ::send(cli,
  13490. #ifdef _WIN32
  13491. static_cast<const char *>(response_header.c_str()),
  13492. static_cast<int>(response_header.size()),
  13493. #else
  13494. response_header.c_str(), response_header.size(),
  13495. #endif
  13496. 0);
  13497. // Send 10MB of data
  13498. std::string chunk(64 * 1024, 'A');
  13499. size_t total_sent = 0;
  13500. while (total_sent < MALICIOUS_DATA_SIZE) {
  13501. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13502. auto sent = ::send(cli,
  13503. #ifdef _WIN32
  13504. static_cast<const char *>(chunk.c_str()),
  13505. static_cast<int>(to_send),
  13506. #else
  13507. chunk.c_str(), to_send,
  13508. #endif
  13509. 0);
  13510. if (sent <= 0) break;
  13511. total_sent += static_cast<size_t>(sent);
  13512. }
  13513. detail::close_socket(cli);
  13514. }
  13515. detail::close_socket(srv);
  13516. });
  13517. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13518. size_t total_read = 0;
  13519. {
  13520. Client cli("127.0.0.1", PORT + 2);
  13521. cli.set_read_timeout(5, 0);
  13522. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13523. auto stream = cli.open_stream("GET", "/malicious");
  13524. ASSERT_TRUE(stream.is_valid());
  13525. char buffer[64 * 1024];
  13526. ssize_t n;
  13527. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13528. total_read += static_cast<size_t>(n);
  13529. }
  13530. } // StreamHandle and Client destroyed here, closing the socket
  13531. server_thread.join();
  13532. // With set_payload_max_length, the client must stop reading before consuming
  13533. // all 10MB. The read loop should be cut off at or near the configured limit.
  13534. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13535. << "Client read " << total_read << " bytes, exceeding the configured "
  13536. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13537. }
  13538. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13539. // the entire response body without truncation.
  13540. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13541. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13542. #ifndef _WIN32
  13543. signal(SIGPIPE, SIG_IGN);
  13544. #endif
  13545. auto server_thread = std::thread([] {
  13546. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13547. default_socket_options(srv);
  13548. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13549. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13550. sockaddr_in addr{};
  13551. addr.sin_family = AF_INET;
  13552. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13553. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13554. int opt = 1;
  13555. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13556. #ifdef _WIN32
  13557. reinterpret_cast<const char *>(&opt),
  13558. #else
  13559. &opt,
  13560. #endif
  13561. sizeof(opt));
  13562. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13563. ::listen(srv, 1);
  13564. sockaddr_in cli_addr{};
  13565. socklen_t cli_len = sizeof(cli_addr);
  13566. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13567. if (cli != INVALID_SOCKET) {
  13568. char buf[4096];
  13569. ::recv(cli, buf, sizeof(buf), 0);
  13570. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13571. "Connection: close\r\n"
  13572. "\r\n";
  13573. ::send(cli,
  13574. #ifdef _WIN32
  13575. static_cast<const char *>(response_header.c_str()),
  13576. static_cast<int>(response_header.size()),
  13577. #else
  13578. response_header.c_str(), response_header.size(),
  13579. #endif
  13580. 0);
  13581. std::string chunk(64 * 1024, 'A');
  13582. size_t total_sent = 0;
  13583. while (total_sent < DATA_SIZE) {
  13584. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13585. auto sent = ::send(cli,
  13586. #ifdef _WIN32
  13587. static_cast<const char *>(chunk.c_str()),
  13588. static_cast<int>(to_send),
  13589. #else
  13590. chunk.c_str(), to_send,
  13591. #endif
  13592. 0);
  13593. if (sent <= 0) break;
  13594. total_sent += static_cast<size_t>(sent);
  13595. }
  13596. #ifdef _WIN32
  13597. ::shutdown(cli, SD_SEND);
  13598. #else
  13599. ::shutdown(cli, SHUT_WR);
  13600. #endif
  13601. // Drain until the client closes its end, ensuring all data is delivered
  13602. char drain[1024];
  13603. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  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(0); // 0 means no limit
  13614. auto stream = cli.open_stream("GET", "/data");
  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. }
  13622. server_thread.join();
  13623. EXPECT_EQ(total_read, DATA_SIZE)
  13624. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13625. << " bytes without truncation, but only read " << total_read << " bytes.";
  13626. }
  13627. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13628. // enormous Content-Length must not cause the client to pre-allocate a huge
  13629. // response body buffer. The reservation is capped at payload_max_length_, and
  13630. // the read itself fails when the body exceeds the limit.
  13631. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13632. #ifndef _WIN32
  13633. signal(SIGPIPE, SIG_IGN);
  13634. #endif
  13635. auto server_thread = std::thread([] {
  13636. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13637. default_socket_options(srv);
  13638. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13639. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13640. sockaddr_in addr{};
  13641. addr.sin_family = AF_INET;
  13642. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13643. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13644. int opt = 1;
  13645. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13646. #ifdef _WIN32
  13647. reinterpret_cast<const char *>(&opt),
  13648. #else
  13649. &opt,
  13650. #endif
  13651. sizeof(opt));
  13652. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13653. ::listen(srv, 1);
  13654. sockaddr_in cli_addr{};
  13655. socklen_t cli_len = sizeof(cli_addr);
  13656. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13657. if (cli != INVALID_SOCKET) {
  13658. char buf[4096];
  13659. ::recv(cli, buf, sizeof(buf), 0);
  13660. // Malicious response: claim a 20GB body but send only a tiny payload.
  13661. std::string response = "HTTP/1.1 200 OK\r\n"
  13662. "Content-Length: 20000000000\r\n"
  13663. "\r\n"
  13664. "abc";
  13665. ::send(cli,
  13666. #ifdef _WIN32
  13667. static_cast<const char *>(response.c_str()),
  13668. static_cast<int>(response.size()),
  13669. #else
  13670. response.c_str(), response.size(),
  13671. #endif
  13672. 0);
  13673. detail::close_socket(cli);
  13674. }
  13675. detail::close_socket(srv);
  13676. });
  13677. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13678. {
  13679. Client cli("127.0.0.1", PORT + 2);
  13680. cli.set_read_timeout(5, 0);
  13681. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13682. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13683. // (server claims more bytes than payload_max_length permits), but it must
  13684. // not exhaust memory before getting there.
  13685. auto res = cli.Get("/malicious");
  13686. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13687. }
  13688. server_thread.join();
  13689. }
  13690. // Verify that content_receiver bypasses the default payload_max_length,
  13691. // allowing streaming downloads larger than 100MB without requiring an explicit
  13692. // set_payload_max_length call.
  13693. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13694. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13695. #ifndef _WIN32
  13696. signal(SIGPIPE, SIG_IGN);
  13697. #endif
  13698. auto server_thread = std::thread([] {
  13699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13700. default_socket_options(srv);
  13701. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13702. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13703. sockaddr_in addr{};
  13704. addr.sin_family = AF_INET;
  13705. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13707. int opt = 1;
  13708. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13709. #ifdef _WIN32
  13710. reinterpret_cast<const char *>(&opt),
  13711. #else
  13712. &opt,
  13713. #endif
  13714. sizeof(opt));
  13715. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13716. ::listen(srv, 1);
  13717. sockaddr_in cli_addr{};
  13718. socklen_t cli_len = sizeof(cli_addr);
  13719. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13720. if (cli != INVALID_SOCKET) {
  13721. char buf[4096];
  13722. ::recv(cli, buf, sizeof(buf), 0);
  13723. // Response with Content-Length larger than default 100MB limit
  13724. auto content_length = std::to_string(DATA_SIZE);
  13725. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13726. "Content-Length: " +
  13727. content_length +
  13728. "\r\n"
  13729. "Connection: close\r\n"
  13730. "\r\n";
  13731. ::send(cli,
  13732. #ifdef _WIN32
  13733. static_cast<const char *>(response_header.c_str()),
  13734. static_cast<int>(response_header.size()),
  13735. #else
  13736. response_header.c_str(), response_header.size(),
  13737. #endif
  13738. 0);
  13739. std::string chunk(64 * 1024, 'A');
  13740. size_t total_sent = 0;
  13741. while (total_sent < DATA_SIZE) {
  13742. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13743. auto sent = ::send(cli,
  13744. #ifdef _WIN32
  13745. static_cast<const char *>(chunk.c_str()),
  13746. static_cast<int>(to_send),
  13747. #else
  13748. chunk.c_str(), to_send,
  13749. #endif
  13750. 0);
  13751. if (sent <= 0) break;
  13752. total_sent += static_cast<size_t>(sent);
  13753. }
  13754. detail::close_socket(cli);
  13755. }
  13756. detail::close_socket(srv);
  13757. });
  13758. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13759. size_t total_received = 0;
  13760. {
  13761. Client cli("127.0.0.1", PORT + 2);
  13762. cli.set_read_timeout(10, 0);
  13763. // Do NOT call set_payload_max_length — use the default 100MB limit
  13764. auto res =
  13765. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13766. total_received += data_length;
  13767. return true;
  13768. });
  13769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13770. EXPECT_EQ(StatusCode::OK_200, res->status);
  13771. }
  13772. server_thread.join();
  13773. EXPECT_EQ(total_received, DATA_SIZE)
  13774. << "With content_receiver, the client should read all " << DATA_SIZE
  13775. << " bytes despite the default 100MB payload_max_length, but only read "
  13776. << total_received << " bytes.";
  13777. }
  13778. // Verify that an explicit set_payload_max_length smaller than the response is
  13779. // enforced even when a content_receiver is used.
  13780. TEST(ClientVulnerabilityTest,
  13781. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13782. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13783. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13784. #ifndef _WIN32
  13785. signal(SIGPIPE, SIG_IGN);
  13786. #endif
  13787. auto server_thread = std::thread([] {
  13788. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13789. default_socket_options(srv);
  13790. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13791. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13792. sockaddr_in addr{};
  13793. addr.sin_family = AF_INET;
  13794. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13795. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13796. int opt = 1;
  13797. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13798. #ifdef _WIN32
  13799. reinterpret_cast<const char *>(&opt),
  13800. #else
  13801. &opt,
  13802. #endif
  13803. sizeof(opt));
  13804. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13805. ::listen(srv, 1);
  13806. sockaddr_in cli_addr{};
  13807. socklen_t cli_len = sizeof(cli_addr);
  13808. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13809. if (cli != INVALID_SOCKET) {
  13810. char buf[4096];
  13811. ::recv(cli, buf, sizeof(buf), 0);
  13812. auto content_length = std::to_string(DATA_SIZE);
  13813. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13814. "Content-Length: " +
  13815. content_length +
  13816. "\r\n"
  13817. "Connection: close\r\n"
  13818. "\r\n";
  13819. ::send(cli,
  13820. #ifdef _WIN32
  13821. static_cast<const char *>(response_header.c_str()),
  13822. static_cast<int>(response_header.size()),
  13823. #else
  13824. response_header.c_str(), response_header.size(),
  13825. #endif
  13826. 0);
  13827. std::string chunk(64 * 1024, 'A');
  13828. size_t total_sent = 0;
  13829. while (total_sent < DATA_SIZE) {
  13830. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13831. auto sent = ::send(cli,
  13832. #ifdef _WIN32
  13833. static_cast<const char *>(chunk.c_str()),
  13834. static_cast<int>(to_send),
  13835. #else
  13836. chunk.c_str(), to_send,
  13837. #endif
  13838. 0);
  13839. if (sent <= 0) break;
  13840. total_sent += static_cast<size_t>(sent);
  13841. }
  13842. detail::close_socket(cli);
  13843. }
  13844. detail::close_socket(srv);
  13845. });
  13846. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13847. size_t total_received = 0;
  13848. {
  13849. Client cli("127.0.0.1", PORT + 2);
  13850. cli.set_read_timeout(10, 0);
  13851. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13852. auto res =
  13853. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13854. total_received += data_length;
  13855. return true;
  13856. });
  13857. // Should fail because 200MB exceeds the explicit 150MB limit
  13858. EXPECT_FALSE(res);
  13859. }
  13860. server_thread.join();
  13861. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13862. << "Client with content_receiver should respect the explicit "
  13863. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13864. << total_received << " bytes.";
  13865. }
  13866. // Verify that an explicit set_payload_max_length larger than the response
  13867. // allows the content_receiver to read all data successfully.
  13868. TEST(ClientVulnerabilityTest,
  13869. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13870. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13871. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13872. #ifndef _WIN32
  13873. signal(SIGPIPE, SIG_IGN);
  13874. #endif
  13875. auto server_thread = std::thread([] {
  13876. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13877. default_socket_options(srv);
  13878. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13879. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13880. sockaddr_in addr{};
  13881. addr.sin_family = AF_INET;
  13882. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13883. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13884. int opt = 1;
  13885. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13886. #ifdef _WIN32
  13887. reinterpret_cast<const char *>(&opt),
  13888. #else
  13889. &opt,
  13890. #endif
  13891. sizeof(opt));
  13892. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13893. ::listen(srv, 1);
  13894. sockaddr_in cli_addr{};
  13895. socklen_t cli_len = sizeof(cli_addr);
  13896. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13897. if (cli != INVALID_SOCKET) {
  13898. char buf[4096];
  13899. ::recv(cli, buf, sizeof(buf), 0);
  13900. auto content_length = std::to_string(DATA_SIZE);
  13901. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13902. "Content-Length: " +
  13903. content_length +
  13904. "\r\n"
  13905. "Connection: close\r\n"
  13906. "\r\n";
  13907. ::send(cli,
  13908. #ifdef _WIN32
  13909. static_cast<const char *>(response_header.c_str()),
  13910. static_cast<int>(response_header.size()),
  13911. #else
  13912. response_header.c_str(), response_header.size(),
  13913. #endif
  13914. 0);
  13915. std::string chunk(64 * 1024, 'A');
  13916. size_t total_sent = 0;
  13917. while (total_sent < DATA_SIZE) {
  13918. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13919. auto sent = ::send(cli,
  13920. #ifdef _WIN32
  13921. static_cast<const char *>(chunk.c_str()),
  13922. static_cast<int>(to_send),
  13923. #else
  13924. chunk.c_str(), to_send,
  13925. #endif
  13926. 0);
  13927. if (sent <= 0) break;
  13928. total_sent += static_cast<size_t>(sent);
  13929. }
  13930. #ifdef _WIN32
  13931. ::shutdown(cli, SD_SEND);
  13932. #else
  13933. ::shutdown(cli, SHUT_WR);
  13934. #endif
  13935. char drain[1024];
  13936. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13937. detail::close_socket(cli);
  13938. }
  13939. detail::close_socket(srv);
  13940. });
  13941. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13942. size_t total_received = 0;
  13943. {
  13944. Client cli("127.0.0.1", PORT + 2);
  13945. cli.set_read_timeout(10, 0);
  13946. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13947. auto res =
  13948. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13949. total_received += data_length;
  13950. return true;
  13951. });
  13952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13953. EXPECT_EQ(StatusCode::OK_200, res->status);
  13954. }
  13955. server_thread.join();
  13956. EXPECT_EQ(total_received, DATA_SIZE)
  13957. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13958. << " bytes (larger than " << DATA_SIZE
  13959. << " bytes response), content_receiver should read all data, but only "
  13960. "read "
  13961. << total_received << " bytes.";
  13962. }
  13963. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13964. // Regression test for "zip bomb" attack on the client side: a malicious server
  13965. // sends a small gzip-compressed response that decompresses to a huge payload.
  13966. // The client must enforce payload_max_length on the decompressed size.
  13967. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13968. constexpr size_t DECOMPRESSED_SIZE =
  13969. 10 * 1024 * 1024; // 10MB after decompression
  13970. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13971. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13972. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13973. std::string compressed;
  13974. {
  13975. httplib::detail::gzip_compressor compressor;
  13976. bool ok =
  13977. compressor.compress(uncompressed.data(), uncompressed.size(),
  13978. /*last=*/true, [&](const char *buf, size_t len) {
  13979. compressed.append(buf, len);
  13980. return true;
  13981. });
  13982. ASSERT_TRUE(ok);
  13983. }
  13984. // Sanity: compressed data should be much smaller than the decompressed size
  13985. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13986. #ifndef _WIN32
  13987. signal(SIGPIPE, SIG_IGN);
  13988. #endif
  13989. // Set up the listening socket in the main thread so the server is guaranteed
  13990. // to be ready before the client connects (eliminates race condition).
  13991. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13992. default_socket_options(srv);
  13993. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13994. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13995. sockaddr_in addr{};
  13996. addr.sin_family = AF_INET;
  13997. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13998. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13999. int opt = 1;
  14000. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14001. #ifdef _WIN32
  14002. reinterpret_cast<const char *>(&opt),
  14003. #else
  14004. &opt,
  14005. #endif
  14006. sizeof(opt));
  14007. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14008. ASSERT_EQ(0, ::listen(srv, 1));
  14009. auto server_thread = std::thread([&compressed, srv] {
  14010. sockaddr_in cli_addr{};
  14011. socklen_t cli_len = sizeof(cli_addr);
  14012. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14013. if (cli != INVALID_SOCKET) {
  14014. // Read the full HTTP request (until \r\n\r\n)
  14015. char buf[4096];
  14016. size_t total = 0;
  14017. while (total < sizeof(buf)) {
  14018. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14019. if (n <= 0) break;
  14020. total += static_cast<size_t>(n);
  14021. // Check for end of headers
  14022. if (total >= 4) {
  14023. std::string req(buf, total);
  14024. if (req.find("\r\n\r\n") != std::string::npos) break;
  14025. }
  14026. }
  14027. // Malicious response: gzip-compressed body, no Content-Length
  14028. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14029. "Content-Encoding: gzip\r\n"
  14030. "Connection: close\r\n"
  14031. "\r\n";
  14032. ::send(cli,
  14033. #ifdef _WIN32
  14034. static_cast<const char *>(response_header.c_str()),
  14035. static_cast<int>(response_header.size()),
  14036. #else
  14037. response_header.c_str(), response_header.size(),
  14038. #endif
  14039. 0);
  14040. // Send the compressed payload (small on the wire, huge when decompressed)
  14041. size_t total_sent = 0;
  14042. while (total_sent < compressed.size()) {
  14043. auto to_send = std::min(compressed.size() - total_sent,
  14044. static_cast<size_t>(64 * 1024));
  14045. auto sent =
  14046. ::send(cli,
  14047. #ifdef _WIN32
  14048. static_cast<const char *>(compressed.c_str() + total_sent),
  14049. static_cast<int>(to_send),
  14050. #else
  14051. compressed.c_str() + total_sent, to_send,
  14052. #endif
  14053. 0);
  14054. if (sent <= 0) break;
  14055. total_sent += static_cast<size_t>(sent);
  14056. }
  14057. detail::close_socket(cli);
  14058. }
  14059. });
  14060. auto se = detail::scope_exit([&] {
  14061. detail::close_socket(srv);
  14062. server_thread.join();
  14063. });
  14064. size_t total_decompressed = 0;
  14065. {
  14066. Client cli("127.0.0.1", PORT + 3);
  14067. cli.set_read_timeout(5, 0);
  14068. cli.set_decompress(true);
  14069. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14070. auto stream = cli.open_stream("GET", "/zipbomb");
  14071. ASSERT_TRUE(stream.is_valid());
  14072. char buffer[64 * 1024];
  14073. ssize_t n;
  14074. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14075. total_decompressed += static_cast<size_t>(n);
  14076. }
  14077. }
  14078. // The decompressed size must be capped by payload_max_length. Without
  14079. // protection, the client would decompress the full 10MB from a tiny
  14080. // compressed payload, enabling a zip bomb DoS attack.
  14081. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14082. << "Client decompressed " << total_decompressed
  14083. << " bytes from a gzip response. The decompressed size should be "
  14084. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14085. }
  14086. #endif
  14087. TEST(HostAndPortPropertiesTest, NoSSL) {
  14088. httplib::Client cli("www.google.com", 1234);
  14089. ASSERT_EQ("www.google.com", cli.host());
  14090. ASSERT_EQ(1234, cli.port());
  14091. }
  14092. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14093. httplib::Client cli("www.google.com:1234");
  14094. ASSERT_EQ("www.google.com", cli.host());
  14095. ASSERT_EQ(1234, cli.port());
  14096. }
  14097. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14098. // Port number that overflows int — should not crash, client becomes invalid
  14099. httplib::Client cli("http://www.google.com:99999999999999999999");
  14100. ASSERT_FALSE(cli.is_valid());
  14101. }
  14102. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14103. // Port 99999 exceeds valid range (1-65535) — should not crash
  14104. httplib::Client cli("http://www.google.com:99999");
  14105. ASSERT_FALSE(cli.is_valid());
  14106. auto res = cli.Get("/");
  14107. EXPECT_FALSE(res);
  14108. EXPECT_EQ(Error::Connection, res.error());
  14109. }
  14110. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14111. httplib::Client cli("http://user:pass@localhost:1234");
  14112. ASSERT_FALSE(cli.is_valid());
  14113. EXPECT_FALSE(cli.Get("/"));
  14114. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14115. }
  14116. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14117. httplib::Client cli("http://www.google.com:80abc");
  14118. ASSERT_FALSE(cli.is_valid());
  14119. }
  14120. #ifdef CPPHTTPLIB_SSL_ENABLED
  14121. TEST(HostAndPortPropertiesTest, SSL) {
  14122. httplib::SSLClient cli("www.google.com");
  14123. ASSERT_EQ("www.google.com", cli.host());
  14124. ASSERT_EQ(443, cli.port());
  14125. }
  14126. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14127. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14128. std::string cert;
  14129. read_file(CA_CERT_FILE, cert);
  14130. httplib::SSLClient httplib_client("www.google.com");
  14131. // Load CA store first time
  14132. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14133. // Load CA store second time (update)
  14134. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14135. // Verify client is still valid and can make connections
  14136. httplib_client.enable_server_certificate_verification(true);
  14137. auto res = httplib_client.Get("/");
  14138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14139. // Google may return 200 or 301 depending on various factors
  14140. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14141. res->status == StatusCode::MovedPermanently_301);
  14142. }
  14143. TEST(SSLClientTest, ServerNameIndication_Online) {
  14144. auto host = "httpbingo.org";
  14145. auto path = std::string{"/get"};
  14146. SSLClient cli(host, 443);
  14147. auto res = cli.Get(path);
  14148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14149. ASSERT_EQ(StatusCode::OK_200, res->status);
  14150. }
  14151. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14152. // Use a site that will cause SSL verification failure due to self-signed cert
  14153. SSLClient cli("self-signed.badssl.com", 443);
  14154. cli.enable_server_certificate_verification(true);
  14155. auto res = cli.Get("/");
  14156. ASSERT_TRUE(!res);
  14157. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14158. // Verify backend error is captured for SSLServerVerification
  14159. // This occurs when certificate verification fails
  14160. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14161. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14162. EXPECT_NE(0UL, res.ssl_backend_error());
  14163. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14164. res.ssl_error());
  14165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14166. #if !defined(_WIN32) || \
  14167. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14168. // On non-Windows or when Windows Schannel is disabled, the error comes
  14169. // from OpenSSL's verification
  14170. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14171. res.ssl_backend_error());
  14172. #endif
  14173. #endif
  14174. }
  14175. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14176. // Use a site where hostname doesn't match the certificate
  14177. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14178. SSLClient cli("wrong.host.badssl.com", 443);
  14179. cli.enable_server_certificate_verification(true);
  14180. cli.enable_server_hostname_verification(true);
  14181. auto res = cli.Get("/");
  14182. ASSERT_TRUE(!res);
  14183. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14184. // Verify backend error is captured for hostname verification failure
  14185. EXPECT_NE(0UL, res.ssl_backend_error());
  14186. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14187. res.ssl_error());
  14188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14189. #if !defined(_WIN32) || \
  14190. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14191. // On non-Windows or when Windows Schannel is disabled, the error comes
  14192. // from OpenSSL's hostname verification
  14193. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14194. res.ssl_backend_error());
  14195. #endif
  14196. #endif
  14197. }
  14198. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14199. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14200. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14201. SSLClient cli("www.google.com", 443);
  14202. cli.enable_server_certificate_verification(true);
  14203. auto res = cli.Get("/");
  14204. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14205. }
  14206. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14207. SSLClient cli("www.google.com", 443);
  14208. cli.enable_server_certificate_verification(true);
  14209. cli.enable_windows_certificate_verification(false);
  14210. auto res = cli.Get("/");
  14211. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14212. }
  14213. // The server sends an intermediate cross-signed by a root Windows trusts,
  14214. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14215. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14216. SSLClient cli("accounts.spotify.com", 443);
  14217. auto res = cli.Get("/");
  14218. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14219. << " ssl_backend_error=" << res.ssl_backend_error();
  14220. }
  14221. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14222. // policy status, which no backend reports for a self-signed certificate.
  14223. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14224. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14225. ASSERT_TRUE(svr.is_valid());
  14226. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14227. auto se = detail::scope_exit([&] {
  14228. svr.stop();
  14229. t.join();
  14230. ASSERT_FALSE(svr.is_running());
  14231. });
  14232. svr.wait_until_ready();
  14233. SSLClient cli("127.0.0.1", PORT);
  14234. cli.set_connection_timeout(30);
  14235. auto res = cli.Get("/");
  14236. ASSERT_FALSE(res);
  14237. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14238. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14239. }
  14240. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14241. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14242. ASSERT_TRUE(svr.is_valid());
  14243. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14244. auto se = detail::scope_exit([&] {
  14245. svr.stop();
  14246. t.join();
  14247. ASSERT_FALSE(svr.is_running());
  14248. });
  14249. svr.wait_until_ready();
  14250. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14251. {
  14252. ws::WebSocketClient client(url);
  14253. auto res = client.connect();
  14254. ASSERT_FALSE(res);
  14255. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14256. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14257. res.ssl_backend_error());
  14258. }
  14259. {
  14260. ws::WebSocketClient client(url);
  14261. client.enable_windows_certificate_verification(false);
  14262. auto res = client.connect();
  14263. ASSERT_FALSE(res);
  14264. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14265. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14266. res.ssl_backend_error());
  14267. }
  14268. }
  14269. #endif
  14270. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14271. Client cli("https://google.com");
  14272. auto res = cli.Get("/");
  14273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14274. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14275. }
  14276. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14277. SSLClient cli("google.com");
  14278. cli.set_ca_cert_path(CA_CERT_FILE);
  14279. auto res = cli.Get("/");
  14280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14281. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14282. }
  14283. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14284. SSLClient cli("google.com");
  14285. cli.enable_server_certificate_verification(true);
  14286. cli.set_ca_cert_path("hello");
  14287. auto res = cli.Get("/");
  14288. ASSERT_TRUE(!res);
  14289. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14290. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14291. // should be set
  14292. EXPECT_EQ(0, res.ssl_error());
  14293. // Verify backend error is captured for SSLLoadingCerts
  14294. // This error occurs when loading CA certificates fails
  14295. EXPECT_NE(0UL, res.ssl_backend_error());
  14296. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14297. // OpenSSL specific error codes:
  14298. // > openssl errstr 0x80000002
  14299. // error:80000002:system library::No such file or directory
  14300. // > openssl errstr 0xA000126
  14301. // error:0A000126:SSL routines::unexpected eof while reading
  14302. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14303. res.ssl_backend_error() == 0xA000126);
  14304. #endif
  14305. }
  14306. TEST(SSLClientTest, ServerCertificateVerification4) {
  14307. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14308. ASSERT_TRUE(svr.is_valid());
  14309. svr.Get("/test", [&](const Request &, Response &res) {
  14310. res.set_content("test", "text/plain");
  14311. svr.stop();
  14312. ASSERT_TRUE(true);
  14313. });
  14314. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14315. auto se = detail::scope_exit([&] {
  14316. t.join();
  14317. ASSERT_FALSE(svr.is_running());
  14318. });
  14319. svr.wait_until_ready();
  14320. SSLClient cli("127.0.0.1", PORT);
  14321. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14322. cli.enable_server_certificate_verification(true);
  14323. cli.set_connection_timeout(30);
  14324. auto res = cli.Get("/test");
  14325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14326. ASSERT_EQ(StatusCode::OK_200, res->status);
  14327. }
  14328. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14329. std::string cert;
  14330. read_file(CA_CERT_FILE, cert);
  14331. SSLClient cli("google.com");
  14332. cli.load_ca_cert_store(cert.data(), cert.size());
  14333. const auto res = cli.Get("/");
  14334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14335. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14336. }
  14337. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14338. // clang-format off
  14339. static constexpr char cert[] =
  14340. "GlobalSign Root CA\n"
  14341. "==================\n"
  14342. "-----BEGIN CERTIFICATE-----\n"
  14343. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14344. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14345. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14346. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14347. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14348. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14349. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14350. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14351. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14352. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14353. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14354. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14355. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14356. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14357. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14358. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14359. "-----END CERTIFICATE-----\n";
  14360. // clang-format on
  14361. SSLClient cli("google.com");
  14362. cli.load_ca_cert_store(cert, sizeof(cert));
  14363. const auto res = cli.Get("/");
  14364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14365. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14366. }
  14367. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14368. SSLClient cli("www.youtube.com");
  14369. cli.set_ca_cert_path(CA_CERT_FILE);
  14370. cli.enable_server_certificate_verification(true);
  14371. cli.set_follow_location(true);
  14372. auto res = cli.Get("/");
  14373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14374. ASSERT_EQ(StatusCode::OK_200, res->status);
  14375. }
  14376. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14377. SSLClient cli("wWw.YouTube.Com");
  14378. cli.set_ca_cert_path(CA_CERT_FILE);
  14379. cli.enable_server_certificate_verification(true);
  14380. cli.enable_server_hostname_verification(true);
  14381. cli.set_follow_location(true);
  14382. auto res = cli.Get("/");
  14383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14384. ASSERT_EQ(StatusCode::OK_200, res->status);
  14385. }
  14386. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14387. SSLClient cli("gOoGlE.COm");
  14388. cli.enable_server_certificate_verification(true);
  14389. cli.enable_server_hostname_verification(true);
  14390. cli.set_follow_location(true);
  14391. auto res = cli.Get("/");
  14392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14393. ASSERT_EQ(StatusCode::OK_200, res->status);
  14394. }
  14395. TEST(SSLClientTest, Issue2004_Online) {
  14396. Client client("https://google.com");
  14397. client.set_follow_location(true);
  14398. auto res = client.Get("/");
  14399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14400. ASSERT_EQ(StatusCode::OK_200, res->status);
  14401. auto body = res->body;
  14402. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14403. }
  14404. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14405. // Create SSLClient with invalid cert/key to make is_valid() return false
  14406. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14407. "nonexistent_key.pem");
  14408. // is_valid() should be false due to cert loading failure
  14409. ASSERT_FALSE(cli.is_valid());
  14410. auto res = cli.Get("/");
  14411. ASSERT_FALSE(res);
  14412. EXPECT_EQ(Error::SSLConnection, res.error());
  14413. }
  14414. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14415. // Test for Issue #2251: SSL error not properly reported when client cert
  14416. // and key paths are swapped or mismatched
  14417. // This simulates the scenario where user accidentally swaps the cert and key
  14418. // files
  14419. // Using client cert file as private key and vice versa (completely wrong)
  14420. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14421. // Should fail validation due to cert/key mismatch
  14422. ASSERT_FALSE(cli.is_valid());
  14423. // Attempt to make a request should fail with proper error
  14424. auto res = cli.Get("/");
  14425. ASSERT_FALSE(res);
  14426. EXPECT_EQ(Error::SSLConnection, res.error());
  14427. // SSL error should be recorded in the Result object (this is the key fix for
  14428. // Issue #2251)
  14429. auto backend_error = res.ssl_backend_error();
  14430. EXPECT_NE(0u, backend_error);
  14431. }
  14432. // Tests cert/key mismatch detection at the TLS context level
  14433. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14434. // Test that using mismatched cert/key causes connection failure.
  14435. // We verify this at the SSLClient level rather than through internal
  14436. // TLS API functions.
  14437. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14438. cli.enable_server_certificate_verification(false);
  14439. cli.set_connection_timeout(2);
  14440. // The mismatch should cause a connection or handshake error
  14441. auto res = cli.Get("/test");
  14442. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14443. // Either way, the request should fail
  14444. EXPECT_FALSE(res);
  14445. }
  14446. #endif
  14447. #if 0
  14448. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14449. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14450. ASSERT_TRUE(cli != nullptr);
  14451. cli->set_address_family(AF_INET6);
  14452. cli->set_interface("en0");
  14453. auto res = cli->Get("/get");
  14454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14455. ASSERT_EQ(StatusCode::OK_200, res->status);
  14456. }
  14457. #endif
  14458. // Client certificate tests - work with all TLS backends
  14459. #ifdef CPPHTTPLIB_SSL_ENABLED
  14460. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14461. void ClientCertPresent(
  14462. const std::string &client_cert_file,
  14463. const std::string &client_private_key_file,
  14464. const std::string &client_encrypted_private_key_pass = std::string(),
  14465. const ClientCertServerSetup &setup = nullptr) {
  14466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14467. ASSERT_TRUE(svr.is_valid());
  14468. if (setup) { setup(svr); }
  14469. svr.Get("/test", [&](const Request &req, Response &res) {
  14470. res.set_content("test", "text/plain");
  14471. auto cert = req.peer_cert();
  14472. ASSERT_TRUE(static_cast<bool>(cert));
  14473. std::string common_name = cert.subject_cn();
  14474. EXPECT_EQ("Common Name", common_name);
  14475. });
  14476. auto port = svr.bind_to_any_port(HOST);
  14477. ASSERT_LT(0, port);
  14478. thread t = thread([&]() { svr.listen_after_bind(); });
  14479. auto se = detail::scope_exit([&] {
  14480. svr.stop();
  14481. t.join();
  14482. ASSERT_FALSE(svr.is_running());
  14483. });
  14484. svr.wait_until_ready();
  14485. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14486. client_encrypted_private_key_pass);
  14487. cli.enable_server_certificate_verification(false);
  14488. cli.set_connection_timeout(30);
  14489. auto res = cli.Get("/test");
  14490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14491. ASSERT_EQ(StatusCode::OK_200, res->status);
  14492. }
  14493. TEST(SSLClientServerTest, ClientCertPresent) {
  14494. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14495. }
  14496. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14497. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14498. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14499. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14500. }
  14501. // Expects svr, which must require client certificates, to reject a client
  14502. // that has none
  14503. void RejectsClientWithoutCert(SSLServer &svr) {
  14504. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14505. auto port = svr.bind_to_any_port(HOST);
  14506. ASSERT_LT(0, port);
  14507. thread t = thread([&]() { svr.listen_after_bind(); });
  14508. auto se = detail::scope_exit([&] {
  14509. svr.stop();
  14510. t.join();
  14511. ASSERT_FALSE(svr.is_running());
  14512. });
  14513. svr.wait_until_ready();
  14514. SSLClient cli(HOST, port);
  14515. cli.set_connection_timeout(30);
  14516. // Skip the server certificate check, so that the request fails because the
  14517. // client certificate is missing rather than because cert.pem is not trusted
  14518. cli.enable_server_certificate_verification(false);
  14519. auto res = cli.Get("/test");
  14520. ASSERT_FALSE(res);
  14521. // The server rejects the client during the handshake, or on TLS 1.3 right
  14522. // after it, which the client notices on its first write or read
  14523. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14524. res.error() == Error::Write || res.error() == Error::Read)
  14525. << to_string(res.error());
  14526. if (res.error() == Error::SSLConnection) {
  14527. EXPECT_NE(0UL, res.ssl_backend_error());
  14528. }
  14529. // A rejection noticed on the write keeps the TLS error the write hit
  14530. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14531. }
  14532. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14534. ASSERT_TRUE(svr.is_valid());
  14535. if (setup) { setup(svr); }
  14536. RejectsClientWithoutCert(svr);
  14537. }
  14538. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14539. // A server that requires client certificates must keep requiring them after
  14540. // setup changes it, and keep accepting a client that has one
  14541. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14542. ClientCertMissing(setup);
  14543. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14544. setup);
  14545. }
  14546. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14547. ClientCertStillRequired([](SSLServer &svr) {
  14548. ASSERT_TRUE(tls::set_verify_callback(
  14549. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14550. });
  14551. }
  14552. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14553. ClientCertStillRequired([](SSLServer &svr) {
  14554. ASSERT_TRUE(tls::set_verify_callback(
  14555. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14556. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14557. });
  14558. }
  14559. // The client verifies the server certificate during the handshake, so a
  14560. // server that fails the check never gets the client certificate, even when a
  14561. // verifier of the client's own accepts it
  14562. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14563. struct Case {
  14564. const char *trusted_ca;
  14565. const char *host;
  14566. Error error;
  14567. };
  14568. // cert2.pem names localhost: the first client does not trust it, and the
  14569. // second trusts it but asks for another name
  14570. for (const auto &c :
  14571. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14572. Case{SERVER_CERT2_FILE, "example.com",
  14573. Error::SSLServerHostnameVerification}}) {
  14574. for (auto with_verifier : {false, true}) {
  14575. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14576. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14577. CLIENT_CA_CERT_FILE);
  14578. ASSERT_TRUE(svr.is_valid());
  14579. std::atomic<bool> got_client_cert{false};
  14580. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14581. [&](const tls::VerifyContext &) {
  14582. got_client_cert = true;
  14583. return true;
  14584. }));
  14585. auto port = svr.bind_to_any_port("127.0.0.1");
  14586. ASSERT_LT(0, port);
  14587. thread t = thread([&] { svr.listen_after_bind(); });
  14588. svr.wait_until_ready();
  14589. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14590. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14591. cli.set_ca_cert_path(c.trusted_ca);
  14592. if (with_verifier) {
  14593. cli.set_server_certificate_verifier(
  14594. [](const tls::VerifyContext &) { return true; });
  14595. }
  14596. auto res = cli.Get("/");
  14597. EXPECT_FALSE(res);
  14598. EXPECT_EQ(c.error, res.error());
  14599. svr.stop();
  14600. t.join();
  14601. EXPECT_FALSE(got_client_cert);
  14602. }
  14603. }
  14604. }
  14605. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14606. std::string cert_pem, key_pem, ca_pem;
  14607. read_file(SERVER_CERT_FILE, cert_pem);
  14608. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14609. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14610. ASSERT_TRUE(
  14611. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14612. }
  14613. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14615. ASSERT_TRUE(svr.is_valid());
  14616. UpdateCertsPemWithClientCA(svr);
  14617. RejectsClientWithoutCert(svr);
  14618. }
  14619. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14620. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14621. }
  14622. // A TLS error from one request must not show up in a later request's Result
  14623. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14625. ASSERT_TRUE(svr.is_valid());
  14626. svr.Get("/test", [](const Request &, Response &res) {
  14627. res.set_content("test", "text/plain");
  14628. });
  14629. auto port = svr.bind_to_any_port(HOST);
  14630. ASSERT_LT(0, port);
  14631. thread t = thread([&]() { svr.listen_after_bind(); });
  14632. auto se = detail::scope_exit([&] {
  14633. svr.stop();
  14634. t.join();
  14635. ASSERT_FALSE(svr.is_running());
  14636. });
  14637. svr.wait_until_ready();
  14638. SSLClient cli(HOST, port);
  14639. cli.set_connection_timeout(30);
  14640. cli.enable_server_hostname_verification(false);
  14641. // cert.pem is not trusted, so the handshake fails
  14642. ASSERT_FALSE(cli.Get("/test"));
  14643. cli.enable_server_certificate_verification(false);
  14644. auto res = cli.Get("/test");
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. EXPECT_EQ(0, res.ssl_error());
  14647. EXPECT_EQ(0UL, res.ssl_backend_error());
  14648. }
  14649. // PEM memory-based constructor tests (works with all TLS backends).
  14650. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14651. // terminator after it.
  14652. void PemMemoryClientCertPresent(
  14653. const std::string &client_cert_file,
  14654. const std::string &client_private_key_file,
  14655. const std::string &client_encrypted_private_key_pass = std::string(),
  14656. bool exact_size = false) {
  14657. // Read PEM files into memory
  14658. std::string server_cert_pem, server_key_pem;
  14659. std::string client_ca_pem;
  14660. std::string client_cert_pem, client_key_pem;
  14661. read_file(SERVER_CERT_FILE, server_cert_pem);
  14662. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14663. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14664. read_file(client_cert_file, client_cert_pem);
  14665. read_file(client_private_key_file, client_key_pem);
  14666. std::list<std::vector<char>> exact_copies;
  14667. auto data = [&](const std::string &pem) -> const char * {
  14668. if (!exact_size) { return pem.c_str(); }
  14669. exact_copies.emplace_back(pem.begin(), pem.end());
  14670. return exact_copies.back().data();
  14671. };
  14672. // Create server with PEM memory
  14673. SSLServer::PemMemory server_pem = {
  14674. data(server_cert_pem),
  14675. server_cert_pem.size(),
  14676. data(server_key_pem),
  14677. server_key_pem.size(),
  14678. data(client_ca_pem),
  14679. client_ca_pem.size(),
  14680. nullptr // no password for server key
  14681. };
  14682. SSLServer svr(server_pem);
  14683. ASSERT_TRUE(svr.is_valid());
  14684. svr.Get("/test", [&](const Request &req, Response &res) {
  14685. res.set_content("test", "text/plain");
  14686. auto cert = req.peer_cert();
  14687. ASSERT_TRUE(static_cast<bool>(cert));
  14688. EXPECT_EQ("Common Name", cert.subject_cn());
  14689. });
  14690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14691. auto se = detail::scope_exit([&] {
  14692. svr.stop();
  14693. t.join();
  14694. ASSERT_FALSE(svr.is_running());
  14695. });
  14696. svr.wait_until_ready();
  14697. // Create client with PEM memory
  14698. const char *password = client_encrypted_private_key_pass.empty()
  14699. ? nullptr
  14700. : client_encrypted_private_key_pass.c_str();
  14701. SSLClient::PemMemory client_pem = {
  14702. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14703. client_key_pem.size(), password};
  14704. SSLClient cli(HOST, PORT, client_pem);
  14705. cli.enable_server_certificate_verification(false);
  14706. cli.set_connection_timeout(30);
  14707. auto res = cli.Get("/test");
  14708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14709. ASSERT_EQ(StatusCode::OK_200, res->status);
  14710. }
  14711. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14712. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14713. }
  14714. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14715. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14716. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14717. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14718. }
  14719. // A server built from PEM memory with a client CA requires client certificates,
  14720. // also when the CA is a NUL-terminated string passed with a length of 0
  14721. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14722. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14723. read_file(SERVER_CERT_FILE, server_cert_pem);
  14724. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14725. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14726. SSLServer::PemMemory server_pem = {
  14727. server_cert_pem.c_str(),
  14728. server_cert_pem.size(),
  14729. server_key_pem.c_str(),
  14730. server_key_pem.size(),
  14731. client_ca_pem.c_str(),
  14732. client_ca_pem.size(),
  14733. nullptr // no password for server key
  14734. };
  14735. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14736. SCOPED_TRACE(client_ca_pem_len);
  14737. server_pem.client_ca_pem_len = client_ca_pem_len;
  14738. SSLServer svr(server_pem);
  14739. ASSERT_TRUE(svr.is_valid());
  14740. RejectsClientWithoutCert(svr);
  14741. }
  14742. // An empty CA fails to load instead of turning the check off
  14743. server_pem.client_ca_pem = "";
  14744. server_pem.client_ca_pem_len = 0;
  14745. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14746. }
  14747. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14748. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14749. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14750. true);
  14751. }
  14752. // A length shorter than the PEM cuts it short, so it no longer loads
  14753. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14754. std::string cert, key;
  14755. read_file(SERVER_CERT_FILE, cert);
  14756. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14757. for (auto cut_cert : {true, false}) {
  14758. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14759. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14760. SSLServer::PemMemory server_pem = {
  14761. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14762. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14763. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14764. key_len, nullptr};
  14765. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14766. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14767. key.c_str(), key_len, nullptr};
  14768. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14769. }
  14770. }
  14771. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14772. class NoListenSSLServer : public SSLServer {
  14773. public:
  14774. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14775. const char *client_ca_cert_file_path,
  14776. const char *client_ca_cert_dir_path = nullptr)
  14777. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14778. client_ca_cert_dir_path),
  14779. stop_(false) {}
  14780. std::atomic_bool stop_;
  14781. private:
  14782. bool process_and_close_socket(socket_t /*sock*/) override {
  14783. // Don't create SSL context
  14784. while (!stop_.load()) {
  14785. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14786. }
  14787. return true;
  14788. }
  14789. };
  14790. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14791. CLIENT_CA_CERT_FILE);
  14792. ASSERT_TRUE(svr.is_valid());
  14793. svr.Get("/test", [&](const Request &, Response &res) {
  14794. res.set_content("test", "text/plain");
  14795. });
  14796. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14797. auto se = detail::scope_exit([&] {
  14798. svr.stop_ = true;
  14799. svr.stop();
  14800. t.join();
  14801. ASSERT_FALSE(svr.is_running());
  14802. });
  14803. svr.wait_until_ready();
  14804. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14805. cli.enable_server_certificate_verification(false);
  14806. cli.set_connection_timeout(1);
  14807. auto res = cli.Get("/test");
  14808. ASSERT_TRUE(!res);
  14809. EXPECT_EQ(Error::SSLConnection, res.error());
  14810. // Timeout results in WantRead error code (maps to backend-specific value)
  14811. EXPECT_NE(0, res.ssl_error());
  14812. }
  14813. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14814. // Test SSLServer with client certificate verification using the standard
  14815. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14817. CLIENT_CA_CERT_DIR);
  14818. ASSERT_TRUE(svr.is_valid());
  14819. svr.Get("/test", [&](const Request &req, Response &res) {
  14820. res.set_content("test", "text/plain");
  14821. auto cert = req.peer_cert();
  14822. ASSERT_TRUE(static_cast<bool>(cert));
  14823. auto common_name = cert.subject_cn();
  14824. EXPECT_EQ("Common Name", common_name);
  14825. });
  14826. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14827. auto se = detail::scope_exit([&] {
  14828. svr.stop();
  14829. t.join();
  14830. ASSERT_FALSE(svr.is_running());
  14831. });
  14832. svr.wait_until_ready();
  14833. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14834. cli.enable_server_certificate_verification(false);
  14835. cli.set_connection_timeout(30);
  14836. auto res = cli.Get("/test");
  14837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14838. ASSERT_EQ(StatusCode::OK_200, res->status);
  14839. }
  14840. // Test verify_hostname on every backend: a host is named by a SAN only
  14841. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14842. using namespace httplib::tls;
  14843. // We need a running server to test against
  14844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14845. ASSERT_TRUE(svr.is_valid());
  14846. svr.Get("/test", [](const Request &, Response &res) {
  14847. res.set_content("ok", "text/plain");
  14848. });
  14849. thread t([&]() { svr.listen(HOST, PORT); });
  14850. auto se = detail::scope_exit([&] {
  14851. svr.stop();
  14852. t.join();
  14853. });
  14854. svr.wait_until_ready();
  14855. bool verify_callback_called = false;
  14856. bool verify_result_wrong = false;
  14857. SSLClient cli(HOST, PORT);
  14858. cli.enable_server_certificate_verification(true);
  14859. cli.set_ca_cert_path(CA_CERT_FILE);
  14860. cli.set_connection_timeout(5);
  14861. // Note: Test certificate has CN="Common Name", not "localhost"
  14862. bool verify_result_cn = false;
  14863. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14864. verify_callback_called = true;
  14865. if (!ctx.cert) return false;
  14866. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14867. verify_result_cn = ctx.check_hostname("Common Name");
  14868. // Test 2: wrong hostname should not match
  14869. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14870. return true; // Accept for the purpose of this test
  14871. });
  14872. auto res = cli.Get("/test");
  14873. // The request may succeed or fail depending on cert configuration
  14874. // but the callback should have been called
  14875. ASSERT_TRUE(verify_callback_called)
  14876. << "Verify callback should have been called";
  14877. EXPECT_FALSE(verify_result_cn)
  14878. << "verify_hostname must not match the certificate CN (no SAN)";
  14879. // Wrong hostname should not match
  14880. EXPECT_FALSE(verify_result_wrong)
  14881. << "verify_hostname should not match 'wronghost.example.com'";
  14882. }
  14883. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14884. // backend verifies it.
  14885. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14886. // Certificate CN is "localhost" and it carries no SAN.
  14887. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14888. ASSERT_TRUE(svr.is_valid());
  14889. svr.Get("/test", [](const Request &, Response &res) {
  14890. res.set_content("ok", "text/plain");
  14891. });
  14892. auto port = svr.bind_to_any_port(HOST);
  14893. thread t([&]() { svr.listen_after_bind(); });
  14894. auto se = detail::scope_exit([&] {
  14895. svr.stop();
  14896. t.join();
  14897. });
  14898. svr.wait_until_ready();
  14899. SSLClient cli("localhost", port);
  14900. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14901. cli.enable_server_certificate_verification(true);
  14902. cli.set_connection_timeout(5);
  14903. auto res = cli.Get("/test");
  14904. ASSERT_FALSE(res);
  14905. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14906. // The same certificate is accepted once host name verification is off, so the
  14907. // failure above is the host name and not the chain.
  14908. cli.enable_server_hostname_verification(false);
  14909. res = cli.Get("/test");
  14910. ASSERT_TRUE(res) << to_string(res.error());
  14911. EXPECT_EQ(StatusCode::OK_200, res->status);
  14912. }
  14913. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14914. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14915. // X509_check_ip behavior and must hold for every backend.
  14916. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14917. using namespace httplib::tls;
  14918. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14919. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14920. ASSERT_TRUE(svr.is_valid());
  14921. svr.Get("/test", [](const Request &, Response &res) {
  14922. res.set_content("ok", "text/plain");
  14923. });
  14924. thread t([&]() { svr.listen(HOST, PORT); });
  14925. auto se = detail::scope_exit([&] {
  14926. svr.stop();
  14927. t.join();
  14928. });
  14929. svr.wait_until_ready();
  14930. bool verify_callback_called = false;
  14931. bool ip_matched_via_cn = true;
  14932. SSLClient cli(HOST, PORT);
  14933. cli.enable_server_certificate_verification(true);
  14934. cli.set_ca_cert_path(CA_CERT_FILE);
  14935. cli.set_connection_timeout(5);
  14936. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14937. verify_callback_called = true;
  14938. if (!ctx.cert) return false;
  14939. // The IP appears only in the CN, so it must NOT be accepted.
  14940. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14941. return true; // Accept for the purpose of this test
  14942. });
  14943. cli.Get("/test");
  14944. ASSERT_TRUE(verify_callback_called)
  14945. << "Verify callback should have been called";
  14946. EXPECT_FALSE(ip_matched_via_cn)
  14947. << "An IP host must not be authenticated via the certificate CN";
  14948. }
  14949. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14950. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14951. using namespace httplib::tls;
  14952. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14953. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14954. ASSERT_TRUE(svr.is_valid());
  14955. svr.Get("/test", [](const Request &, Response &res) {
  14956. res.set_content("ok", "text/plain");
  14957. });
  14958. thread t([&]() { svr.listen(HOST, PORT); });
  14959. auto se = detail::scope_exit([&] {
  14960. svr.stop();
  14961. t.join();
  14962. });
  14963. svr.wait_until_ready();
  14964. bool verify_callback_called = false;
  14965. bool san_matched = false;
  14966. bool wrong_ipv6_matched = true;
  14967. bool cn_ipv6_matched = true;
  14968. SSLClient cli(HOST, PORT);
  14969. cli.enable_server_certificate_verification(true);
  14970. cli.set_ca_cert_path(CA_CERT_FILE);
  14971. cli.set_connection_timeout(5);
  14972. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14973. verify_callback_called = true;
  14974. if (!ctx.cert) return false;
  14975. // Matches the IPv6 iPAddress SAN.
  14976. san_matched = ctx.check_hostname("2001:db8::1");
  14977. // A different IPv6 address must not match.
  14978. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14979. // "::1" lives only in the CN, so it must not be accepted.
  14980. cn_ipv6_matched = ctx.check_hostname("::1");
  14981. return true; // Accept for the purpose of this test
  14982. });
  14983. cli.Get("/test");
  14984. ASSERT_TRUE(verify_callback_called)
  14985. << "Verify callback should have been called";
  14986. EXPECT_TRUE(san_matched)
  14987. << "verify_hostname should match an IPv6 iPAddress SAN";
  14988. EXPECT_FALSE(wrong_ipv6_matched)
  14989. << "verify_hostname should not match a non-matching IPv6 address";
  14990. EXPECT_FALSE(cn_ipv6_matched)
  14991. << "An IPv6 host must not be authenticated via the certificate CN";
  14992. }
  14993. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14994. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14995. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14996. using namespace httplib::tls;
  14997. // SANs: DNS:a.zz, IP:42.46.122.122
  14998. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14999. ASSERT_TRUE(svr.is_valid());
  15000. svr.Get("/test", [](const Request &, Response &res) {
  15001. res.set_content("ok", "text/plain");
  15002. });
  15003. auto port = svr.bind_to_any_port(HOST);
  15004. thread t([&]() { svr.listen_after_bind(); });
  15005. auto se = detail::scope_exit([&] {
  15006. svr.stop();
  15007. t.join();
  15008. });
  15009. svr.wait_until_ready();
  15010. bool verify_callback_called = false;
  15011. bool dns_san_matched = false;
  15012. bool ip_san_matched = false;
  15013. bool ip_matched_via_dns_san = true;
  15014. bool dns_matched_via_ip_san = true;
  15015. bool cn_matched_next_to_dns_san = true;
  15016. SSLClient cli(HOST, port);
  15017. cli.enable_server_certificate_verification(true);
  15018. cli.set_ca_cert_path(CA_CERT_FILE);
  15019. cli.set_connection_timeout(5);
  15020. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15021. verify_callback_called = true;
  15022. if (!ctx.cert) return false;
  15023. dns_san_matched = ctx.check_hostname("a.zz");
  15024. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15025. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15026. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15027. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15028. return true; // Accept for the purpose of this test
  15029. });
  15030. cli.Get("/test");
  15031. ASSERT_TRUE(verify_callback_called)
  15032. << "Verify callback should have been called";
  15033. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15034. EXPECT_TRUE(ip_san_matched)
  15035. << "verify_hostname should match an iPAddress SAN";
  15036. EXPECT_FALSE(ip_matched_via_dns_san)
  15037. << "An IP host must not be authenticated via a dNSName SAN";
  15038. EXPECT_FALSE(dns_matched_via_ip_san)
  15039. << "A DNS host must not be authenticated via an iPAddress SAN";
  15040. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15041. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15042. }
  15043. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15044. // "www.*.example.test" names one host and not every host under example.test.
  15045. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15046. using namespace httplib::tls;
  15047. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15048. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15049. ASSERT_TRUE(svr.is_valid());
  15050. svr.Get("/test", [](const Request &, Response &res) {
  15051. res.set_content("ok", "text/plain");
  15052. });
  15053. auto port = svr.bind_to_any_port(HOST);
  15054. thread t([&]() { svr.listen_after_bind(); });
  15055. auto se = detail::scope_exit([&] {
  15056. svr.stop();
  15057. t.join();
  15058. });
  15059. svr.wait_until_ready();
  15060. bool verify_callback_called = false;
  15061. bool leftmost_wildcard_matched = false;
  15062. bool wildcard_spanned_labels = true;
  15063. bool inner_wildcard_matched = true;
  15064. SSLClient cli(HOST, port);
  15065. cli.enable_server_certificate_verification(true);
  15066. cli.set_ca_cert_path(CA_CERT_FILE);
  15067. cli.set_connection_timeout(5);
  15068. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15069. verify_callback_called = true;
  15070. if (!ctx.cert) return false;
  15071. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15072. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15073. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15074. return true; // Accept for the purpose of this test
  15075. });
  15076. cli.Get("/test");
  15077. ASSERT_TRUE(verify_callback_called)
  15078. << "Verify callback should have been called";
  15079. EXPECT_TRUE(leftmost_wildcard_matched)
  15080. << "A leftmost wildcard should match a single label";
  15081. EXPECT_FALSE(wildcard_spanned_labels)
  15082. << "A wildcard label must not match more than one label";
  15083. EXPECT_FALSE(inner_wildcard_matched)
  15084. << "A wildcard outside the leftmost label must not be honoured";
  15085. }
  15086. // sans() must report each SAN entry under its own type.
  15087. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15088. using namespace httplib::tls;
  15089. // SANs: DNS:a.zz, IP:42.46.122.122
  15090. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15091. ASSERT_TRUE(svr.is_valid());
  15092. svr.Get("/test", [](const Request &, Response &res) {
  15093. res.set_content("ok", "text/plain");
  15094. });
  15095. auto port = svr.bind_to_any_port(HOST);
  15096. thread t([&]() { svr.listen_after_bind(); });
  15097. auto se = detail::scope_exit([&] {
  15098. svr.stop();
  15099. t.join();
  15100. });
  15101. svr.wait_until_ready();
  15102. bool verify_callback_called = false;
  15103. std::vector<SanEntry> sans;
  15104. SSLClient cli(HOST, port);
  15105. cli.enable_server_certificate_verification(true);
  15106. cli.set_ca_cert_path(CA_CERT_FILE);
  15107. cli.set_connection_timeout(5);
  15108. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15109. verify_callback_called = true;
  15110. if (!ctx.cert) return false;
  15111. sans = ctx.sans();
  15112. return true; // Accept for the purpose of this test
  15113. });
  15114. cli.Get("/test");
  15115. ASSERT_TRUE(verify_callback_called)
  15116. << "Verify callback should have been called";
  15117. auto has_san = [&](SanType type, const std::string &value) {
  15118. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15119. return san.type == type && san.value == value;
  15120. });
  15121. };
  15122. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15123. << "sans() should report the dNSName SAN";
  15124. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15125. << "sans() should report the iPAddress SAN";
  15126. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15127. << "sans() must not report the dNSName SAN as an address";
  15128. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15129. << "sans() must not report the iPAddress SAN as a DNS name";
  15130. }
  15131. #endif
  15132. // mbedTLS-specific callback constructor test
  15133. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15134. #ifdef CPPHTTPLIB_SSL_ENABLED
  15135. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15137. ASSERT_TRUE(svr.is_valid());
  15138. // Set up a handler to verify client certificate is present
  15139. bool client_cert_verified = false;
  15140. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15141. // Verify that client certificate was provided
  15142. client_cert_verified = true;
  15143. res.set_content("success", "text/plain");
  15144. });
  15145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15146. auto se = detail::scope_exit([&] {
  15147. svr.stop();
  15148. t.join();
  15149. ASSERT_FALSE(svr.is_running());
  15150. });
  15151. svr.wait_until_ready();
  15152. // Client with certificate
  15153. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15154. cli.enable_server_certificate_verification(false);
  15155. cli.set_connection_timeout(30);
  15156. auto res = cli.Get("/test");
  15157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15158. ASSERT_EQ(StatusCode::OK_200, res->status);
  15159. ASSERT_TRUE(client_cert_verified);
  15160. EXPECT_EQ("success", res->body);
  15161. }
  15162. #endif
  15163. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15164. // backends
  15165. #ifdef CPPHTTPLIB_SSL_ENABLED
  15166. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15167. using namespace httplib::tls;
  15168. // Test that when client CA cert file is provided,
  15169. // the server properly requests and validates client certificates
  15170. // Create a server with client authentication
  15171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15172. ASSERT_TRUE(svr.is_valid());
  15173. bool handler_called = false;
  15174. svr.Get("/test", [&](const Request &req, Response &res) {
  15175. handler_called = true;
  15176. // Verify that a client certificate was provided
  15177. auto cert = req.peer_cert();
  15178. ASSERT_TRUE(static_cast<bool>(cert));
  15179. // Get the issuer name
  15180. std::string issuer_str = cert.issuer_name();
  15181. ASSERT_FALSE(issuer_str.empty());
  15182. // The client certificate should be issued by our test CA
  15183. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15184. res.set_content("authenticated", "text/plain");
  15185. });
  15186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15187. auto se = detail::scope_exit([&] {
  15188. svr.stop();
  15189. t.join();
  15190. ASSERT_FALSE(svr.is_running());
  15191. });
  15192. svr.wait_until_ready();
  15193. // Connect with a client certificate issued by the CA
  15194. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15195. cli.enable_server_certificate_verification(false);
  15196. cli.set_connection_timeout(30);
  15197. auto res = cli.Get("/test");
  15198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15199. ASSERT_EQ(StatusCode::OK_200, res->status);
  15200. ASSERT_TRUE(handler_called);
  15201. EXPECT_EQ("authenticated", res->body);
  15202. }
  15203. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15204. using namespace httplib::tls;
  15205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15206. ASSERT_TRUE(svr.is_valid());
  15207. svr.Get("/test", [](const Request &, Response &res) {
  15208. res.set_content("ok", "text/plain");
  15209. });
  15210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15211. auto se = detail::scope_exit([&] {
  15212. svr.stop();
  15213. t.join();
  15214. });
  15215. svr.wait_until_ready();
  15216. SSLClient cli(HOST, PORT);
  15217. cli.enable_server_certificate_verification(false);
  15218. cli.set_connection_timeout(30);
  15219. bool cert_checked = false;
  15220. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15221. if (ctx.cert) {
  15222. auto sans = ctx.sans();
  15223. // Test certificate may or may not have SANs - just verify the API
  15224. // works If SANs exist, verify the types are valid
  15225. for (const auto &san : sans) {
  15226. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15227. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15228. san.type == SanType::OTHER);
  15229. EXPECT_FALSE(san.value.empty());
  15230. }
  15231. cert_checked = true;
  15232. }
  15233. return true;
  15234. });
  15235. auto res = cli.Get("/test");
  15236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15237. EXPECT_TRUE(cert_checked);
  15238. }
  15239. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15240. using namespace httplib::tls;
  15241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15242. ASSERT_TRUE(svr.is_valid());
  15243. svr.Get("/test", [](const Request &, Response &res) {
  15244. res.set_content("ok", "text/plain");
  15245. });
  15246. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15247. auto se = detail::scope_exit([&] {
  15248. svr.stop();
  15249. t.join();
  15250. });
  15251. svr.wait_until_ready();
  15252. SSLClient cli(HOST, PORT);
  15253. cli.enable_server_certificate_verification(false);
  15254. cli.set_connection_timeout(30);
  15255. bool validity_checked = false;
  15256. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15257. if (ctx.cert) {
  15258. time_t not_before = 0, not_after = 0;
  15259. bool result = ctx.validity(not_before, not_after);
  15260. EXPECT_TRUE(result);
  15261. // Verify that not_before < now < not_after for a valid cert
  15262. time_t now = time(nullptr);
  15263. EXPECT_LT(not_before, now);
  15264. EXPECT_GT(not_after, now);
  15265. validity_checked = true;
  15266. }
  15267. return true;
  15268. });
  15269. auto res = cli.Get("/test");
  15270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15271. EXPECT_TRUE(validity_checked);
  15272. }
  15273. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15274. using namespace httplib::tls;
  15275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15276. ASSERT_TRUE(svr.is_valid());
  15277. svr.Get("/test", [](const Request &, Response &res) {
  15278. res.set_content("ok", "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. });
  15285. svr.wait_until_ready();
  15286. SSLClient cli(HOST, PORT);
  15287. cli.enable_server_certificate_verification(false);
  15288. cli.set_connection_timeout(30);
  15289. bool serial_checked = false;
  15290. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15291. if (ctx.cert) {
  15292. std::string serial = ctx.serial();
  15293. EXPECT_FALSE(serial.empty());
  15294. // Serial should be a hex string
  15295. for (char c : serial) {
  15296. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15297. (c >= 'a' && c <= 'f'));
  15298. }
  15299. serial_checked = true;
  15300. }
  15301. return true;
  15302. });
  15303. auto res = cli.Get("/test");
  15304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15305. EXPECT_TRUE(serial_checked);
  15306. }
  15307. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15308. // Test 1: Valid CA file - no error should be recorded
  15309. {
  15310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15311. CLIENT_CA_CERT_FILE);
  15312. ASSERT_TRUE(svr.is_valid());
  15313. // With valid setup, last_ssl_error should be 0
  15314. EXPECT_EQ(0, svr.ssl_last_error());
  15315. }
  15316. // Test 2: Invalid CA file content
  15317. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15318. {
  15319. // Create a temporary file with completely invalid content
  15320. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15321. {
  15322. std::ofstream ofs(temp_invalid_ca);
  15323. ofs << "This is not a certificate file at all\n";
  15324. ofs << "Just plain text content\n";
  15325. }
  15326. // Create server with invalid CA file
  15327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15328. // Clean up temporary file
  15329. std::remove(temp_invalid_ca);
  15330. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15331. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15332. // Note: SSL_CTX_load_verify_locations typically fails first,
  15333. // but our error handling code path is still exercised
  15334. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15335. }
  15336. }
  15337. TEST(VerifyCallbackTest, VerifyContextFields) {
  15338. using namespace httplib::tls;
  15339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15340. ASSERT_TRUE(svr.is_valid());
  15341. svr.Get("/test", [](const Request &, Response &res) {
  15342. res.set_content("ok", "text/plain");
  15343. });
  15344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15345. auto se = detail::scope_exit([&] {
  15346. svr.stop();
  15347. t.join();
  15348. });
  15349. svr.wait_until_ready();
  15350. SSLClient cli(HOST, PORT);
  15351. cli.enable_server_certificate_verification(false);
  15352. cli.set_connection_timeout(30);
  15353. int callback_count = 0;
  15354. bool saw_leaf_cert = false;
  15355. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15356. if (ctx.cert) {
  15357. callback_count++;
  15358. // We should see at least one certificate (the leaf)
  15359. std::string cn = ctx.subject_cn();
  15360. if (!cn.empty()) { saw_leaf_cert = true; }
  15361. // Verify context fields are populated
  15362. EXPECT_NE(ctx.session, nullptr);
  15363. EXPECT_GE(ctx.depth, 0);
  15364. }
  15365. return true;
  15366. });
  15367. auto res = cli.Get("/test");
  15368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15369. EXPECT_GT(callback_count, 0);
  15370. EXPECT_TRUE(saw_leaf_cert);
  15371. }
  15372. // A verifier that accepts runs alongside the built-in verification, and is the
  15373. // only check once that is turned off.
  15374. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15375. using namespace httplib::tls;
  15376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15377. ASSERT_TRUE(svr.is_valid());
  15378. svr.Get("/test", [](const Request &, Response &res) {
  15379. res.set_content("ok", "text/plain");
  15380. });
  15381. auto port = svr.bind_to_any_port(HOST);
  15382. thread t([&]() { svr.listen_after_bind(); });
  15383. auto se = detail::scope_exit([&] {
  15384. svr.stop();
  15385. t.join();
  15386. });
  15387. svr.wait_until_ready();
  15388. SSLClient cli(HOST, port);
  15389. cli.enable_server_hostname_verification(false);
  15390. auto calls = 0;
  15391. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15392. calls++;
  15393. return true;
  15394. });
  15395. // cert.pem is not trusted
  15396. auto res = cli.Get("/test");
  15397. ASSERT_FALSE(res);
  15398. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15399. EXPECT_GT(calls, 0);
  15400. cli.enable_server_certificate_verification(false);
  15401. res = cli.Get("/test");
  15402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15403. EXPECT_EQ("ok", res->body);
  15404. }
  15405. // A verifier belongs to the client that set it, not to the thread that set it.
  15406. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15407. using namespace httplib::tls;
  15408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15409. ASSERT_TRUE(svr.is_valid());
  15410. svr.Get("/test", [](const Request &, Response &res) {
  15411. res.set_content("ok", "text/plain");
  15412. });
  15413. auto port = svr.bind_to_any_port(HOST);
  15414. thread t([&]() { svr.listen_after_bind(); });
  15415. auto se = detail::scope_exit([&] {
  15416. svr.stop();
  15417. t.join();
  15418. });
  15419. svr.wait_until_ready();
  15420. auto rejecting_calls = 0;
  15421. SSLClient rejecting(HOST, port);
  15422. rejecting.enable_server_certificate_verification(false);
  15423. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15424. rejecting_calls++;
  15425. return false;
  15426. });
  15427. auto accepting_calls = 0;
  15428. SSLClient accepting(HOST, port);
  15429. accepting.enable_server_certificate_verification(false);
  15430. // Set on another thread than the requests below.
  15431. thread([&]() {
  15432. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15433. accepting_calls++;
  15434. return true;
  15435. });
  15436. }).join();
  15437. // Requested on another thread than the verifier was set on.
  15438. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15439. EXPECT_GT(rejecting_calls, 0);
  15440. auto res = accepting.Get("/test");
  15441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15442. EXPECT_GT(accepting_calls, 0);
  15443. }
  15444. // A verifier replaced while a handshake runs it lives until it returns.
  15445. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15446. using namespace httplib::tls;
  15447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15448. ASSERT_TRUE(svr.is_valid());
  15449. svr.Get("/test", [](const Request &, Response &res) {
  15450. res.set_content("ok", "text/plain");
  15451. });
  15452. auto port = svr.bind_to_any_port(HOST);
  15453. thread t([&]() { svr.listen_after_bind(); });
  15454. auto se = detail::scope_exit([&] {
  15455. svr.stop();
  15456. t.join();
  15457. });
  15458. svr.wait_until_ready();
  15459. SSLClient cli(HOST, port);
  15460. cli.enable_server_certificate_verification(false);
  15461. std::promise<void> entered;
  15462. std::promise<void> replaced;
  15463. auto replaced_future = replaced.get_future();
  15464. auto first_call = true;
  15465. // Long enough to live on the heap
  15466. std::string expected(64, 'v');
  15467. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15468. if (first_call) {
  15469. first_call = false;
  15470. entered.set_value();
  15471. replaced_future.wait();
  15472. }
  15473. return expected == std::string(64, 'v');
  15474. });
  15475. thread request([&]() {
  15476. auto res = cli.Get("/test");
  15477. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15478. });
  15479. entered.get_future().wait();
  15480. cli.set_server_certificate_verifier(
  15481. [](const VerifyContext &) { return true; });
  15482. replaced.set_value();
  15483. request.join();
  15484. }
  15485. // VerifyContext::session is the same handle the other tls:: functions take.
  15486. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15487. using namespace httplib::tls;
  15488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15489. ASSERT_TRUE(svr.is_valid());
  15490. svr.Get("/test", [](const Request &, Response &res) {
  15491. res.set_content("ok", "text/plain");
  15492. });
  15493. auto port = svr.bind_to_any_port(HOST);
  15494. thread t([&]() { svr.listen_after_bind(); });
  15495. auto se = detail::scope_exit([&] {
  15496. svr.stop();
  15497. t.join();
  15498. });
  15499. svr.wait_until_ready();
  15500. SSLClient cli(HOST, port);
  15501. cli.enable_server_certificate_verification(false);
  15502. session_t verifier_session = nullptr;
  15503. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15504. verifier_session = ctx.session;
  15505. return true;
  15506. });
  15507. session_t session_verifier_session = nullptr;
  15508. cli.set_session_verifier([&](session_t session) {
  15509. session_verifier_session = session;
  15510. return SSLVerifierResponse::NoDecisionMade;
  15511. });
  15512. auto res = cli.Get("/test");
  15513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15514. EXPECT_NE(nullptr, verifier_session);
  15515. EXPECT_EQ(session_verifier_session, verifier_session);
  15516. }
  15517. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15518. using httplib::tls::TlsError;
  15519. // Test that verify_error_to_string returns empty for success
  15520. std::string success_str = TlsError::verify_error_to_string(0);
  15521. EXPECT_TRUE(success_str.empty());
  15522. // Test that verify_error_to_string returns non-empty for error codes
  15523. // Using a common error code (certificate expired)
  15524. std::string error_str =
  15525. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15526. EXPECT_FALSE(error_str.empty());
  15527. }
  15528. TEST(SessionVerifierTest, CertificateAccepted) {
  15529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15530. ASSERT_TRUE(svr.is_valid());
  15531. svr.Get("/test", [](const Request &, Response &res) {
  15532. res.set_content("ok", "text/plain");
  15533. });
  15534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15535. auto se = detail::scope_exit([&] {
  15536. svr.stop();
  15537. t.join();
  15538. });
  15539. svr.wait_until_ready();
  15540. SSLClient cli(HOST, PORT);
  15541. cli.enable_server_certificate_verification(false);
  15542. cli.set_connection_timeout(30);
  15543. bool callback_called = false;
  15544. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15545. EXPECT_NE(session, nullptr);
  15546. callback_called = true;
  15547. return SSLVerifierResponse::CertificateAccepted;
  15548. });
  15549. auto res = cli.Get("/test");
  15550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15551. EXPECT_EQ(200, res->status);
  15552. EXPECT_TRUE(callback_called);
  15553. }
  15554. TEST(SessionVerifierTest, CertificateRejected) {
  15555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15556. ASSERT_TRUE(svr.is_valid());
  15557. svr.Get("/test", [](const Request &, Response &res) {
  15558. res.set_content("ok", "text/plain");
  15559. });
  15560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15561. auto se = detail::scope_exit([&] {
  15562. svr.stop();
  15563. t.join();
  15564. });
  15565. svr.wait_until_ready();
  15566. SSLClient cli(HOST, PORT);
  15567. cli.enable_server_certificate_verification(false);
  15568. cli.set_connection_timeout(30);
  15569. bool callback_called = false;
  15570. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15571. EXPECT_NE(session, nullptr);
  15572. callback_called = true;
  15573. return SSLVerifierResponse::CertificateRejected;
  15574. });
  15575. auto res = cli.Get("/test");
  15576. EXPECT_FALSE(res);
  15577. EXPECT_TRUE(callback_called);
  15578. }
  15579. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15581. ASSERT_TRUE(svr.is_valid());
  15582. svr.Get("/test", [](const Request &, Response &res) {
  15583. res.set_content("ok", "text/plain");
  15584. });
  15585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15586. auto se = detail::scope_exit([&] {
  15587. svr.stop();
  15588. t.join();
  15589. });
  15590. svr.wait_until_ready();
  15591. // NoDecisionMade with verification disabled should succeed (no default check)
  15592. SSLClient cli(HOST, PORT);
  15593. cli.enable_server_certificate_verification(false);
  15594. cli.set_connection_timeout(30);
  15595. bool callback_called = false;
  15596. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15597. EXPECT_NE(session, nullptr);
  15598. callback_called = true;
  15599. return SSLVerifierResponse::NoDecisionMade;
  15600. });
  15601. auto res = cli.Get("/test");
  15602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15603. EXPECT_EQ(200, res->status);
  15604. EXPECT_TRUE(callback_called);
  15605. }
  15606. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15608. ASSERT_TRUE(svr.is_valid());
  15609. svr.Get("/test", [](const Request &, Response &res) {
  15610. res.set_content("ok", "text/plain");
  15611. });
  15612. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15613. auto se = detail::scope_exit([&] {
  15614. svr.stop();
  15615. t.join();
  15616. });
  15617. svr.wait_until_ready();
  15618. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15619. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15620. // so we only check that the request fails, not whether the callback was
  15621. // called.
  15622. SSLClient cli(HOST, PORT);
  15623. cli.enable_server_certificate_verification(true);
  15624. cli.set_connection_timeout(30);
  15625. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15626. EXPECT_NE(session, nullptr);
  15627. return SSLVerifierResponse::NoDecisionMade;
  15628. });
  15629. auto res = cli.Get("/test");
  15630. EXPECT_FALSE(res);
  15631. }
  15632. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15633. // Test SSL server using PemMemory constructor with client CA certificates
  15634. // Read PEM files
  15635. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15636. read_file(SERVER_CERT_FILE, server_cert_pem);
  15637. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15638. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15639. // Create SSLServer with PemMemory constructor including client CA
  15640. SSLServer::PemMemory server_pem = {
  15641. server_cert_pem.c_str(),
  15642. server_cert_pem.size(),
  15643. server_key_pem.c_str(),
  15644. server_key_pem.size(),
  15645. client_ca_pem.c_str(),
  15646. client_ca_pem.size(),
  15647. nullptr // no password for server key
  15648. };
  15649. SSLServer svr(server_pem);
  15650. ASSERT_TRUE(svr.is_valid());
  15651. // No SSL error should be recorded for valid setup
  15652. EXPECT_EQ(0, svr.ssl_last_error());
  15653. // Set up server endpoints
  15654. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15655. res.set_content("ok", "text/plain");
  15656. });
  15657. // Start server in a thread
  15658. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15659. svr.wait_until_ready();
  15660. // Connect with client certificate (using constructor with paths)
  15661. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15662. cli.enable_server_certificate_verification(false);
  15663. auto res = cli.Get("/test-pem-ca");
  15664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15665. EXPECT_EQ(200, res->status);
  15666. EXPECT_EQ("ok", res->body);
  15667. svr.stop();
  15668. server_thread.join();
  15669. }
  15670. #endif
  15671. #ifdef _WIN32
  15672. TEST(CleanupTest, WSACleanup) {
  15673. int ret = WSACleanup();
  15674. ASSERT_EQ(0, ret);
  15675. }
  15676. #endif
  15677. #ifndef CPPHTTPLIB_SSL_ENABLED
  15678. TEST(NoSSLSupport, SimpleInterface) {
  15679. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15680. }
  15681. #endif
  15682. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15683. TEST(InvalidScheme, SimpleInterface) {
  15684. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15685. }
  15686. #endif
  15687. TEST(NoScheme, SimpleInterface) {
  15688. Client cli("yahoo.com:80");
  15689. ASSERT_TRUE(cli.is_valid());
  15690. }
  15691. TEST(SendAPI, SimpleInterface_Online) {
  15692. Client cli("http://yahoo.com");
  15693. Request req;
  15694. req.method = "GET";
  15695. req.path = "/";
  15696. auto res = cli.send(req);
  15697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15698. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15699. }
  15700. TEST(SendAPI, WithParamsInRequest) {
  15701. Server svr;
  15702. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15703. EXPECT_TRUE(req.has_param("test"));
  15704. EXPECT_EQ("test_value", req.get_param_value("test"));
  15705. });
  15706. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15707. auto se = detail::scope_exit([&] {
  15708. svr.stop();
  15709. t.join();
  15710. ASSERT_FALSE(svr.is_running());
  15711. });
  15712. svr.wait_until_ready();
  15713. Client cli(HOST, PORT);
  15714. {
  15715. Request req;
  15716. req.method = "GET";
  15717. req.path = "/";
  15718. req.params.emplace("test", "test_value");
  15719. auto res = cli.send(req);
  15720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15721. }
  15722. {
  15723. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15725. }
  15726. }
  15727. TEST(ClientImplMethods, GetSocketTest) {
  15728. httplib::Server svr;
  15729. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15730. res.status = StatusCode::OK_200;
  15731. });
  15732. auto port = svr.bind_to_any_port("127.0.0.1");
  15733. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15734. auto se = detail::scope_exit([&] {
  15735. svr.stop();
  15736. thread.join();
  15737. ASSERT_FALSE(svr.is_running());
  15738. });
  15739. svr.wait_until_ready();
  15740. {
  15741. httplib::Client cli("127.0.0.1", port);
  15742. cli.set_keep_alive(true);
  15743. // Use the behavior of cpp-httplib of opening the connection
  15744. // only when the first request happens. If that changes,
  15745. // this test would be obsolete.
  15746. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15747. // This also implicitly tests the server. But other tests would fail much
  15748. // earlier than this one to be considered.
  15749. auto res = cli.Get("/");
  15750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15751. EXPECT_EQ(StatusCode::OK_200, res->status);
  15752. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15753. }
  15754. }
  15755. #ifdef CPPHTTPLIB_SSL_ENABLED
  15756. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15757. Client cli("http://yahoo.com");
  15758. auto res = cli.Get("/");
  15759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15760. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15761. cli.set_follow_location(true);
  15762. res = cli.Get("/");
  15763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15764. EXPECT_EQ(StatusCode::OK_200, res->status);
  15765. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15766. }
  15767. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15768. Client cli("https://yahoo.com");
  15769. auto res = cli.Get("/");
  15770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15771. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15772. cli.set_follow_location(true);
  15773. res = cli.Get("/");
  15774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15775. EXPECT_EQ(StatusCode::OK_200, res->status);
  15776. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15777. }
  15778. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15779. Client cli("https://yahoo.com");
  15780. auto res = cli.Get("/");
  15781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15782. ASSERT_FALSE(!res);
  15783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15784. ASSERT_FALSE(res == nullptr);
  15785. ASSERT_TRUE(res != nullptr);
  15786. EXPECT_EQ(Error::Success, res.error());
  15787. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15788. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15789. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15790. cli.set_follow_location(true);
  15791. res = cli.Get("/");
  15792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15793. EXPECT_EQ(Error::Success, res.error());
  15794. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15795. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15796. EXPECT_EQ(StatusCode::OK_200, res->status);
  15797. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15798. }
  15799. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15800. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15801. Client cli("https://cdnjs.cloudflare.com");
  15802. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15803. Headers{{"Accept-Encoding", "br"}});
  15804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15805. EXPECT_EQ(StatusCode::OK_200, res->status);
  15806. EXPECT_EQ(287630U, res->body.size());
  15807. EXPECT_EQ("application/javascript; charset=utf-8",
  15808. res->get_header_value("Content-Type"));
  15809. }
  15810. #endif
  15811. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15812. #undef REDIR_HOST // Silence compiler warning
  15813. #define REDIR_HOST "https://httpbingo.org"
  15814. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15815. Client cli(REDIR_HOST);
  15816. cli.set_follow_location(true);
  15817. auto res =
  15818. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15820. EXPECT_EQ(StatusCode::OK_200, res->status);
  15821. }
  15822. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15823. Client cli(REDIR_HOST);
  15824. cli.set_follow_location(true);
  15825. Params params;
  15826. params.emplace("url", "http://example.com");
  15827. params.emplace("status_code", "302");
  15828. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15830. EXPECT_EQ(StatusCode::OK_200, res->status);
  15831. }
  15832. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15833. Client cli(REDIR_HOST);
  15834. cli.set_follow_location(true);
  15835. Params params;
  15836. params.emplace("url", "http://example.com");
  15837. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15839. EXPECT_EQ(StatusCode::OK_200, res->status);
  15840. }
  15841. TEST(HttpToHttpsRedirectTest, CertFile) {
  15842. auto ssl_port = PORT + 1;
  15843. Server svr;
  15844. ASSERT_TRUE(svr.is_valid());
  15845. svr.Get("/index", [&](const Request &, Response &res) {
  15846. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15847. "/index");
  15848. svr.stop();
  15849. });
  15850. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15851. ASSERT_TRUE(ssl_svr.is_valid());
  15852. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15853. res.set_content("test", "text/plain");
  15854. ssl_svr.stop();
  15855. });
  15856. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15857. thread t2 =
  15858. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15859. auto se = detail::scope_exit([&] {
  15860. t2.join();
  15861. t.join();
  15862. ASSERT_FALSE(svr.is_running());
  15863. });
  15864. svr.wait_until_ready();
  15865. ssl_svr.wait_until_ready();
  15866. Client cli("127.0.0.1", PORT);
  15867. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15868. cli.enable_server_certificate_verification(true);
  15869. cli.set_follow_location(true);
  15870. cli.set_connection_timeout(30);
  15871. auto res = cli.Get("/index");
  15872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15873. ASSERT_EQ(StatusCode::OK_200, res->status);
  15874. }
  15875. TEST(UppercaseSchemeTest, UsesTLS) {
  15876. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15877. ASSERT_TRUE(ssl_svr.is_valid());
  15878. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15879. res.set_content("test", "text/plain");
  15880. });
  15881. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15882. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15883. Server svr;
  15884. svr.Get("/index", [&](const Request &, Response &res) {
  15885. res.set_redirect(https_url + "/index");
  15886. });
  15887. auto port = svr.bind_to_any_port("127.0.0.1");
  15888. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15889. auto t2 = thread([&] { svr.listen_after_bind(); });
  15890. auto se = detail::scope_exit([&] {
  15891. svr.stop();
  15892. ssl_svr.stop();
  15893. t2.join();
  15894. t.join();
  15895. });
  15896. ssl_svr.wait_until_ready();
  15897. svr.wait_until_ready();
  15898. {
  15899. Client cli(https_url);
  15900. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15901. auto res = cli.Get("/index");
  15902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15903. EXPECT_EQ("test", res->body);
  15904. }
  15905. {
  15906. Client cli("127.0.0.1", port);
  15907. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15908. cli.set_follow_location(true);
  15909. auto res = cli.Get("/index");
  15910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15911. EXPECT_EQ("test", res->body);
  15912. }
  15913. }
  15914. TEST(SSLClientRedirectTest, CertFile) {
  15915. auto ssl_port = PORT + 1;
  15916. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15917. ASSERT_TRUE(ssl_svr1.is_valid());
  15918. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15919. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15920. "/index");
  15921. ssl_svr1.stop();
  15922. });
  15923. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15924. ASSERT_TRUE(ssl_svr2.is_valid());
  15925. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15926. res.set_content("test", "text/plain");
  15927. ssl_svr2.stop();
  15928. });
  15929. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15930. thread t2 =
  15931. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15932. auto se = detail::scope_exit([&] {
  15933. t2.join();
  15934. t.join();
  15935. ASSERT_FALSE(ssl_svr1.is_running());
  15936. });
  15937. ssl_svr1.wait_until_ready();
  15938. ssl_svr2.wait_until_ready();
  15939. SSLClient cli("127.0.0.1", PORT);
  15940. std::string cert;
  15941. read_file(SERVER_CERT2_FILE, cert);
  15942. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15943. cli.enable_server_certificate_verification(true);
  15944. cli.set_follow_location(true);
  15945. cli.set_connection_timeout(30);
  15946. auto res = cli.Get("/index");
  15947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15948. ASSERT_EQ(StatusCode::OK_200, res->status);
  15949. }
  15950. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15951. // another port, so the client follows it with a new client.
  15952. static Result GetThroughTlsRedirectToDifferentPort(
  15953. const std::function<void(SSLClient &)> &setup,
  15954. const char *target_cert = SERVER_CERT2_FILE,
  15955. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15956. auto ssl_port = PORT + 1;
  15957. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15958. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15959. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15960. "/index");
  15961. });
  15962. SSLServer ssl_svr2(target_cert, target_key);
  15963. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15964. res.set_content("test", "text/plain");
  15965. });
  15966. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15967. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15968. auto se = detail::scope_exit([&] {
  15969. ssl_svr2.stop();
  15970. ssl_svr1.stop();
  15971. t2.join();
  15972. t.join();
  15973. });
  15974. ssl_svr1.wait_until_ready();
  15975. ssl_svr2.wait_until_ready();
  15976. SSLClient cli("127.0.0.1", PORT);
  15977. cli.set_follow_location(true);
  15978. cli.set_connection_timeout(30);
  15979. setup(cli);
  15980. return cli.Get("/index");
  15981. }
  15982. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15983. auto calls = 0;
  15984. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15985. cli.enable_server_certificate_verification(false);
  15986. // Accept the first server only.
  15987. cli.set_session_verifier([&](tls::session_t) {
  15988. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15989. : SSLVerifierResponse::CertificateRejected;
  15990. });
  15991. });
  15992. ASSERT_FALSE(res);
  15993. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15994. EXPECT_EQ(2, calls);
  15995. }
  15996. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15997. std::string pinned;
  15998. auto res = GetThroughTlsRedirectToDifferentPort(
  15999. [&](SSLClient &cli) {
  16000. cli.enable_server_certificate_verification(false);
  16001. // Pin the first certificate seen.
  16002. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16003. if (pinned.empty()) { pinned = ctx.serial(); }
  16004. return ctx.serial() == pinned;
  16005. });
  16006. },
  16007. // A certificate other than the first server's.
  16008. SERVER_CERT_FILE);
  16009. EXPECT_FALSE(res);
  16010. EXPECT_FALSE(pinned.empty());
  16011. }
  16012. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16013. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16014. std::string cert;
  16015. read_file(SERVER_CERT2_FILE, cert);
  16016. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16017. });
  16018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16019. EXPECT_EQ(StatusCode::OK_200, res->status);
  16020. }
  16021. // The target's certificate is signed by the root CA, which the first server's
  16022. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16023. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16024. auto res = GetThroughTlsRedirectToDifferentPort(
  16025. [](SSLClient &cli) {
  16026. std::string root_ca, cert;
  16027. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16028. read_file(SERVER_CERT2_FILE, cert);
  16029. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16030. cli.load_ca_cert_store(cert.data(), cert.size());
  16031. cli.enable_server_hostname_verification(false);
  16032. },
  16033. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16035. EXPECT_EQ(StatusCode::OK_200, res->status);
  16036. }
  16037. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16038. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16039. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16040. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16041. auto res = GetThroughTlsRedirectToDifferentPort(
  16042. [](SSLClient &cli) {
  16043. std::string root_ca, cert;
  16044. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16045. read_file(SERVER_CERT2_FILE, cert);
  16046. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16047. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16048. cli.enable_server_hostname_verification(false);
  16049. },
  16050. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16051. ASSERT_FALSE(res);
  16052. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16053. }
  16054. #endif
  16055. #endif
  16056. #ifdef CPPHTTPLIB_SSL_ENABLED
  16057. // Test that set_ca_cert_store() skips system certs (consistent with
  16058. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16059. // should be trusted - system certs should NOT be loaded.
  16060. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16061. // Load a specific cert that is NOT a system CA cert
  16062. std::string cert;
  16063. read_file(SERVER_CERT2_FILE, cert);
  16064. SSLClient cli("google.com");
  16065. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16066. cli.enable_server_certificate_verification(true);
  16067. // This should FAIL because:
  16068. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16069. // 2. System certs should NOT be loaded when custom store is set
  16070. // If system certs WERE loaded, this would succeed
  16071. auto res = cli.Get("/");
  16072. ASSERT_FALSE(res);
  16073. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16074. }
  16075. // Same as above, but through the native store handle path. Regression test:
  16076. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16077. // merged system certs into the user-provided store.
  16078. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16079. std::string cert;
  16080. read_file(SERVER_CERT2_FILE, cert);
  16081. SSLClient cli("google.com");
  16082. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16083. cli.enable_server_certificate_verification(true);
  16084. auto res = cli.Get("/");
  16085. ASSERT_FALSE(res);
  16086. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16087. }
  16088. // A custom store set via the native handle must still verify a server whose
  16089. // cert it does contain.
  16090. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16091. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16092. ASSERT_TRUE(svr.is_valid());
  16093. svr.Get("/test", [&](const Request &, Response &res) {
  16094. res.set_content("test", "text/plain");
  16095. });
  16096. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16097. auto se = detail::scope_exit([&] {
  16098. svr.stop();
  16099. t.join();
  16100. ASSERT_FALSE(svr.is_running());
  16101. });
  16102. svr.wait_until_ready();
  16103. SSLClient cli("127.0.0.1", PORT);
  16104. std::string cert;
  16105. read_file(SERVER_CERT2_FILE, cert);
  16106. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16107. cli.enable_server_certificate_verification(true);
  16108. cli.set_connection_timeout(30);
  16109. auto res = cli.Get("/test");
  16110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16111. ASSERT_EQ(StatusCode::OK_200, res->status);
  16112. }
  16113. // CA certs loaded through the universal Client must be transferred to the
  16114. // client created internally for following an HTTPS redirect. Regression test:
  16115. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16116. // the CA data for redirect transfer.
  16117. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16118. auto ssl_port = PORT + 1;
  16119. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16120. ASSERT_TRUE(ssl_svr1.is_valid());
  16121. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16122. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16123. "/index");
  16124. });
  16125. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16126. ASSERT_TRUE(ssl_svr2.is_valid());
  16127. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16128. res.set_content("test", "text/plain");
  16129. });
  16130. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16131. thread t2 =
  16132. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16133. auto se = detail::scope_exit([&] {
  16134. ssl_svr2.stop();
  16135. ssl_svr1.stop();
  16136. t2.join();
  16137. t.join();
  16138. ASSERT_FALSE(ssl_svr1.is_running());
  16139. });
  16140. ssl_svr1.wait_until_ready();
  16141. ssl_svr2.wait_until_ready();
  16142. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16143. std::string cert;
  16144. read_file(SERVER_CERT2_FILE, cert);
  16145. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16146. cli.enable_server_certificate_verification(true);
  16147. cli.set_follow_location(true);
  16148. cli.set_connection_timeout(30);
  16149. auto res = cli.Get("/index");
  16150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16151. ASSERT_EQ(StatusCode::OK_200, res->status);
  16152. }
  16153. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16154. // so a host signed by a system CA verifies even though a custom CA is set
  16155. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16156. std::string cert;
  16157. read_file(SERVER_CERT2_FILE, cert);
  16158. SSLClient cli("google.com");
  16159. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16160. cli.enable_system_ca(true);
  16161. cli.enable_server_certificate_verification(true);
  16162. auto res = cli.Get("/");
  16163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16164. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16165. }
  16166. // The custom CA remains effective when combined with the system CA
  16167. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16168. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16169. ASSERT_TRUE(svr.is_valid());
  16170. svr.Get("/test", [&](const Request &, Response &res) {
  16171. res.set_content("test", "text/plain");
  16172. });
  16173. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16174. auto se = detail::scope_exit([&] {
  16175. svr.stop();
  16176. t.join();
  16177. ASSERT_FALSE(svr.is_running());
  16178. });
  16179. svr.wait_until_ready();
  16180. SSLClient cli("127.0.0.1", PORT);
  16181. std::string cert;
  16182. read_file(SERVER_CERT2_FILE, cert);
  16183. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16184. cli.enable_system_ca(true);
  16185. cli.enable_server_certificate_verification(true);
  16186. cli.set_connection_timeout(30);
  16187. auto res = cli.Get("/test");
  16188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16189. ASSERT_EQ(StatusCode::OK_200, res->status);
  16190. }
  16191. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16192. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16193. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16194. static CFDictionaryRef
  16195. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16196. const SecTrustSettingsResult *result) {
  16197. auto constraint =
  16198. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16199. &kCFTypeDictionaryValueCallBacks);
  16200. if (policy) {
  16201. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16202. }
  16203. if (policy_string) {
  16204. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16205. kCFStringEncodingUTF8);
  16206. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16207. CFRelease(str);
  16208. }
  16209. if (result) {
  16210. auto number_value = static_cast<SInt32>(*result);
  16211. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16212. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16213. CFRelease(number);
  16214. }
  16215. return constraint;
  16216. }
  16217. static SecTrustSettingsResult
  16218. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16219. auto trust_settings =
  16220. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16221. for (auto constraint : constraints) {
  16222. CFArrayAppendValue(trust_settings, constraint);
  16223. CFRelease(constraint);
  16224. }
  16225. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16226. CFRelease(trust_settings);
  16227. return result;
  16228. }
  16229. // The system CA loader takes a Keychain certificate as a trusted root only
  16230. // when its Trust Settings say so for SSL, not merely because it has some.
  16231. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16232. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16233. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16234. const auto deny = kSecTrustSettingsResultDeny;
  16235. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16236. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16237. auto x509_policy = SecPolicyCreateBasicX509();
  16238. // "Always Trust", which stores no constraint at all
  16239. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16240. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16241. ssl_trust_settings_result(
  16242. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16243. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16244. ssl_trust_settings_result(
  16245. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16246. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16247. ssl_trust_settings_result(
  16248. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16249. // "Never Trust", for everything or for SSL
  16250. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16251. ssl_trust_settings_result(
  16252. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16253. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16254. ssl_trust_settings_result(
  16255. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16256. // Trusted for another policy, for one host, or not at all
  16257. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16258. ssl_trust_settings_result(
  16259. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16260. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16261. ssl_trust_settings_result({make_usage_constraint(
  16262. ssl_policy, "www.example.com", &trust_root)}));
  16263. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16264. ssl_trust_settings_result(
  16265. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16266. // The first constraint that applies to SSL decides
  16267. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16268. ssl_trust_settings_result(
  16269. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16270. make_usage_constraint(nullptr, nullptr, &deny)}));
  16271. CFRelease(x509_policy);
  16272. CFRelease(ssl_policy);
  16273. }
  16274. #endif
  16275. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16276. // skip chain verification entirely (only the certificate identity was
  16277. // checked), so a server presenting an untrusted certificate with a matching
  16278. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16279. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16280. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16281. ASSERT_TRUE(svr.is_valid());
  16282. svr.Get("/test", [&](const Request &, Response &res) {
  16283. res.set_content("test", "text/plain");
  16284. });
  16285. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16286. auto se = detail::scope_exit([&] {
  16287. svr.stop();
  16288. t.join();
  16289. ASSERT_FALSE(svr.is_running());
  16290. });
  16291. svr.wait_until_ready();
  16292. SSLClient cli("127.0.0.1", PORT);
  16293. std::string cert;
  16294. // A trusted CA that did not sign the server certificate. The server cert
  16295. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16296. // this connection.
  16297. read_file(CLIENT_CA_CERT_FILE, cert);
  16298. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16299. cli.enable_server_certificate_verification(true);
  16300. cli.set_connection_timeout(30);
  16301. auto res = cli.Get("/test");
  16302. ASSERT_FALSE(res);
  16303. }
  16304. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16305. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16306. // CA that failed to come through fails verification instead of trusting them.
  16307. // (wolfSSL does not list the system CAs it loaded.)
  16308. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16309. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16310. ASSERT_TRUE(svr.is_valid());
  16311. auto port = svr.bind_to_any_port("127.0.0.1");
  16312. ASSERT_LT(0, port);
  16313. thread t = thread([&] { svr.listen_after_bind(); });
  16314. auto se = detail::scope_exit([&] {
  16315. svr.stop();
  16316. t.join();
  16317. ASSERT_FALSE(svr.is_running());
  16318. });
  16319. svr.wait_until_ready();
  16320. // The CAs a client trusts once its first request has loaded them
  16321. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16322. Client cli("https://127.0.0.1:" + std::to_string(port));
  16323. setup(cli);
  16324. cli.Get("/");
  16325. return tls::get_ca_names(cli.tls_context()).size();
  16326. };
  16327. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16328. EXPECT_EQ(0u,
  16329. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16330. }
  16331. #endif
  16332. // A TLS setting changed between requests applies to the next one, not just to
  16333. // the next connection
  16334. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16335. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16336. ASSERT_TRUE(svr.is_valid());
  16337. svr.Get("/", [](const Request &req, Response &res) {
  16338. res.set_content(std::to_string(req.remote_port), "text/plain");
  16339. });
  16340. auto port = svr.bind_to_any_port("127.0.0.1");
  16341. ASSERT_LT(0, port);
  16342. thread t = thread([&] { svr.listen_after_bind(); });
  16343. auto se = detail::scope_exit([&] {
  16344. svr.stop();
  16345. t.join();
  16346. ASSERT_FALSE(svr.is_running());
  16347. });
  16348. svr.wait_until_ready();
  16349. SSLClient cli("127.0.0.1", port);
  16350. cli.set_keep_alive(true);
  16351. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16352. cli.enable_server_certificate_verification(false);
  16353. // The port the request went out from, so a new one means a new connection
  16354. auto client_port = [&] {
  16355. auto res = cli.Get("/");
  16356. return res ? res->body : std::string();
  16357. };
  16358. auto last = client_port();
  16359. ASSERT_FALSE(last.empty());
  16360. // Setting a value it already has keeps the connection
  16361. cli.enable_server_certificate_verification(false);
  16362. cli.enable_server_hostname_verification(true);
  16363. EXPECT_EQ(last, client_port());
  16364. cli.enable_server_certificate_verification(true);
  16365. auto res = cli.Get("/");
  16366. EXPECT_FALSE(res);
  16367. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16368. std::string ca;
  16369. read_file(SERVER_CERT2_FILE, ca);
  16370. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16371. last = client_port();
  16372. ASSERT_FALSE(last.empty());
  16373. std::vector<std::function<void()>> setters = {
  16374. [&] { cli.enable_server_hostname_verification(false); },
  16375. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16376. [&] {
  16377. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16378. },
  16379. [&] {
  16380. cli.set_server_certificate_verifier(
  16381. [](const tls::VerifyContext &) { return true; });
  16382. },
  16383. [&] {
  16384. cli.set_session_verifier(
  16385. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16386. },
  16387. };
  16388. for (const auto &setter : setters) {
  16389. setter();
  16390. auto next = client_port();
  16391. ASSERT_FALSE(next.empty());
  16392. EXPECT_NE(last, next);
  16393. last = next;
  16394. }
  16395. cli.set_session_verifier(
  16396. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16397. auto handle = cli.open_stream("GET", "/");
  16398. EXPECT_FALSE(handle.is_valid());
  16399. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16400. }
  16401. // A PEM given to create_ca_store() needs no NUL after it
  16402. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16403. std::string pem;
  16404. read_file(SERVER_CERT2_FILE, pem);
  16405. auto buf = pem + "X";
  16406. auto store = tls::create_ca_store(buf.data(), pem.size());
  16407. EXPECT_TRUE(store != nullptr);
  16408. SSLClient cli("localhost");
  16409. cli.set_ca_cert_store(store);
  16410. }
  16411. // enable_system_ca(false) prevents system CA loading entirely
  16412. TEST(SSLClientTest, DisableSystemCa_Online) {
  16413. SSLClient cli("google.com");
  16414. cli.enable_system_ca(false);
  16415. cli.enable_server_certificate_verification(true);
  16416. auto res = cli.Get("/");
  16417. ASSERT_FALSE(res);
  16418. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16419. // itself when the CA chain is empty
  16420. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16421. res.error() == Error::SSLConnection);
  16422. }
  16423. // The universal Client forwards enable_system_ca()
  16424. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16425. std::string cert;
  16426. read_file(SERVER_CERT2_FILE, cert);
  16427. Client cli("https://google.com");
  16428. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16429. cli.enable_system_ca(true);
  16430. cli.enable_server_certificate_verification(true);
  16431. auto res = cli.Get("/");
  16432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16433. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16434. }
  16435. // The system CA policy must carry over to the client created internally for
  16436. // following a cross-host HTTPS redirect
  16437. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16438. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16439. ASSERT_TRUE(svr.is_valid());
  16440. svr.Get("/index", [&](const Request &, Response &res) {
  16441. res.set_redirect("https://www.google.com/");
  16442. });
  16443. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  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. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16451. std::string cert;
  16452. read_file(SERVER_CERT2_FILE, cert);
  16453. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16454. cli.enable_system_ca(true);
  16455. cli.enable_server_certificate_verification(true);
  16456. cli.set_follow_location(true);
  16457. cli.set_connection_timeout(30);
  16458. // Receiving any response proves the redirect client completed the TLS
  16459. // handshake with a system-CA-signed host
  16460. auto res = cli.Get("/index");
  16461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16462. }
  16463. TEST(MultipartFormDataTest, LargeData) {
  16464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16465. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16466. const ContentReader &content_reader) {
  16467. if (req.is_multipart_form_data()) {
  16468. std::vector<FormData> items;
  16469. content_reader(
  16470. [&](const FormData &file) {
  16471. items.push_back(file);
  16472. return true;
  16473. },
  16474. [&](const char *data, size_t data_length) {
  16475. items.back().content.append(data, data_length);
  16476. return true;
  16477. });
  16478. EXPECT_TRUE(std::string(items[0].name) == "document");
  16479. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16480. EXPECT_TRUE(items[0].filename == "2MB_data");
  16481. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16482. EXPECT_TRUE(items[1].name == "hello");
  16483. EXPECT_TRUE(items[1].content == "world");
  16484. EXPECT_TRUE(items[1].filename == "");
  16485. EXPECT_TRUE(items[1].content_type == "");
  16486. } else {
  16487. std::string body;
  16488. content_reader([&](const char *data, size_t data_length) {
  16489. body.append(data, data_length);
  16490. return true;
  16491. });
  16492. }
  16493. });
  16494. auto port = svr.bind_to_any_port(HOST);
  16495. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16496. auto se = detail::scope_exit([&] {
  16497. svr.stop();
  16498. t.join();
  16499. ASSERT_FALSE(svr.is_running());
  16500. });
  16501. svr.wait_until_ready();
  16502. {
  16503. std::string data(1024 * 1024 * 2, '.');
  16504. std::stringstream buffer;
  16505. buffer << data;
  16506. SSLClient cli(HOST, port);
  16507. cli.enable_server_certificate_verification(false);
  16508. UploadFormDataItems items{
  16509. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16510. {"hello", "world", "", ""},
  16511. };
  16512. auto res = cli.Post("/post", items);
  16513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16514. ASSERT_EQ(StatusCode::OK_200, res->status);
  16515. }
  16516. }
  16517. TEST(MultipartFormDataTest, DataProviderItems) {
  16518. std::random_device seed_gen;
  16519. std::mt19937 random(seed_gen());
  16520. std::string rand1;
  16521. rand1.resize(1000);
  16522. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16523. std::string rand2;
  16524. rand2.resize(3000);
  16525. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16526. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16527. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16528. const ContentReader &content_reader) {
  16529. ASSERT_FALSE(req.is_multipart_form_data());
  16530. std::string body;
  16531. content_reader([&](const char *data, size_t data_length) {
  16532. body.append(data, data_length);
  16533. return true;
  16534. });
  16535. EXPECT_EQ(body, "");
  16536. });
  16537. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16538. const ContentReader &content_reader) {
  16539. ASSERT_TRUE(req.is_multipart_form_data());
  16540. std::vector<FormData> items;
  16541. content_reader(
  16542. [&](const FormData &file) {
  16543. items.push_back(file);
  16544. return true;
  16545. },
  16546. [&](const char *data, size_t data_length) {
  16547. items.back().content.append(data, data_length);
  16548. return true;
  16549. });
  16550. ASSERT_TRUE(items.size() == 2);
  16551. EXPECT_EQ(std::string(items[0].name), "name1");
  16552. EXPECT_EQ(items[0].content, "Testing123");
  16553. EXPECT_EQ(items[0].filename, "filename1");
  16554. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16555. EXPECT_EQ(items[1].name, "name2");
  16556. EXPECT_EQ(items[1].content, "Testing456");
  16557. EXPECT_EQ(items[1].filename, "");
  16558. EXPECT_EQ(items[1].content_type, "");
  16559. });
  16560. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16561. const ContentReader &content_reader) {
  16562. ASSERT_TRUE(req.is_multipart_form_data());
  16563. std::vector<FormData> items;
  16564. content_reader(
  16565. [&](const FormData &file) {
  16566. items.push_back(file);
  16567. return true;
  16568. },
  16569. [&](const char *data, size_t data_length) {
  16570. items.back().content.append(data, data_length);
  16571. return true;
  16572. });
  16573. ASSERT_TRUE(items.size() == 2);
  16574. EXPECT_EQ(items[0].name, "name3");
  16575. EXPECT_EQ(items[0].content, rand1);
  16576. EXPECT_EQ(items[0].filename, "filename3");
  16577. EXPECT_EQ(items[0].content_type, "");
  16578. EXPECT_EQ(items[1].name, "name4");
  16579. EXPECT_EQ(items[1].content, rand2);
  16580. EXPECT_EQ(items[1].filename, "filename4");
  16581. EXPECT_EQ(items[1].content_type, "");
  16582. });
  16583. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16584. const ContentReader &content_reader) {
  16585. ASSERT_TRUE(req.is_multipart_form_data());
  16586. std::vector<FormData> items;
  16587. content_reader(
  16588. [&](const FormData &file) {
  16589. items.push_back(file);
  16590. return true;
  16591. },
  16592. [&](const char *data, size_t data_length) {
  16593. items.back().content.append(data, data_length);
  16594. return true;
  16595. });
  16596. ASSERT_TRUE(items.size() == 4);
  16597. EXPECT_EQ(std::string(items[0].name), "name1");
  16598. EXPECT_EQ(items[0].content, "Testing123");
  16599. EXPECT_EQ(items[0].filename, "filename1");
  16600. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16601. EXPECT_EQ(items[1].name, "name2");
  16602. EXPECT_EQ(items[1].content, "Testing456");
  16603. EXPECT_EQ(items[1].filename, "");
  16604. EXPECT_EQ(items[1].content_type, "");
  16605. EXPECT_EQ(items[2].name, "name3");
  16606. EXPECT_EQ(items[2].content, rand1);
  16607. EXPECT_EQ(items[2].filename, "filename3");
  16608. EXPECT_EQ(items[2].content_type, "");
  16609. EXPECT_EQ(items[3].name, "name4");
  16610. EXPECT_EQ(items[3].content, rand2);
  16611. EXPECT_EQ(items[3].filename, "filename4");
  16612. EXPECT_EQ(items[3].content_type, "");
  16613. });
  16614. auto port = svr.bind_to_any_port("localhost");
  16615. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16616. auto se = detail::scope_exit([&] {
  16617. svr.stop();
  16618. t.join();
  16619. ASSERT_FALSE(svr.is_running());
  16620. });
  16621. svr.wait_until_ready();
  16622. {
  16623. SSLClient cli("localhost", port);
  16624. cli.enable_server_certificate_verification(false);
  16625. UploadFormDataItems items{
  16626. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16627. {"name2", "Testing456", "", ""}, // not a file
  16628. };
  16629. {
  16630. auto res = cli.Post("/post-none", {}, {}, {});
  16631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16632. ASSERT_EQ(StatusCode::OK_200, res->status);
  16633. }
  16634. FormDataProviderItems providers;
  16635. {
  16636. auto res =
  16637. cli.Post("/post-items", {}, items, providers); // empty providers
  16638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16639. ASSERT_EQ(StatusCode::OK_200, res->status);
  16640. }
  16641. providers.push_back({"name3",
  16642. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16643. // test the offset is given correctly at each step
  16644. if (!offset)
  16645. sink.os.write(rand1.data(), 30);
  16646. else if (offset == 30)
  16647. sink.os.write(rand1.data() + 30, 300);
  16648. else if (offset == 330)
  16649. sink.os.write(rand1.data() + 330, 670);
  16650. else if (offset == rand1.size())
  16651. sink.done();
  16652. return true;
  16653. },
  16654. "filename3",
  16655. {}});
  16656. providers.push_back({"name4",
  16657. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16658. // test the offset is given correctly at each step
  16659. if (!offset)
  16660. sink.os.write(rand2.data(), 2000);
  16661. else if (offset == 2000)
  16662. sink.os.write(rand2.data() + 2000, 1);
  16663. else if (offset == 2001)
  16664. sink.os.write(rand2.data() + 2001, 999);
  16665. else if (offset == rand2.size())
  16666. sink.done();
  16667. return true;
  16668. },
  16669. "filename4",
  16670. {}});
  16671. {
  16672. auto res = cli.Post("/post-providers", {}, {}, providers);
  16673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16674. ASSERT_EQ(StatusCode::OK_200, res->status);
  16675. }
  16676. {
  16677. auto res = cli.Post("/post-both", {}, items, providers);
  16678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16679. ASSERT_EQ(StatusCode::OK_200, res->status);
  16680. }
  16681. }
  16682. }
  16683. TEST(MultipartFormDataTest, BadHeader) {
  16684. Server svr;
  16685. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16686. res.set_content("ok", "text/plain");
  16687. });
  16688. thread t = thread([&] { svr.listen(HOST, PORT); });
  16689. auto se = detail::scope_exit([&] {
  16690. svr.stop();
  16691. t.join();
  16692. ASSERT_FALSE(svr.is_running());
  16693. });
  16694. svr.wait_until_ready();
  16695. const std::string body =
  16696. "This is the preamble. It is to be ignored, though it\r\n"
  16697. "is a handy place for composition agents to include an\r\n"
  16698. "explanatory note to non-MIME conformant readers.\r\n"
  16699. "\r\n"
  16700. "\r\n"
  16701. "--simple boundary\r\n"
  16702. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16703. ": BAD...\r\n"
  16704. "\r\n"
  16705. "value1\r\n"
  16706. "--simple boundary\r\n"
  16707. "Content-Disposition: form-data; name=\"field2\"; "
  16708. "filename=\"example.txt\"\r\n"
  16709. "\r\n"
  16710. "value2\r\n"
  16711. "--simple boundary--\r\n"
  16712. "This is the epilogue. It is also to be ignored.\r\n";
  16713. std::string content_type =
  16714. R"(multipart/form-data; boundary="simple boundary")";
  16715. Client cli(HOST, PORT);
  16716. auto res = cli.Post("/post", body, content_type.c_str());
  16717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16718. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16719. }
  16720. TEST(MultipartFormDataTest, WithPreamble) {
  16721. Server svr;
  16722. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16723. res.set_content("ok", "text/plain");
  16724. });
  16725. thread t = thread([&] { svr.listen(HOST, PORT); });
  16726. auto se = detail::scope_exit([&] {
  16727. svr.stop();
  16728. t.join();
  16729. ASSERT_FALSE(svr.is_running());
  16730. });
  16731. svr.wait_until_ready();
  16732. const std::string body =
  16733. "This is the preamble. It is to be ignored, though it\r\n"
  16734. "is a handy place for composition agents to include an\r\n"
  16735. "explanatory note to non-MIME conformant readers.\r\n"
  16736. "\r\n"
  16737. "\r\n"
  16738. "--simple boundary\r\n"
  16739. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16740. "\r\n"
  16741. "value1\r\n"
  16742. "--simple boundary\r\n"
  16743. "Content-Disposition: form-data; name=\"field2\"; "
  16744. "filename=\"example.txt\"\r\n"
  16745. "\r\n"
  16746. "value2\r\n"
  16747. "--simple boundary--\r\n"
  16748. "This is the epilogue. It is also to be ignored.\r\n";
  16749. std::string content_type =
  16750. R"(multipart/form-data; boundary="simple boundary")";
  16751. Client cli(HOST, PORT);
  16752. auto res = cli.Post("/post", body, content_type.c_str());
  16753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16754. EXPECT_EQ(StatusCode::OK_200, res->status);
  16755. }
  16756. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16758. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16759. const ContentReader &content_reader) {
  16760. if (req.is_multipart_form_data()) {
  16761. std::vector<FormData> items;
  16762. content_reader(
  16763. [&](const FormData &file) {
  16764. items.push_back(file);
  16765. return true;
  16766. },
  16767. [&](const char *data, size_t data_length) {
  16768. items.back().content.append(data, data_length);
  16769. return true;
  16770. });
  16771. EXPECT_TRUE(std::string(items[0].name) == "document");
  16772. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16773. EXPECT_TRUE(items[0].filename == "2MB_data");
  16774. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16775. EXPECT_TRUE(items[1].name == "hello");
  16776. EXPECT_TRUE(items[1].content == "world");
  16777. EXPECT_TRUE(items[1].filename == "");
  16778. EXPECT_TRUE(items[1].content_type == "");
  16779. } else {
  16780. std::string body;
  16781. content_reader([&](const char *data, size_t data_length) {
  16782. body.append(data, data_length);
  16783. return true;
  16784. });
  16785. }
  16786. });
  16787. auto port = svr.bind_to_any_port("localhost");
  16788. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16789. auto se = detail::scope_exit([&] {
  16790. svr.stop();
  16791. t.join();
  16792. ASSERT_FALSE(svr.is_running());
  16793. });
  16794. svr.wait_until_ready();
  16795. {
  16796. std::string data(1024 * 1024 * 2, '.');
  16797. std::stringstream buffer;
  16798. buffer << data;
  16799. SSLClient cli("localhost", port);
  16800. cli.enable_server_certificate_verification(false);
  16801. UploadFormDataItems items{
  16802. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16803. {"hello", "world", "", ""},
  16804. };
  16805. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16807. ASSERT_EQ(StatusCode::OK_200, res->status);
  16808. }
  16809. }
  16810. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16811. std::string data(1024 * 1024 * 2, '&');
  16812. std::stringstream buffer;
  16813. buffer << data;
  16814. Client cli("https://localhost:8080");
  16815. UploadFormDataItems items{
  16816. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16817. {"hello", "world", "", ""},
  16818. };
  16819. for (const char &c : " \t\r\n") {
  16820. auto res =
  16821. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16822. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16823. ASSERT_FALSE(res);
  16824. }
  16825. }
  16826. TEST(MultipartFormDataTest, PutFormData) {
  16827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16828. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16829. const ContentReader &content_reader) {
  16830. if (req.is_multipart_form_data()) {
  16831. std::vector<FormData> items;
  16832. content_reader(
  16833. [&](const FormData &file) {
  16834. items.push_back(file);
  16835. return true;
  16836. },
  16837. [&](const char *data, size_t data_length) {
  16838. items.back().content.append(data, data_length);
  16839. return true;
  16840. });
  16841. EXPECT_TRUE(std::string(items[0].name) == "document");
  16842. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16843. EXPECT_TRUE(items[0].filename == "2MB_data");
  16844. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16845. EXPECT_TRUE(items[1].name == "hello");
  16846. EXPECT_TRUE(items[1].content == "world");
  16847. EXPECT_TRUE(items[1].filename == "");
  16848. EXPECT_TRUE(items[1].content_type == "");
  16849. } else {
  16850. std::string body;
  16851. content_reader([&](const char *data, size_t data_length) {
  16852. body.append(data, data_length);
  16853. return true;
  16854. });
  16855. }
  16856. });
  16857. auto port = svr.bind_to_any_port("localhost");
  16858. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16859. auto se = detail::scope_exit([&] {
  16860. svr.stop();
  16861. t.join();
  16862. ASSERT_FALSE(svr.is_running());
  16863. });
  16864. svr.wait_until_ready();
  16865. {
  16866. std::string data(1024 * 1024 * 2, '&');
  16867. std::stringstream buffer;
  16868. buffer << data;
  16869. SSLClient cli("localhost", port);
  16870. cli.enable_server_certificate_verification(false);
  16871. UploadFormDataItems items{
  16872. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16873. {"hello", "world", "", ""},
  16874. };
  16875. auto res = cli.Put("/put", items);
  16876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16877. ASSERT_EQ(StatusCode::OK_200, res->status);
  16878. }
  16879. }
  16880. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16882. svr.Put("/put_customboundary",
  16883. [&](const Request &req, const Response & /*res*/,
  16884. const ContentReader &content_reader) {
  16885. if (req.is_multipart_form_data()) {
  16886. std::vector<FormData> items;
  16887. content_reader(
  16888. [&](const FormData &file) {
  16889. items.push_back(file);
  16890. return true;
  16891. },
  16892. [&](const char *data, size_t data_length) {
  16893. items.back().content.append(data, data_length);
  16894. return true;
  16895. });
  16896. EXPECT_TRUE(std::string(items[0].name) == "document");
  16897. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16898. EXPECT_TRUE(items[0].filename == "2MB_data");
  16899. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16900. EXPECT_TRUE(items[1].name == "hello");
  16901. EXPECT_TRUE(items[1].content == "world");
  16902. EXPECT_TRUE(items[1].filename == "");
  16903. EXPECT_TRUE(items[1].content_type == "");
  16904. } else {
  16905. std::string body;
  16906. content_reader([&](const char *data, size_t data_length) {
  16907. body.append(data, data_length);
  16908. return true;
  16909. });
  16910. }
  16911. });
  16912. auto port = svr.bind_to_any_port("localhost");
  16913. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16914. auto se = detail::scope_exit([&] {
  16915. svr.stop();
  16916. t.join();
  16917. ASSERT_FALSE(svr.is_running());
  16918. });
  16919. svr.wait_until_ready();
  16920. {
  16921. std::string data(1024 * 1024 * 2, '&');
  16922. std::stringstream buffer;
  16923. buffer << data;
  16924. SSLClient cli("localhost", port);
  16925. cli.enable_server_certificate_verification(false);
  16926. UploadFormDataItems items{
  16927. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16928. {"hello", "world", "", ""},
  16929. };
  16930. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16932. ASSERT_EQ(StatusCode::OK_200, res->status);
  16933. }
  16934. }
  16935. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16936. std::string data(1024 * 1024 * 2, '&');
  16937. std::stringstream buffer;
  16938. buffer << data;
  16939. Client cli("https://localhost:8080");
  16940. cli.enable_server_certificate_verification(false);
  16941. UploadFormDataItems items{
  16942. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16943. {"hello", "world", "", ""},
  16944. };
  16945. for (const char &c : " \t\r\n") {
  16946. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16947. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16948. ASSERT_FALSE(res);
  16949. }
  16950. }
  16951. TEST(MultipartFormDataTest, AlternateFilename) {
  16952. auto handled = false;
  16953. Server svr;
  16954. svr.Post("/test", [&](const Request &req, Response &res) {
  16955. ASSERT_EQ(2u, req.form.files.size());
  16956. ASSERT_EQ(1u, req.form.fields.size());
  16957. // Test files
  16958. const auto &file1 = req.form.get_file("file1");
  16959. ASSERT_EQ("file1", file1.name);
  16960. ASSERT_EQ("A.txt", file1.filename);
  16961. ASSERT_EQ("text/plain", file1.content_type);
  16962. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16963. const auto &file2 = req.form.get_file("file2");
  16964. ASSERT_EQ("file2", file2.name);
  16965. ASSERT_EQ("a.html", file2.filename);
  16966. ASSERT_EQ("text/html", file2.content_type);
  16967. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16968. file2.content);
  16969. // Test text field
  16970. const auto &text = req.form.get_field("text");
  16971. ASSERT_EQ("text default", text);
  16972. res.set_content("ok", "text/plain");
  16973. handled = true;
  16974. });
  16975. thread t = thread([&] { svr.listen(HOST, PORT); });
  16976. auto se = detail::scope_exit([&] {
  16977. svr.stop();
  16978. t.join();
  16979. ASSERT_FALSE(svr.is_running());
  16980. ASSERT_TRUE(handled);
  16981. });
  16982. svr.wait_until_ready();
  16983. auto req = "POST /test HTTP/1.1\r\n"
  16984. "Host: localhost\r\n"
  16985. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16986. "Content-Length: 399\r\n"
  16987. "\r\n"
  16988. "----------\r\n"
  16989. "Content-Disposition: form-data; name=\"text\"\r\n"
  16990. "\r\n"
  16991. "text default\r\n"
  16992. "----------\r\n"
  16993. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16994. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16995. "Content-Type: text/plain\r\n"
  16996. "\r\n"
  16997. "Content of a.txt.\r\n"
  16998. "\r\n"
  16999. "----------\r\n"
  17000. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17001. "\"a.html\"\r\n"
  17002. "Content-Type: text/html\r\n"
  17003. "\r\n"
  17004. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17005. "\r\n"
  17006. "------------\r\n";
  17007. ASSERT_TRUE(send_request(1, req));
  17008. }
  17009. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17010. auto handled = false;
  17011. Server svr;
  17012. svr.Post("/test", [&](const Request &req, Response &res) {
  17013. // Case-insensitive "utf-8''" prefix with a long value
  17014. const auto &file = req.form.get_file("file1");
  17015. ASSERT_EQ("file1", file.name);
  17016. // 8000 chars exercises both the Content-Disposition parser and the
  17017. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17018. // Prior to the fix, std::regex_match on this header would cause O(N)
  17019. // stack recursion in libstdc++, leading to SIGSEGV.
  17020. std::string expected_filename(8000, 'A');
  17021. ASSERT_EQ(expected_filename, file.filename);
  17022. res.set_content("ok", "text/plain");
  17023. handled = true;
  17024. });
  17025. thread t = thread([&] { svr.listen(HOST, PORT); });
  17026. auto se = detail::scope_exit([&] {
  17027. svr.stop();
  17028. t.join();
  17029. ASSERT_FALSE(svr.is_running());
  17030. ASSERT_TRUE(handled);
  17031. });
  17032. svr.wait_until_ready();
  17033. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17034. // Regression test for GHSA-qq6v-r583-3h69
  17035. std::string long_filename(8000, 'A');
  17036. std::string body = "----------\r\n"
  17037. "Content-Disposition: form-data; name=\"file1\"; "
  17038. "filename*=\"Utf-8''" +
  17039. long_filename +
  17040. "\"\r\n"
  17041. "\r\n"
  17042. "hello\r\n"
  17043. "------------\r\n";
  17044. auto req = "POST /test HTTP/1.1\r\n"
  17045. "Host: localhost\r\n"
  17046. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17047. "Content-Length: " +
  17048. std::to_string(body.size()) + "\r\n\r\n" + body;
  17049. ASSERT_TRUE(send_request(1, req));
  17050. }
  17051. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17052. auto handled = false;
  17053. Server svr;
  17054. svr.Post("/test", [&](const Request &req, Response &) {
  17055. ASSERT_EQ(2u, req.form.fields.size());
  17056. const auto &text1 = req.form.get_field("text1");
  17057. ASSERT_EQ("text1", text1);
  17058. const auto &text2 = req.form.get_field("text2");
  17059. ASSERT_EQ("text2", text2);
  17060. handled = true;
  17061. });
  17062. thread t = thread([&] { svr.listen(HOST, PORT); });
  17063. auto se = detail::scope_exit([&] {
  17064. svr.stop();
  17065. t.join();
  17066. ASSERT_FALSE(svr.is_running());
  17067. ASSERT_TRUE(handled);
  17068. });
  17069. svr.wait_until_ready();
  17070. auto req = "POST /test HTTP/1.1\r\n"
  17071. "Host: localhost\r\n"
  17072. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17073. "Content-Length: 146\r\n"
  17074. "\r\n----------\r\n"
  17075. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17076. "\r\n"
  17077. "text1"
  17078. "\r\n----------\r\n"
  17079. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17080. "\r\n"
  17081. "text2"
  17082. "\r\n------------";
  17083. std::string response;
  17084. ASSERT_TRUE(send_request(1, req, &response));
  17085. ASSERT_EQ("200", response.substr(9, 3));
  17086. }
  17087. TEST(MultipartFormDataTest, ContentLength) {
  17088. auto handled = false;
  17089. Server svr;
  17090. svr.Post("/test", [&](const Request &req, Response &) {
  17091. ASSERT_EQ(2u, req.form.fields.size());
  17092. const auto &text1 = req.form.get_field("text1");
  17093. ASSERT_EQ("text1", text1);
  17094. const auto &text2 = req.form.get_field("text2");
  17095. ASSERT_EQ("text2", text2);
  17096. handled = true;
  17097. });
  17098. thread t = thread([&] { svr.listen(HOST, PORT); });
  17099. auto se = detail::scope_exit([&] {
  17100. svr.stop();
  17101. t.join();
  17102. ASSERT_FALSE(svr.is_running());
  17103. ASSERT_TRUE(handled);
  17104. });
  17105. svr.wait_until_ready();
  17106. auto req = "POST /test HTTP/1.1\r\n"
  17107. "Host: localhost\r\n"
  17108. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17109. "Content-Length: 167\r\n"
  17110. "\r\n----------\r\n"
  17111. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17112. "Content-Length: 5\r\n"
  17113. "\r\n"
  17114. "text1"
  17115. "\r\n----------\r\n"
  17116. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17117. "\r\n"
  17118. "text2"
  17119. "\r\n------------\r\n";
  17120. std::string response;
  17121. ASSERT_TRUE(send_request(1, req, &response));
  17122. ASSERT_EQ("200", response.substr(9, 3));
  17123. }
  17124. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17125. auto handled = false;
  17126. Server svr;
  17127. svr.Post("/test", [&](const Request &req, Response &) {
  17128. ASSERT_EQ(2u, req.form.fields.size());
  17129. const auto &text1 = req.form.get_field("text1");
  17130. ASSERT_EQ("text1", text1);
  17131. // TODO: Add header access for text fields if needed
  17132. const auto &text2 = req.form.get_field("text2");
  17133. ASSERT_EQ("text2", text2);
  17134. // TODO: Header access for text fields needs to be implemented
  17135. // auto &headers = it->second.headers;
  17136. // ASSERT_EQ(3U, headers.size());
  17137. // auto custom_header = headers.find("x-whatever");
  17138. // ASSERT_TRUE(custom_header != headers.end());
  17139. // ASSERT_NE("customvalue", custom_header->second);
  17140. // ASSERT_EQ("CustomValue", custom_header->second);
  17141. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17142. handled = true;
  17143. });
  17144. thread t = thread([&] { svr.listen(HOST, PORT); });
  17145. auto se = detail::scope_exit([&] {
  17146. svr.stop();
  17147. t.join();
  17148. ASSERT_FALSE(svr.is_running());
  17149. ASSERT_TRUE(handled);
  17150. });
  17151. svr.wait_until_ready();
  17152. auto req = "POST /test HTTP/1.1\r\n"
  17153. "Host: localhost\r\n"
  17154. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17155. "Content-Length: 232\r\n"
  17156. "\r\n----------\r\n"
  17157. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17158. "Content-Length: 5\r\n"
  17159. "X-Test: 1\r\n"
  17160. "\r\n"
  17161. "text1"
  17162. "\r\n----------\r\n"
  17163. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17164. "Content-Type: text/plain\r\n"
  17165. "X-Whatever: CustomValue\r\n"
  17166. "\r\n"
  17167. "text2"
  17168. "\r\n------------\r\n"
  17169. "That should be disregarded. Not even read";
  17170. std::string response;
  17171. ASSERT_TRUE(send_request(1, req, &response));
  17172. ASSERT_EQ("200", response.substr(9, 3));
  17173. }
  17174. TEST(MultipartFormDataTest, LargeHeader) {
  17175. auto handled = false;
  17176. Server svr;
  17177. svr.Post("/test", [&](const Request &req, Response &) {
  17178. ASSERT_EQ(1u, req.form.fields.size());
  17179. const auto &text = req.form.get_field("name1");
  17180. ASSERT_EQ("text1", text);
  17181. handled = true;
  17182. });
  17183. thread t = thread([&] { svr.listen(HOST, PORT); });
  17184. auto se = detail::scope_exit([&] {
  17185. svr.stop();
  17186. t.join();
  17187. ASSERT_FALSE(svr.is_running());
  17188. ASSERT_TRUE(handled);
  17189. });
  17190. svr.wait_until_ready();
  17191. auto boundary = std::string("cpp-httplib-multipart-data");
  17192. std::string content = "--" + boundary +
  17193. "\r\n"
  17194. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17195. "\r\n"
  17196. "text1\r\n"
  17197. "--" +
  17198. boundary + "--\r\n";
  17199. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17200. "Host: localhost\r\n"
  17201. "Content-Type: multipart/form-data;boundary=" +
  17202. boundary +
  17203. "\r\n"
  17204. "Content-Length: " +
  17205. std::to_string(content.size()) +
  17206. "\r\n"
  17207. "Dummy-Header: ";
  17208. std::string header_suffix = "\r\n"
  17209. "\r\n";
  17210. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17211. size_t header_dummy_size =
  17212. read_buff_size -
  17213. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17214. auto header_dummy = std::string(header_dummy_size, '@');
  17215. auto req = header_prefix + header_dummy + header_suffix + content;
  17216. std::string response;
  17217. ASSERT_TRUE(send_request(1, req, &response));
  17218. ASSERT_EQ("200", response.substr(9, 3));
  17219. }
  17220. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17221. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17222. // (not chunked Transfer-Encoding) after the streaming refactor.
  17223. auto handled = false;
  17224. Server svr;
  17225. svr.Post("/upload", [&](const Request &req, Response &res) {
  17226. auto cl_it = req.headers.find("Content-Length");
  17227. EXPECT_TRUE(cl_it != req.headers.end());
  17228. auto te_it = req.headers.find("Transfer-Encoding");
  17229. EXPECT_TRUE(te_it == req.headers.end());
  17230. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17231. res.set_content("ok", "text/plain");
  17232. handled = true;
  17233. });
  17234. auto port = svr.bind_to_any_port(HOST);
  17235. auto t = thread([&] { svr.listen_after_bind(); });
  17236. auto se = detail::scope_exit([&] {
  17237. svr.stop();
  17238. t.join();
  17239. ASSERT_FALSE(svr.is_running());
  17240. ASSERT_TRUE(handled);
  17241. });
  17242. svr.wait_until_ready();
  17243. UploadFormDataItems items = {
  17244. {"field1", "hello", "", "text/plain"},
  17245. {"file1", "world", "test.txt", "application/octet-stream"},
  17246. };
  17247. Client cli(HOST, port);
  17248. auto res = cli.Post("/upload", {}, items);
  17249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17250. EXPECT_EQ(StatusCode::OK_200, res->status);
  17251. }
  17252. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17253. // Verify that make_multipart_content_provider coalesces many small segments
  17254. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17255. constexpr size_t kItemCount = 1000;
  17256. UploadFormDataItems items;
  17257. items.reserve(kItemCount);
  17258. for (size_t i = 0; i < kItemCount; i++) {
  17259. items.push_back(
  17260. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17261. }
  17262. const std::string boundary = "----test-boundary";
  17263. auto content_length = detail::get_multipart_content_length(items, boundary);
  17264. auto provider = detail::make_multipart_content_provider(items, boundary);
  17265. // Drive the provider the same way write_content_with_progress does
  17266. size_t write_count = 0;
  17267. size_t total_bytes = 0;
  17268. DataSink sink;
  17269. size_t offset = 0;
  17270. sink.write = [&](const char *d, size_t l) -> bool {
  17271. (void)d;
  17272. write_count++;
  17273. total_bytes += l;
  17274. offset += l;
  17275. return true;
  17276. };
  17277. sink.is_writable = []() -> bool { return true; };
  17278. while (offset < content_length) {
  17279. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17280. }
  17281. EXPECT_EQ(content_length, total_bytes);
  17282. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17283. // With buffering into 64KB blocks, write_count should be much smaller.
  17284. auto segment_count = 3 * kItemCount + 1;
  17285. EXPECT_LT(write_count, segment_count / 10);
  17286. }
  17287. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17288. // Integration test: send many UploadFormDataItems and verify the server
  17289. // receives all of them correctly (#2410).
  17290. constexpr size_t kItemCount = 500;
  17291. auto handled = false;
  17292. Server svr;
  17293. svr.Post("/upload", [&](const Request &req, Response &res) {
  17294. EXPECT_EQ(kItemCount, req.form.fields.size());
  17295. for (size_t i = 0; i < kItemCount; i++) {
  17296. auto key = "field" + std::to_string(i);
  17297. auto val = "value" + std::to_string(i);
  17298. auto it = req.form.fields.find(key);
  17299. if (it != req.form.fields.end()) {
  17300. EXPECT_EQ(val, it->second.content);
  17301. } else {
  17302. ADD_FAILURE() << "Missing field: " << key;
  17303. }
  17304. }
  17305. res.set_content("ok", "text/plain");
  17306. handled = true;
  17307. });
  17308. auto port = svr.bind_to_any_port(HOST);
  17309. auto t = thread([&] { svr.listen_after_bind(); });
  17310. auto se = detail::scope_exit([&] {
  17311. svr.stop();
  17312. t.join();
  17313. ASSERT_FALSE(svr.is_running());
  17314. ASSERT_TRUE(handled);
  17315. });
  17316. svr.wait_until_ready();
  17317. UploadFormDataItems items;
  17318. items.reserve(kItemCount);
  17319. for (size_t i = 0; i < kItemCount; i++) {
  17320. items.push_back(
  17321. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17322. }
  17323. Client cli(HOST, port);
  17324. auto res = cli.Post("/upload", items);
  17325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17326. EXPECT_EQ(StatusCode::OK_200, res->status);
  17327. }
  17328. TEST(MultipartFormDataTest, MakeFileProvider) {
  17329. // Verify make_file_provider sends a file's contents correctly.
  17330. const std::string file_content(4096, 'Z');
  17331. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17332. {
  17333. std::ofstream ofs(tmp_path, std::ios::binary);
  17334. ofs.write(file_content.data(),
  17335. static_cast<std::streamsize>(file_content.size()));
  17336. }
  17337. auto handled = false;
  17338. Server svr;
  17339. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17340. const ContentReader &content_reader) {
  17341. ASSERT_TRUE(req.is_multipart_form_data());
  17342. std::vector<FormData> items;
  17343. content_reader(
  17344. [&](const FormData &file) {
  17345. items.push_back(file);
  17346. return true;
  17347. },
  17348. [&](const char *data, size_t data_length) {
  17349. items.back().content.append(data, data_length);
  17350. return true;
  17351. });
  17352. ASSERT_EQ(1u, items.size());
  17353. EXPECT_EQ("myfile", items[0].name);
  17354. EXPECT_EQ("data.bin", items[0].filename);
  17355. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17356. EXPECT_EQ(file_content, items[0].content);
  17357. handled = true;
  17358. });
  17359. auto port = svr.bind_to_any_port(HOST);
  17360. auto t = thread([&] { svr.listen_after_bind(); });
  17361. auto se = detail::scope_exit([&] {
  17362. svr.stop();
  17363. t.join();
  17364. ASSERT_FALSE(svr.is_running());
  17365. ASSERT_TRUE(handled);
  17366. std::remove(tmp_path.c_str());
  17367. });
  17368. svr.wait_until_ready();
  17369. FormDataProviderItems providers;
  17370. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17371. "application/octet-stream"));
  17372. Client cli(HOST, port);
  17373. auto res = cli.Post("/upload", {}, {}, providers);
  17374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17375. EXPECT_EQ(StatusCode::OK_200, res->status);
  17376. }
  17377. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17378. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17379. // (100) headers is rejected with a 400 Bad Request response.
  17380. Server svr;
  17381. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17382. res.set_content("ok", "text/plain");
  17383. });
  17384. thread t = thread([&] { svr.listen(HOST, PORT); });
  17385. auto se = detail::scope_exit([&] {
  17386. svr.stop();
  17387. t.join();
  17388. ASSERT_FALSE(svr.is_running());
  17389. });
  17390. svr.wait_until_ready();
  17391. // Build a multipart part with 101 custom headers (exceeding
  17392. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17393. std::stringstream body;
  17394. body << "--simpleboundary\r\n"
  17395. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17396. for (int i = 0; i < 101; i++) {
  17397. body << "X-Custom-Header-" << i << ": value\r\n";
  17398. }
  17399. body << "\r\n"
  17400. << "value1\r\n"
  17401. << "--simpleboundary--\r\n";
  17402. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17403. Client cli(HOST, PORT);
  17404. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17406. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17407. }
  17408. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17409. // A body that never contains the declared boundary must not be accumulated
  17410. // while the parser waits for it. Buffering it would also make every read
  17411. // rescan everything seen so far, which is quadratic in the body size.
  17412. Server svr;
  17413. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17414. res.set_content("ok", "text/plain");
  17415. });
  17416. auto port = svr.bind_to_any_port(HOST);
  17417. thread t = thread([&] { svr.listen_after_bind(); });
  17418. auto se = detail::scope_exit([&] {
  17419. svr.stop();
  17420. t.join();
  17421. ASSERT_FALSE(svr.is_running());
  17422. });
  17423. svr.wait_until_ready();
  17424. Client cli(HOST, port);
  17425. cli.set_read_timeout(60, 0);
  17426. cli.set_write_timeout(60, 0);
  17427. // '-' is the worst case: it matches the first character of the boundary, so
  17428. // every position has to be checked against it.
  17429. auto post_dashes = [&](size_t size) {
  17430. const std::string body(size, '-');
  17431. auto start = std::chrono::steady_clock::now();
  17432. auto res =
  17433. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17434. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17435. std::chrono::steady_clock::now() - start)
  17436. .count();
  17437. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17438. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17439. return ms;
  17440. };
  17441. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17442. // Windows.
  17443. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17444. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17445. // Comparing the two sizes rather than checking an absolute duration keeps
  17446. // this meaningful across build types and CI load, both of which move the
  17447. // absolute numbers by more than an order of magnitude. Four times the bytes
  17448. // costs about four times the time when parsing is linear, and about sixteen
  17449. // times when the body is buffered and rescanned.
  17450. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17451. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17452. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17453. << "ms, which suggests the body is being buffered and rescanned";
  17454. }
  17455. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17456. // A boundary can only be followed by CRLF or by "--", so anything else is
  17457. // malformed no matter what comes next. The parser must say so right away
  17458. // instead of buffering the rest of the declared body.
  17459. Server svr;
  17460. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17461. res.set_content("ok", "text/plain");
  17462. });
  17463. auto port = svr.bind_to_any_port(HOST);
  17464. thread t = thread([&] { svr.listen_after_bind(); });
  17465. auto se = detail::scope_exit([&] {
  17466. svr.stop();
  17467. t.join();
  17468. ASSERT_FALSE(svr.is_running());
  17469. });
  17470. svr.wait_until_ready();
  17471. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17472. // buffers instead of failing would still be waiting for the remaining bytes.
  17473. const std::string body = "--zzzz\r\n"
  17474. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17475. "\r\n"
  17476. "text1"
  17477. "\r\n--zzzzXX";
  17478. const std::string req = "POST /post HTTP/1.1\r\n"
  17479. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17480. "Content-Length: 1048576\r\n"
  17481. "\r\n" +
  17482. body;
  17483. std::string response;
  17484. ASSERT_TRUE(send_request(3, req, &response, port));
  17485. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17486. EXPECT_EQ("400", response.substr(9, 3));
  17487. }
  17488. // Posts a multipart body split into two writes, so that the server sees the
  17489. // split at whatever offset the caller chose, and expects the single "text1"
  17490. // field to come through.
  17491. static void expect_split_multipart_ok(const std::string &body1,
  17492. const std::string &body2) {
  17493. auto handled = false;
  17494. Server svr;
  17495. svr.Post("/post", [&](const Request &req, Response &) {
  17496. EXPECT_EQ(1u, req.form.fields.size());
  17497. EXPECT_EQ("text1", req.form.get_field("text1"));
  17498. handled = true;
  17499. });
  17500. auto port = svr.bind_to_any_port(HOST);
  17501. thread t = thread([&] { svr.listen_after_bind(); });
  17502. auto se = detail::scope_exit([&] {
  17503. svr.stop();
  17504. t.join();
  17505. ASSERT_FALSE(svr.is_running());
  17506. ASSERT_TRUE(handled);
  17507. });
  17508. svr.wait_until_ready();
  17509. // "Connection: close" makes the server close once it has answered, so the
  17510. // response drain ends immediately instead of idling until the read timeout.
  17511. const std::string head =
  17512. "POST /post HTTP/1.1\r\n"
  17513. "Host: localhost\r\n"
  17514. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17515. "Connection: close\r\n"
  17516. "Content-Length: " +
  17517. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17518. std::string response;
  17519. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17520. ASSERT_GE(response.size(), 12u) << "no response";
  17521. EXPECT_EQ("200", response.substr(9, 3));
  17522. }
  17523. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17524. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17525. // ignored, including when it does not arrive in the same read as the
  17526. // close-delimiter itself.
  17527. expect_split_multipart_ok("--zzzz\r\n"
  17528. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17529. "\r\n"
  17530. "text1"
  17531. "\r\n--zzzz--",
  17532. "\r\nthis epilogue must be ignored\r\n");
  17533. }
  17534. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17535. // The initial boundary may be preceded by a preamble of any length and may
  17536. // straddle a read boundary. Discarding data while waiting for it must not
  17537. // throw away a partial boundary sitting at the end of the buffer.
  17538. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17539. "zz\r\n"
  17540. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17541. "\r\n"
  17542. "text1"
  17543. "\r\n--zzzz--\r\n");
  17544. }
  17545. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17546. // The received boundary was only checked for being non-empty, so it could be
  17547. // as long as a header is allowed to be. The parser scans the body for
  17548. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17549. // costs a nearly full comparison at nearly every position, making the
  17550. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17551. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17552. Server svr;
  17553. svr.Post("/post", [](const Request &req, Response &res) {
  17554. EXPECT_EQ(1u, req.form.fields.size());
  17555. EXPECT_EQ("text1", req.form.get_field("text1"));
  17556. res.set_content("ok", "text/plain");
  17557. });
  17558. auto port = svr.bind_to_any_port(HOST);
  17559. thread t = thread([&] { svr.listen_after_bind(); });
  17560. auto se = detail::scope_exit([&] {
  17561. svr.stop();
  17562. t.join();
  17563. ASSERT_FALSE(svr.is_running());
  17564. });
  17565. svr.wait_until_ready();
  17566. Client cli(HOST, port);
  17567. auto post_with_boundary_of_length = [&](size_t len) {
  17568. const std::string boundary(len, 'a');
  17569. const std::string body =
  17570. "--" + boundary +
  17571. "\r\n"
  17572. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17573. "\r\n"
  17574. "text1"
  17575. "\r\n--" +
  17576. boundary + "--\r\n";
  17577. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17578. };
  17579. auto res = post_with_boundary_of_length(70);
  17580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17581. EXPECT_EQ(StatusCode::OK_200, res->status);
  17582. res = post_with_boundary_of_length(71);
  17583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17584. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17585. }
  17586. TEST(MakeFileBodyTest, Basic) {
  17587. const std::string file_content(4096, 'Z');
  17588. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17589. {
  17590. std::ofstream ofs(tmp_path, std::ios::binary);
  17591. ofs.write(file_content.data(),
  17592. static_cast<std::streamsize>(file_content.size()));
  17593. }
  17594. auto handled = false;
  17595. Server svr;
  17596. svr.Post("/upload", [&](const Request &req, Response &res) {
  17597. EXPECT_EQ(file_content, req.body);
  17598. handled = true;
  17599. res.status = StatusCode::OK_200;
  17600. });
  17601. auto port = svr.bind_to_any_port(HOST);
  17602. auto 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. std::remove(tmp_path.c_str());
  17609. });
  17610. svr.wait_until_ready();
  17611. auto fb = make_file_body(tmp_path);
  17612. ASSERT_GT(fb.first, 0u);
  17613. Client cli(HOST, port);
  17614. auto res =
  17615. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17617. EXPECT_EQ(StatusCode::OK_200, res->status);
  17618. }
  17619. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17620. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17621. {
  17622. std::ofstream ofs(path, std::ios::binary);
  17623. const std::string content(100, 'A');
  17624. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17625. }
  17626. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17627. auto body = make_file_body(path);
  17628. ASSERT_EQ(100u, body.first);
  17629. ASSERT_TRUE(static_cast<bool>(body.second));
  17630. // Rewritten shorter after its length was measured - and, on a server, after
  17631. // that length has already gone out as Content-Length.
  17632. {
  17633. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17634. const std::string content(10, 'A');
  17635. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17636. }
  17637. std::string written;
  17638. DataSink sink;
  17639. sink.write = [&](const char *d, size_t l) {
  17640. written.append(d, l);
  17641. return true;
  17642. };
  17643. // The provider has to report failure. write_content_with_progress() advances
  17644. // its offset only by what was written, so a provider that returns true
  17645. // without completing the length it promised is called again straight away,
  17646. // and again.
  17647. EXPECT_FALSE(body.second(0, body.first, sink));
  17648. EXPECT_EQ(std::string(10, 'A'), written);
  17649. }
  17650. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17651. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17652. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17653. {
  17654. std::ofstream ofs(path, std::ios::binary);
  17655. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17656. }
  17657. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17658. auto body = make_file_body(path);
  17659. ASSERT_EQ(content.size(), body.first);
  17660. ASSERT_TRUE(static_cast<bool>(body.second));
  17661. std::string written;
  17662. DataSink sink;
  17663. sink.write = [&](const char *d, size_t l) {
  17664. written.append(d, l);
  17665. return true;
  17666. };
  17667. EXPECT_TRUE(body.second(0, body.first, sink));
  17668. EXPECT_EQ(content, written);
  17669. }
  17670. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17671. static constexpr unsigned int number_of_tasks{1000000};
  17672. std::atomic_uint count{0};
  17673. std::unique_ptr<TaskQueue> task_queue{
  17674. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17675. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17676. auto queued = task_queue->enqueue(
  17677. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17678. EXPECT_TRUE(queued);
  17679. }
  17680. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17681. task_queue->shutdown();
  17682. #else
  17683. EXPECT_NO_THROW(task_queue->shutdown());
  17684. #endif
  17685. EXPECT_EQ(number_of_tasks, count.load());
  17686. }
  17687. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17688. static constexpr unsigned int number_of_tasks{1000000};
  17689. static constexpr unsigned int qlimit{2};
  17690. unsigned int queued_count{0};
  17691. std::atomic_uint count{0};
  17692. std::unique_ptr<TaskQueue> task_queue{
  17693. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17694. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17695. if (task_queue->enqueue(
  17696. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17697. queued_count++;
  17698. }
  17699. }
  17700. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17701. task_queue->shutdown();
  17702. #else
  17703. EXPECT_NO_THROW(task_queue->shutdown());
  17704. #endif
  17705. EXPECT_EQ(queued_count, count.load());
  17706. EXPECT_TRUE(queued_count <= number_of_tasks);
  17707. EXPECT_TRUE(queued_count >= qlimit);
  17708. }
  17709. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17710. // Use a short idle timeout so a dynamic thread spawns, times out and
  17711. // exits during the test, and the pool keeps working afterwards.
  17712. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17713. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17714. /*idle_timeout_sec=*/1}};
  17715. std::atomic_uint count{0};
  17716. std::condition_variable cv;
  17717. std::mutex mtx;
  17718. bool release = false;
  17719. // Block the base thread so the second task spawns a dynamic thread.
  17720. EXPECT_TRUE(task_queue->enqueue([&] {
  17721. std::unique_lock<std::mutex> lock(mtx);
  17722. while (!release) {
  17723. cv.wait(lock);
  17724. }
  17725. count++;
  17726. }));
  17727. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17728. // Let the dynamic thread finish its task and exceed the idle timeout.
  17729. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17730. {
  17731. std::unique_lock<std::mutex> lock(mtx);
  17732. release = true;
  17733. }
  17734. cv.notify_all();
  17735. // The pool must still accept and run tasks after the dynamic thread exited.
  17736. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17737. task_queue->shutdown();
  17738. EXPECT_EQ(3u, count.load());
  17739. }
  17740. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17741. static constexpr size_t number_of_tasks{32};
  17742. std::unique_ptr<TaskQueue> task_queue{
  17743. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17744. // Let the base threads go idle so the burst below finds them waiting.
  17745. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17746. std::mutex mtx;
  17747. std::condition_variable cv;
  17748. size_t running = 0;
  17749. bool release = false;
  17750. for (size_t i = 0; i < number_of_tasks; i++) {
  17751. EXPECT_TRUE(task_queue->enqueue([&] {
  17752. std::unique_lock<std::mutex> lock(mtx);
  17753. running++;
  17754. cv.notify_all();
  17755. cv.wait(lock, [&] { return release; });
  17756. }));
  17757. }
  17758. {
  17759. std::unique_lock<std::mutex> lock(mtx);
  17760. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17761. [&] { return running == number_of_tasks; }));
  17762. release = true;
  17763. }
  17764. cv.notify_all();
  17765. task_queue->shutdown();
  17766. }
  17767. TEST(TaskQueueTest, MaxQueuedRequests) {
  17768. static constexpr unsigned int qlimit{3};
  17769. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17770. std::condition_variable sem_cv;
  17771. std::mutex sem_mtx;
  17772. int credits = 0;
  17773. bool queued;
  17774. /* Fill up the queue with tasks that will block until we give them credits to
  17775. * complete. */
  17776. for (unsigned int n = 0; n <= qlimit;) {
  17777. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17778. std::unique_lock<std::mutex> lock(sem_mtx);
  17779. while (credits <= 0) {
  17780. sem_cv.wait(lock);
  17781. }
  17782. /* Consume the credit and signal the test code if they are all gone. */
  17783. if (--credits == 0) { sem_cv.notify_one(); }
  17784. });
  17785. if (n < qlimit) {
  17786. /* The first qlimit enqueues must succeed. */
  17787. EXPECT_TRUE(queued);
  17788. } else {
  17789. /* The last one will succeed only when the worker thread
  17790. * starts and dequeues the first blocking task. Although
  17791. * not necessary for the correctness of this test, we sleep for
  17792. * a short while to avoid busy waiting. */
  17793. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17794. }
  17795. if (queued) { n++; }
  17796. }
  17797. /* Further enqueues must fail since the queue is full. */
  17798. for (auto i = 0; i < 4; i++) {
  17799. queued = task_queue->enqueue([] {});
  17800. EXPECT_FALSE(queued);
  17801. }
  17802. /* Give the credits to allow the previous tasks to complete. */
  17803. {
  17804. std::unique_lock<std::mutex> lock(sem_mtx);
  17805. credits += qlimit + 1;
  17806. }
  17807. sem_cv.notify_all();
  17808. /* Wait for all the credits to be consumed. */
  17809. {
  17810. std::unique_lock<std::mutex> lock(sem_mtx);
  17811. while (credits > 0) {
  17812. sem_cv.wait(lock);
  17813. }
  17814. }
  17815. /* Check that we are able again to enqueue at least qlimit tasks. */
  17816. for (unsigned int i = 0; i < qlimit; i++) {
  17817. queued = task_queue->enqueue([] {});
  17818. EXPECT_TRUE(queued);
  17819. }
  17820. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17821. task_queue->shutdown();
  17822. #else
  17823. EXPECT_NO_THROW(task_queue->shutdown());
  17824. #endif
  17825. }
  17826. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17827. Server svr;
  17828. std::string method;
  17829. std::string body;
  17830. auto has_content_length = false;
  17831. auto has_transfer_encoding = false;
  17832. std::atomic<int> bad_requests{0};
  17833. // Leftover body bytes get parsed as a malformed request and answered with
  17834. // 400
  17835. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17836. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17837. });
  17838. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17839. res.set_redirect("/down", StatusCode::SeeOther_303);
  17840. });
  17841. svr.Get("/down", [&](const Request &req, Response &res) {
  17842. method = req.method;
  17843. body = req.body;
  17844. has_content_length = req.has_header("Content-Length");
  17845. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17846. res.set_content("ok", "text/plain");
  17847. });
  17848. auto port = svr.bind_to_any_port(HOST);
  17849. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17850. auto se = detail::scope_exit([&] {
  17851. svr.stop();
  17852. thread.join();
  17853. ASSERT_FALSE(svr.is_running());
  17854. });
  17855. svr.wait_until_ready();
  17856. const std::string payload = "SECRET-BODY";
  17857. auto check = [&](Client &cli, const Result &res) {
  17858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17859. EXPECT_EQ(StatusCode::OK_200, res->status);
  17860. EXPECT_EQ("ok", res->body);
  17861. EXPECT_EQ("GET", method);
  17862. EXPECT_TRUE(body.empty());
  17863. EXPECT_FALSE(has_content_length);
  17864. EXPECT_FALSE(has_transfer_encoding);
  17865. // Nothing of the original body may be left on the connection
  17866. auto res2 = cli.Get("/down");
  17867. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17868. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17869. EXPECT_EQ("ok", res2->body);
  17870. EXPECT_EQ(0, bad_requests);
  17871. };
  17872. // With content length
  17873. {
  17874. Client cli(HOST, port);
  17875. cli.set_keep_alive(true);
  17876. cli.set_follow_location(true);
  17877. auto res = cli.Post(
  17878. "/up", payload.size(),
  17879. [&](size_t offset, size_t length, DataSink &sink) {
  17880. return sink.write(payload.data() + offset, length);
  17881. },
  17882. "text/plain");
  17883. check(cli, res);
  17884. }
  17885. // Without content length (chunked)
  17886. {
  17887. Client cli(HOST, port);
  17888. cli.set_keep_alive(true);
  17889. cli.set_follow_location(true);
  17890. auto res = cli.Post(
  17891. "/up",
  17892. [&](size_t /*offset*/, DataSink &sink) {
  17893. sink.write(payload.data(), payload.size());
  17894. sink.done();
  17895. return true;
  17896. },
  17897. "text/plain");
  17898. check(cli, res);
  17899. }
  17900. }
  17901. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17902. Server svr;
  17903. std::string target;
  17904. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17905. // Echo the still-encoded name back in the Location
  17906. const std::string prefix = "/start/";
  17907. res.status = StatusCode::Found_302;
  17908. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17909. });
  17910. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17911. target = req.target;
  17912. res.set_content("ok", "text/plain");
  17913. });
  17914. auto port = svr.bind_to_any_port(HOST);
  17915. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17916. auto se = detail::scope_exit([&] {
  17917. svr.stop();
  17918. thread.join();
  17919. ASSERT_FALSE(svr.is_running());
  17920. });
  17921. svr.wait_until_ready();
  17922. // Decoding the Location path would turn the first four into a path
  17923. // separator, a query delimiter, a fragment delimiter and a different
  17924. // percent-encoded octet. The rest must keep reaching the server as they are.
  17925. const std::vector<std::string> names = {
  17926. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17927. };
  17928. for (auto path_encode : {true, false}) {
  17929. Client cli(HOST, port);
  17930. cli.set_follow_location(true);
  17931. cli.set_path_encode(path_encode);
  17932. for (const auto &name : names) {
  17933. target.clear();
  17934. auto res = cli.Get("/start/" + name);
  17935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17936. EXPECT_EQ(StatusCode::OK_200, res->status);
  17937. EXPECT_EQ("/dest/" + name, target);
  17938. }
  17939. }
  17940. }
  17941. TEST(RedirectTest, NotModifiedIsReturned) {
  17942. Server svr;
  17943. svr.Get("/cached", [](const Request &, Response &res) {
  17944. res.status = StatusCode::NotModified_304;
  17945. });
  17946. auto port = svr.bind_to_any_port(HOST);
  17947. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17948. auto se = detail::scope_exit([&] {
  17949. svr.stop();
  17950. thread.join();
  17951. ASSERT_FALSE(svr.is_running());
  17952. });
  17953. svr.wait_until_ready();
  17954. Client cli(HOST, port);
  17955. cli.set_follow_location(true);
  17956. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17958. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17959. }
  17960. TEST(RedirectTest, NoLocationIsReturned) {
  17961. Server svr;
  17962. svr.Get("/no-location", [](const Request &, Response &res) {
  17963. res.status = StatusCode::Found_302;
  17964. res.set_content("no location", "text/plain");
  17965. });
  17966. auto port = svr.bind_to_any_port(HOST);
  17967. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17968. auto se = detail::scope_exit([&] {
  17969. svr.stop();
  17970. thread.join();
  17971. ASSERT_FALSE(svr.is_running());
  17972. });
  17973. svr.wait_until_ready();
  17974. Client cli(HOST, port);
  17975. cli.set_follow_location(true);
  17976. auto res = cli.Get("/no-location");
  17977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17978. EXPECT_EQ(StatusCode::Found_302, res->status);
  17979. EXPECT_EQ("no location", res->body);
  17980. // The callbacks see the body of the response that is returned
  17981. auto handler_called = false;
  17982. auto progress_called = false;
  17983. std::string body;
  17984. auto res2 = cli.Get(
  17985. "/no-location",
  17986. [&](const Response &) {
  17987. handler_called = true;
  17988. return true;
  17989. },
  17990. [&](const char *data, size_t data_length) {
  17991. body.append(data, data_length);
  17992. return true;
  17993. },
  17994. [&](size_t, size_t) {
  17995. progress_called = true;
  17996. return true;
  17997. });
  17998. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17999. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18000. EXPECT_TRUE(handler_called);
  18001. EXPECT_TRUE(progress_called);
  18002. EXPECT_EQ("no location", body);
  18003. }
  18004. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18005. Server svr;
  18006. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18007. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18008. });
  18009. svr.Get("/hello", [](const Request &req, Response &res) {
  18010. res.set_content(req.get_param_value("key"), "text/plain");
  18011. });
  18012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18013. auto se = detail::scope_exit([&] {
  18014. svr.stop();
  18015. thread.join();
  18016. ASSERT_FALSE(svr.is_running());
  18017. });
  18018. svr.wait_until_ready();
  18019. {
  18020. Client cli(HOST, PORT);
  18021. cli.set_follow_location(true);
  18022. auto res = cli.Get("/");
  18023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18024. EXPECT_EQ(StatusCode::OK_200, res->status);
  18025. EXPECT_EQ("val&key2=val2", res->body);
  18026. }
  18027. }
  18028. #endif
  18029. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18030. Server svr;
  18031. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18032. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18033. });
  18034. svr.Get("/hello", [](const Request &req, Response &res) {
  18035. res.set_content(req.get_param_value("key"), "text/plain");
  18036. });
  18037. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18038. auto se = detail::scope_exit([&] {
  18039. svr.stop();
  18040. thread.join();
  18041. ASSERT_FALSE(svr.is_running());
  18042. });
  18043. svr.wait_until_ready();
  18044. {
  18045. Client cli(HOST, PORT);
  18046. cli.set_follow_location(true);
  18047. auto res = cli.Get("/");
  18048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18049. EXPECT_EQ(StatusCode::OK_200, res->status);
  18050. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18051. }
  18052. }
  18053. TEST(RedirectTest, RedirectWithPlusInPath) {
  18054. Server svr;
  18055. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18056. res.set_redirect("/a+b");
  18057. });
  18058. // Route pattern uses regex; escape + as \\+
  18059. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18060. res.set_content(req.path, "text/plain");
  18061. });
  18062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18063. auto se = detail::scope_exit([&] {
  18064. svr.stop();
  18065. thread.join();
  18066. ASSERT_FALSE(svr.is_running());
  18067. });
  18068. svr.wait_until_ready();
  18069. {
  18070. Client cli(HOST, PORT);
  18071. cli.set_follow_location(true);
  18072. auto res = cli.Get("/");
  18073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18074. EXPECT_EQ(StatusCode::OK_200, res->status);
  18075. EXPECT_EQ("/a+b", res->body);
  18076. }
  18077. }
  18078. TEST(RedirectTest, ResolveRelativeLocation) {
  18079. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18080. const std::vector<std::pair<std::string, std::string>> cases = {
  18081. {"g", "/b/c/g"},
  18082. {"./g", "/b/c/g"},
  18083. {"g/", "/b/c/g/"},
  18084. {"?y", "/b/c/d;p?y"},
  18085. {"g?y", "/b/c/g?y"},
  18086. {"#s", "/b/c/d;p?q#s"},
  18087. {"g#s", "/b/c/g#s"},
  18088. {"g?y#s", "/b/c/g?y#s"},
  18089. {";x", "/b/c/;x"},
  18090. {"g;x", "/b/c/g;x"},
  18091. {".", "/b/c/"},
  18092. {"./", "/b/c/"},
  18093. {"..", "/b/"},
  18094. {"../", "/b/"},
  18095. {"../g", "/b/g"},
  18096. {"../..", "/"},
  18097. {"../../", "/"},
  18098. {"../../g", "/g"},
  18099. {"../../../g", "/g"},
  18100. {"g.", "/b/c/g."},
  18101. {".g", "/b/c/.g"},
  18102. {"g..", "/b/c/g.."},
  18103. {"..g", "/b/c/..g"},
  18104. {"./../g", "/b/g"},
  18105. {"./g/.", "/b/c/g/"},
  18106. {"g/./h", "/b/c/g/h"},
  18107. {"g/../h", "/b/c/h"},
  18108. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18109. {"g;x=1/../y", "/b/c/y"},
  18110. {"g?y/./x", "/b/c/g?y/./x"},
  18111. {"g#s/../x", "/b/c/g#s/../x"},
  18112. // Not relative-path references, so left for parse_url.
  18113. {"/g", "/g"},
  18114. {"//g", "//g"},
  18115. {"http://g/x", "http://g/x"},
  18116. {"g:h", "g:h"},
  18117. };
  18118. for (const auto &c : cases) {
  18119. EXPECT_EQ(c.second,
  18120. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18121. << c.first;
  18122. }
  18123. // A result starting with "//" is still a path, not a network-path reference
  18124. EXPECT_EQ("/.//g",
  18125. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18126. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18127. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18128. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18129. }
  18130. TEST(RedirectTest, RemoveDotSegments) {
  18131. // RFC 3986 section 5.2.4
  18132. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18133. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18134. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18135. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18136. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18137. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18138. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18139. }
  18140. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18141. Server svr;
  18142. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18143. res.set_redirect("/dir/../target?x=1");
  18144. });
  18145. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18146. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18147. "/dir/./../target");
  18148. });
  18149. svr.Get("/target", [](const Request &req, Response &res) {
  18150. res.set_content(req.path, "text/plain");
  18151. });
  18152. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18153. auto se = detail::scope_exit([&] {
  18154. svr.stop();
  18155. th.join();
  18156. ASSERT_FALSE(svr.is_running());
  18157. });
  18158. svr.wait_until_ready();
  18159. Client cli("localhost", PORT);
  18160. cli.set_follow_location(true);
  18161. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18162. auto res = cli.Get(path);
  18163. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18164. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18165. EXPECT_EQ("/target", res->body) << path;
  18166. }
  18167. }
  18168. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18169. Server svr;
  18170. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18171. res.set_redirect(req.get_param_value("to"));
  18172. });
  18173. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18174. res.set_content(req.target, "text/plain");
  18175. });
  18176. svr.Get("/other", [](const Request &req, Response &res) {
  18177. res.set_content(req.target, "text/plain");
  18178. });
  18179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18180. auto se = detail::scope_exit([&] {
  18181. svr.stop();
  18182. thread.join();
  18183. ASSERT_FALSE(svr.is_running());
  18184. });
  18185. svr.wait_until_ready();
  18186. const std::vector<std::pair<std::string, std::string>> cases = {
  18187. {"next", "/dir/next"},
  18188. {"./next?x=1", "/dir/next?x=1"},
  18189. {"../other", "/other"},
  18190. };
  18191. for (const auto &c : cases) {
  18192. Client cli(HOST, PORT);
  18193. cli.set_follow_location(true);
  18194. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18195. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18196. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18197. EXPECT_EQ(c.second, res->body) << c.first;
  18198. }
  18199. }
  18200. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18201. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18202. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18203. Server other;
  18204. std::atomic<int> other_hits{0};
  18205. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18206. other_hits++;
  18207. res.set_content("other", "text/plain");
  18208. });
  18209. auto other_port = other.bind_to_any_port("127.0.0.1");
  18210. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18211. Server svr;
  18212. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18213. res.set_redirect(req.get_param_value("to"));
  18214. });
  18215. svr.Get(".*", [](const Request &req, Response &res) {
  18216. res.set_content(req.path, "text/plain");
  18217. });
  18218. auto port = svr.bind_to_any_port(HOST);
  18219. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18220. auto se = detail::scope_exit([&] {
  18221. svr.stop();
  18222. thread.join();
  18223. other.stop();
  18224. other_thread.join();
  18225. ASSERT_FALSE(svr.is_running());
  18226. ASSERT_FALSE(other.is_running());
  18227. });
  18228. svr.wait_until_ready();
  18229. other.wait_until_ready();
  18230. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18231. for (const auto &to :
  18232. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18233. Client cli(HOST, port);
  18234. cli.set_follow_location(true);
  18235. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18236. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18237. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18238. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18239. }
  18240. EXPECT_EQ(0, other_hits.load());
  18241. }
  18242. #ifdef CPPHTTPLIB_SSL_ENABLED
  18243. TEST(RedirectTest, Issue2185_Online) {
  18244. SSLClient client("github.com");
  18245. client.set_follow_location(true);
  18246. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18247. "Coollab-Windows.zip");
  18248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18249. EXPECT_EQ(StatusCode::OK_200, res->status);
  18250. EXPECT_EQ(9920427U, res->body.size());
  18251. }
  18252. #endif
  18253. TEST(VulnerabilityTest, CRLFInjection) {
  18254. Server svr;
  18255. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18256. res.set_content("Hello 1", "text/plain");
  18257. });
  18258. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18259. res.set_content("Hello 2", "text/plain");
  18260. });
  18261. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18262. res.set_content("Hello 3", "text/plain");
  18263. });
  18264. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18265. res.set_content("Hello 4", "text/plain");
  18266. });
  18267. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18268. for (const auto &x : req.headers) {
  18269. auto key = x.first;
  18270. EXPECT_STRNE("evil", key.c_str());
  18271. }
  18272. });
  18273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18274. auto se = detail::scope_exit([&] {
  18275. svr.stop();
  18276. thread.join();
  18277. ASSERT_FALSE(svr.is_running());
  18278. });
  18279. svr.wait_until_ready();
  18280. {
  18281. Client cli(HOST, PORT);
  18282. cli.Post("/test1", "A=B",
  18283. "application/x-www-form-urlencoded\r\nevil: hello1");
  18284. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18285. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18286. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18287. }
  18288. }
  18289. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18290. auto server_thread = std::thread([] {
  18291. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18292. default_socket_options(srv);
  18293. sockaddr_in addr{};
  18294. addr.sin_family = AF_INET;
  18295. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18296. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18297. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18298. ::listen(srv, 1);
  18299. sockaddr_in cli_addr{};
  18300. socklen_t cli_len = sizeof(cli_addr);
  18301. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18302. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18303. std::string buf_all;
  18304. char buf[2048];
  18305. ssize_t n;
  18306. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18307. buf_all.append(buf, static_cast<size_t>(n));
  18308. size_t pos;
  18309. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18310. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18311. auto e = request_block.find("\r\n");
  18312. if (e != std::string::npos) {
  18313. auto request_line = request_block.substr(0, e);
  18314. std::string msg =
  18315. "CRLF injection detected in request line: '" + request_line + "'";
  18316. EXPECT_FALSE(true) << msg;
  18317. }
  18318. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18319. ::send(cli,
  18320. #ifdef _WIN32
  18321. static_cast<const char *>(resp.c_str()),
  18322. static_cast<int>(resp.size()),
  18323. #else
  18324. resp.c_str(), resp.size(),
  18325. #endif
  18326. 0);
  18327. buf_all.erase(0, pos + 4);
  18328. }
  18329. }
  18330. detail::close_socket(cli);
  18331. detail::close_socket(srv);
  18332. });
  18333. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18334. auto cli = Client("127.0.0.1", PORT + 1);
  18335. auto headers = Headers{
  18336. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18337. {"Connection", "keep-alive"}};
  18338. auto res = cli.Get("/hi", headers);
  18339. EXPECT_FALSE(res);
  18340. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18341. server_thread.join();
  18342. }
  18343. // A request rejected before any byte reaches the socket must fail right away
  18344. // instead of waiting for a response the server will never send.
  18345. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18346. // The kernel completes the TCP handshake from the listen backlog, so the
  18347. // client connects, but nothing ever reads, responds or closes.
  18348. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18349. default_socket_options(srv);
  18350. sockaddr_in addr{};
  18351. addr.sin_family = AF_INET;
  18352. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18353. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18354. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18355. ASSERT_EQ(0, ::listen(srv, 8));
  18356. auto cli = Client("127.0.0.1", PORT + 1);
  18357. cli.set_read_timeout(10, 0);
  18358. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18359. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18360. std::chrono::steady_clock::now() - start)
  18361. .count();
  18362. };
  18363. {
  18364. Request req;
  18365. req.method = "GE T";
  18366. req.path = "/";
  18367. auto start = std::chrono::steady_clock::now();
  18368. auto res = cli.send(req);
  18369. EXPECT_FALSE(res);
  18370. EXPECT_EQ(Error::Write, res.error());
  18371. EXPECT_LT(elapsed_ms(start), 1000);
  18372. }
  18373. {
  18374. auto start = std::chrono::steady_clock::now();
  18375. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18376. EXPECT_FALSE(res);
  18377. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18378. EXPECT_LT(elapsed_ms(start), 1000);
  18379. }
  18380. EXPECT_FALSE(cli.is_socket_open());
  18381. detail::close_socket(srv);
  18382. }
  18383. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18384. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18385. default_socket_options(srv);
  18386. sockaddr_in addr{};
  18387. addr.sin_family = AF_INET;
  18388. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18389. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18390. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18391. ASSERT_EQ(0, ::listen(srv, 1));
  18392. std::string received;
  18393. auto server_thread = std::thread([&] {
  18394. auto sock = ::accept(srv, nullptr, nullptr);
  18395. if (sock == INVALID_SOCKET) { return; }
  18396. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18397. char buf[2048];
  18398. ssize_t n;
  18399. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18400. received.append(buf, static_cast<size_t>(n));
  18401. }
  18402. detail::close_socket(sock);
  18403. });
  18404. {
  18405. auto cli = Client("127.0.0.1", PORT + 1);
  18406. // "Z" sorts after the default headers, so writing straight to the socket
  18407. // would have sent the request line and those headers before the rejection.
  18408. auto handle =
  18409. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18410. EXPECT_FALSE(handle.is_valid());
  18411. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18412. }
  18413. server_thread.join();
  18414. detail::close_socket(srv);
  18415. EXPECT_TRUE(received.empty()) << received;
  18416. }
  18417. TEST(PathParamsTest, StaticMatch) {
  18418. const auto pattern = "/users/all";
  18419. detail::PathParamsMatcher matcher(pattern);
  18420. Request request;
  18421. request.path = "/users/all";
  18422. ASSERT_TRUE(matcher.match(request));
  18423. std::unordered_map<std::string, std::string> expected_params = {};
  18424. EXPECT_EQ(request.path_params, expected_params);
  18425. }
  18426. TEST(PathParamsTest, StaticMismatch) {
  18427. const auto pattern = "/users/all";
  18428. detail::PathParamsMatcher matcher(pattern);
  18429. Request request;
  18430. request.path = "/users/1";
  18431. ASSERT_FALSE(matcher.match(request));
  18432. }
  18433. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18434. const auto pattern = "/users/:id/subscriptions";
  18435. detail::PathParamsMatcher matcher(pattern);
  18436. Request request;
  18437. request.path = "/users/42/subscriptions";
  18438. ASSERT_TRUE(matcher.match(request));
  18439. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18440. EXPECT_EQ(request.path_params, expected_params);
  18441. }
  18442. TEST(PathParamsTest, SingleParamInTheEnd) {
  18443. const auto pattern = "/users/:id";
  18444. detail::PathParamsMatcher matcher(pattern);
  18445. Request request;
  18446. request.path = "/users/24";
  18447. ASSERT_TRUE(matcher.match(request));
  18448. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18449. EXPECT_EQ(request.path_params, expected_params);
  18450. }
  18451. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18452. const auto pattern = "/users/:id/";
  18453. detail::PathParamsMatcher matcher(pattern);
  18454. Request request;
  18455. request.path = "/users/42/";
  18456. ASSERT_TRUE(matcher.match(request));
  18457. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18458. EXPECT_EQ(request.path_params, expected_params);
  18459. }
  18460. TEST(PathParamsTest, EmptyParam) {
  18461. const auto pattern = "/users/:id/";
  18462. detail::PathParamsMatcher matcher(pattern);
  18463. Request request;
  18464. request.path = "/users//";
  18465. ASSERT_TRUE(matcher.match(request));
  18466. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18467. EXPECT_EQ(request.path_params, expected_params);
  18468. }
  18469. TEST(PathParamsTest, FragmentMismatch) {
  18470. const auto pattern = "/users/:id/";
  18471. detail::PathParamsMatcher matcher(pattern);
  18472. Request request;
  18473. request.path = "/admins/24/";
  18474. ASSERT_FALSE(matcher.match(request));
  18475. }
  18476. TEST(PathParamsTest, ExtraFragments) {
  18477. const auto pattern = "/users/:id";
  18478. detail::PathParamsMatcher matcher(pattern);
  18479. Request request;
  18480. request.path = "/users/42/subscriptions";
  18481. ASSERT_FALSE(matcher.match(request));
  18482. }
  18483. TEST(PathParamsTest, MissingTrailingParam) {
  18484. const auto pattern = "/users/:id";
  18485. detail::PathParamsMatcher matcher(pattern);
  18486. Request request;
  18487. request.path = "/users";
  18488. ASSERT_FALSE(matcher.match(request));
  18489. }
  18490. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18491. const auto pattern = "/users/:id/subscriptions";
  18492. detail::PathParamsMatcher matcher(pattern);
  18493. Request request;
  18494. request.path = "/users/subscriptions";
  18495. ASSERT_FALSE(matcher.match(request));
  18496. }
  18497. TEST(PathParamsTest, MultipleParams) {
  18498. const auto pattern = "/users/:userid/subscriptions/:subid";
  18499. detail::PathParamsMatcher matcher(pattern);
  18500. Request request;
  18501. request.path = "/users/42/subscriptions/2";
  18502. ASSERT_TRUE(matcher.match(request));
  18503. std::unordered_map<std::string, std::string> expected_params = {
  18504. {"userid", "42"}, {"subid", "2"}};
  18505. EXPECT_EQ(request.path_params, expected_params);
  18506. }
  18507. TEST(PathParamsTest, SequenceOfParams) {
  18508. const auto pattern = "/values/:x/:y/:z";
  18509. detail::PathParamsMatcher matcher(pattern);
  18510. Request request;
  18511. request.path = "/values/1/2/3";
  18512. ASSERT_TRUE(matcher.match(request));
  18513. std::unordered_map<std::string, std::string> expected_params = {
  18514. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18515. EXPECT_EQ(request.path_params, expected_params);
  18516. }
  18517. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18518. const auto pattern = "/prefix:suffix";
  18519. detail::PathParamsMatcher matcher(pattern);
  18520. Request request;
  18521. request.path = "/prefix:suffix";
  18522. ASSERT_TRUE(matcher.match(request));
  18523. const std::unordered_map<std::string, std::string> expected_params = {};
  18524. EXPECT_EQ(request.path_params, expected_params);
  18525. }
  18526. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18527. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18528. // calling thread's stack on a long enough path for a quantified pattern;
  18529. // RegexMatcher must refuse to run regex matching on paths beyond
  18530. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18531. detail::RegexMatcher matcher("/files/(.*)");
  18532. Request within_limit;
  18533. within_limit.path = "/files/" + std::string(10, 'A');
  18534. EXPECT_TRUE(matcher.match(within_limit));
  18535. Request over_limit;
  18536. over_limit.path =
  18537. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18538. EXPECT_FALSE(matcher.match(over_limit));
  18539. }
  18540. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18541. Server svr;
  18542. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18543. res.set_content("ok", "text/plain");
  18544. });
  18545. auto port = svr.bind_to_any_port(HOST);
  18546. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18547. auto se = detail::scope_exit([&] {
  18548. svr.stop();
  18549. thread.join();
  18550. ASSERT_FALSE(svr.is_running());
  18551. });
  18552. svr.wait_until_ready();
  18553. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18554. // request URI limit; this used to be able to crash the process.
  18555. std::string path =
  18556. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18557. std::string req = "GET " + path +
  18558. " HTTP/1.1\r\n"
  18559. "Host: " +
  18560. std::string(HOST) + ":" + std::to_string(port) +
  18561. "\r\n"
  18562. "Connection: close\r\n"
  18563. "\r\n";
  18564. std::string response;
  18565. ASSERT_TRUE(send_request(5, req, &response, port));
  18566. EXPECT_NE(std::string::npos, response.find("404"));
  18567. }
  18568. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18569. Server svr;
  18570. auto handler = [](const Request & /*req*/, Response &res) {
  18571. res.set_content("hit", "text/plain");
  18572. };
  18573. // No regex metacharacter, so this one is compared literally
  18574. svr.Get("/literal/route", handler);
  18575. // '.' is a regex metacharacter, so this one must keep regex semantics
  18576. svr.Get("/a.c", handler);
  18577. auto port = svr.bind_to_any_port(HOST);
  18578. std::thread t([&]() { svr.listen_after_bind(); });
  18579. auto se = detail::scope_exit([&] {
  18580. svr.stop();
  18581. t.join();
  18582. ASSERT_FALSE(svr.is_running());
  18583. });
  18584. svr.wait_until_ready();
  18585. Client cli(HOST, port);
  18586. struct {
  18587. const char *path;
  18588. int status;
  18589. } cases[] = {
  18590. {"/literal/route", StatusCode::OK_200},
  18591. {"/literal/routes", StatusCode::NotFound_404},
  18592. {"/literal/rout", StatusCode::NotFound_404},
  18593. {"/abc", StatusCode::OK_200},
  18594. {"/a.c", StatusCode::OK_200},
  18595. };
  18596. for (const auto &x : cases) {
  18597. auto res = cli.Get(x.path);
  18598. ASSERT_TRUE(res) << x.path;
  18599. EXPECT_EQ(x.status, res->status) << x.path;
  18600. }
  18601. }
  18602. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18603. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18604. // from exhausting the stack, so it must only constrain routes that actually
  18605. // run a regular expression. A literal route is matched by comparison and
  18606. // stays usable at any length.
  18607. Server svr;
  18608. const std::string pattern =
  18609. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18610. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18611. res.set_content("hit", "text/plain");
  18612. });
  18613. auto port = svr.bind_to_any_port(HOST);
  18614. std::thread t([&]() { svr.listen_after_bind(); });
  18615. auto se = detail::scope_exit([&] {
  18616. svr.stop();
  18617. t.join();
  18618. ASSERT_FALSE(svr.is_running());
  18619. });
  18620. svr.wait_until_ready();
  18621. Client cli(HOST, port);
  18622. auto res = cli.Get(pattern);
  18623. ASSERT_TRUE(res);
  18624. EXPECT_EQ(StatusCode::OK_200, res->status);
  18625. }
  18626. TEST(ParseUrlTest, VariousPatterns) {
  18627. {
  18628. detail::UrlComponents uc;
  18629. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18630. EXPECT_EQ("http", uc.scheme);
  18631. EXPECT_EQ("example.com", uc.host);
  18632. EXPECT_EQ("8080", uc.port);
  18633. EXPECT_EQ("/path", uc.path);
  18634. EXPECT_EQ("?q=1", uc.query);
  18635. }
  18636. {
  18637. detail::UrlComponents uc;
  18638. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18639. EXPECT_EQ("https", uc.scheme);
  18640. EXPECT_EQ("example.com", uc.host);
  18641. EXPECT_TRUE(uc.port.empty());
  18642. EXPECT_EQ("/path", uc.path);
  18643. }
  18644. {
  18645. detail::UrlComponents uc;
  18646. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18647. EXPECT_EQ("::1", uc.host);
  18648. EXPECT_EQ("8080", uc.port);
  18649. EXPECT_EQ("/path", uc.path);
  18650. }
  18651. {
  18652. detail::UrlComponents uc;
  18653. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18654. }
  18655. {
  18656. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18657. // the path while the connection still targets the bracketed host.
  18658. detail::UrlComponents uc;
  18659. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18660. }
  18661. {
  18662. detail::UrlComponents uc;
  18663. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18664. }
  18665. {
  18666. detail::UrlComponents uc;
  18667. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18668. EXPECT_EQ("::1", uc.host);
  18669. EXPECT_TRUE(uc.port.empty());
  18670. EXPECT_EQ("/path", uc.path);
  18671. }
  18672. {
  18673. detail::UrlComponents uc;
  18674. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18675. EXPECT_TRUE(uc.scheme.empty());
  18676. EXPECT_EQ("example.com", uc.host);
  18677. EXPECT_EQ("/path", uc.path);
  18678. EXPECT_EQ("?q=1", uc.query);
  18679. }
  18680. {
  18681. detail::UrlComponents uc;
  18682. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18683. EXPECT_TRUE(uc.host.empty());
  18684. EXPECT_EQ("/path", uc.path);
  18685. EXPECT_EQ("?q=1", uc.query);
  18686. }
  18687. {
  18688. detail::UrlComponents uc;
  18689. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18690. EXPECT_EQ("example.com", uc.host);
  18691. EXPECT_EQ("8080", uc.port);
  18692. }
  18693. {
  18694. // Unix socket path — must not be parsed as host
  18695. detail::UrlComponents uc;
  18696. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18697. EXPECT_TRUE(uc.host.empty());
  18698. }
  18699. {
  18700. detail::UrlComponents uc;
  18701. ASSERT_TRUE(detail::parse_url("", uc));
  18702. EXPECT_TRUE(uc.host.empty());
  18703. EXPECT_TRUE(uc.path.empty());
  18704. }
  18705. {
  18706. detail::UrlComponents uc;
  18707. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18708. EXPECT_EQ("http", uc.scheme);
  18709. }
  18710. {
  18711. detail::UrlComponents uc;
  18712. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18713. }
  18714. {
  18715. // Accepted by parse_url; callers restrict to http/https
  18716. detail::UrlComponents uc;
  18717. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18718. EXPECT_EQ("ftp", uc.scheme);
  18719. }
  18720. {
  18721. detail::UrlComponents uc;
  18722. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18723. }
  18724. {
  18725. detail::UrlComponents uc;
  18726. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18727. }
  18728. }
  18729. TEST(ParseUrlTest, FragmentHandling) {
  18730. {
  18731. detail::UrlComponents uc;
  18732. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18733. EXPECT_EQ("/path", uc.path);
  18734. EXPECT_TRUE(uc.query.empty());
  18735. }
  18736. {
  18737. detail::UrlComponents uc;
  18738. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18739. EXPECT_TRUE(uc.path.empty());
  18740. EXPECT_TRUE(uc.query.empty());
  18741. }
  18742. }
  18743. TEST(ParseUrlTest, UserinfoHandling) {
  18744. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18745. // parsers would see evil.com as the host.
  18746. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18747. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18748. for (auto url : urls) {
  18749. detail::UrlComponents uc;
  18750. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18751. }
  18752. }
  18753. TEST(ParseUrlTest, IPv6EdgeCases) {
  18754. {
  18755. detail::UrlComponents uc;
  18756. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18757. EXPECT_TRUE(uc.scheme.empty());
  18758. EXPECT_EQ("::1", uc.host);
  18759. EXPECT_EQ("8080", uc.port);
  18760. }
  18761. {
  18762. // Zone ID '%25' is not in [a-fA-F0-9:]
  18763. detail::UrlComponents uc;
  18764. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18765. }
  18766. }
  18767. TEST(ParseUrlTest, SchemeEdgeCases) {
  18768. {
  18769. detail::UrlComponents uc;
  18770. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18771. }
  18772. {
  18773. detail::UrlComponents uc;
  18774. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18775. }
  18776. {
  18777. detail::UrlComponents uc;
  18778. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18779. }
  18780. {
  18781. detail::UrlComponents uc;
  18782. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18783. EXPECT_EQ("https", uc.scheme);
  18784. }
  18785. }
  18786. TEST(ParseUrlTest, PortEdgeCases) {
  18787. {
  18788. detail::UrlComponents uc;
  18789. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18790. EXPECT_TRUE(uc.port.empty());
  18791. EXPECT_EQ("/path", uc.path);
  18792. }
  18793. {
  18794. // parse_url accepts any port string; validation is done by parse_port
  18795. detail::UrlComponents uc;
  18796. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18797. EXPECT_EQ("abc", uc.port);
  18798. }
  18799. }
  18800. TEST(ParseUrlTest, WebSocketPatterns) {
  18801. {
  18802. detail::UrlComponents uc;
  18803. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18804. EXPECT_EQ("ws", uc.scheme);
  18805. EXPECT_EQ("echo.example.com", uc.host);
  18806. EXPECT_EQ("8080", uc.port);
  18807. EXPECT_EQ("/ws", uc.path);
  18808. }
  18809. {
  18810. detail::UrlComponents uc;
  18811. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18812. EXPECT_EQ("wss", uc.scheme);
  18813. EXPECT_EQ("echo.example.com", uc.host);
  18814. EXPECT_TRUE(uc.port.empty());
  18815. EXPECT_EQ("/ws", uc.path);
  18816. }
  18817. }
  18818. TEST(ParseUrlTest, QueryOnly) {
  18819. detail::UrlComponents uc;
  18820. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18821. EXPECT_TRUE(uc.host.empty());
  18822. EXPECT_TRUE(uc.path.empty());
  18823. EXPECT_EQ("?q=1&r=2", uc.query);
  18824. }
  18825. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18826. detail::UrlComponents uc;
  18827. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18828. EXPECT_TRUE(uc.scheme.empty());
  18829. EXPECT_EQ("example.com", uc.host);
  18830. EXPECT_EQ("443", uc.port);
  18831. EXPECT_EQ("/path", uc.path);
  18832. }
  18833. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18834. // If ipv6 regex working, regex match codepath is taken.
  18835. // else port will default to 80 in Client impl
  18836. int clientImplMagicPort = 80;
  18837. int port = 4321;
  18838. // above ports must be different to avoid false negative
  18839. EXPECT_NE(clientImplMagicPort, port);
  18840. std::string ipV6TestURL = "http://[ff06::c3]";
  18841. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18842. CLIENT_PRIVATE_KEY_FILE);
  18843. EXPECT_EQ(cli.port(), port);
  18844. }
  18845. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18846. auto file_path = "./www/dir/index.html";
  18847. auto dir_path = "./www/dir";
  18848. detail::FileStat stat_file(file_path);
  18849. EXPECT_TRUE(stat_file.is_file());
  18850. EXPECT_FALSE(stat_file.is_dir());
  18851. detail::FileStat stat_dir(dir_path);
  18852. EXPECT_FALSE(stat_dir.is_file());
  18853. EXPECT_TRUE(stat_dir.is_dir());
  18854. }
  18855. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18856. // IPv4 with default HTTP port (80)
  18857. EXPECT_EQ("example.com",
  18858. detail::make_host_and_port_string("example.com", 80, false));
  18859. // IPv4 with default HTTPS port (443)
  18860. EXPECT_EQ("example.com",
  18861. detail::make_host_and_port_string("example.com", 443, true));
  18862. // IPv4 with non-default HTTP port
  18863. EXPECT_EQ("example.com:8080",
  18864. detail::make_host_and_port_string("example.com", 8080, false));
  18865. // IPv4 with non-default HTTPS port
  18866. EXPECT_EQ("example.com:8443",
  18867. detail::make_host_and_port_string("example.com", 8443, true));
  18868. // IPv6 with default HTTP port (80)
  18869. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18870. // IPv6 with default HTTPS port (443)
  18871. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18872. // IPv6 with non-default HTTP port
  18873. EXPECT_EQ("[::1]:8080",
  18874. detail::make_host_and_port_string("::1", 8080, false));
  18875. // IPv6 with non-default HTTPS port
  18876. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18877. // IPv6 full address with default port
  18878. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18879. detail::make_host_and_port_string(
  18880. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18881. // IPv6 full address with non-default port
  18882. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18883. detail::make_host_and_port_string(
  18884. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18885. // IPv6 localhost with non-default port
  18886. EXPECT_EQ("[::1]:3000",
  18887. detail::make_host_and_port_string("::1", 3000, false));
  18888. // IPv6 with zone ID (link-local address) with default port
  18889. EXPECT_EQ("[fe80::1%eth0]",
  18890. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18891. // IPv6 with zone ID (link-local address) with non-default port
  18892. EXPECT_EQ("[fe80::1%eth0]:8080",
  18893. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18894. // Edge case: Port 443 with is_ssl=false (should add port)
  18895. EXPECT_EQ("example.com:443",
  18896. detail::make_host_and_port_string("example.com", 443, false));
  18897. // Edge case: Port 80 with is_ssl=true (should add port)
  18898. EXPECT_EQ("example.com:80",
  18899. detail::make_host_and_port_string("example.com", 80, true));
  18900. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18901. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18902. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18903. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18904. // Security fix: Already bracketed IPv6 should not get double brackets
  18905. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18906. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18907. EXPECT_EQ("[::1]:8080",
  18908. detail::make_host_and_port_string("[::1]", 8080, false));
  18909. EXPECT_EQ("[2001:db8::1]:8080",
  18910. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18911. EXPECT_EQ("[fe80::1%eth0]",
  18912. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18913. EXPECT_EQ("[fe80::1%eth0]:8080",
  18914. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18915. // Edge case: Empty host (should return as-is)
  18916. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18917. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18918. // This is a known limitation but shouldn't crash
  18919. EXPECT_EQ("[host:name]",
  18920. detail::make_host_and_port_string("host:name", 80, false));
  18921. // Port number edge cases (no validation, but should not crash)
  18922. EXPECT_EQ("example.com:0",
  18923. detail::make_host_and_port_string("example.com", 0, false));
  18924. EXPECT_EQ("example.com:-1",
  18925. detail::make_host_and_port_string("example.com", -1, false));
  18926. EXPECT_EQ("example.com:65535",
  18927. detail::make_host_and_port_string("example.com", 65535, false));
  18928. EXPECT_EQ("example.com:65536",
  18929. detail::make_host_and_port_string("example.com", 65536, false));
  18930. }
  18931. namespace httplib {
  18932. namespace detail {
  18933. std::string
  18934. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18935. const std::string &host, int port);
  18936. } // namespace detail
  18937. } // namespace httplib
  18938. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18939. std::map<std::string, std::string> addr_map = {
  18940. {"ipv4.example", "192.0.2.10"},
  18941. {"ipv6.example", "2001:db8::1"},
  18942. {"name.example", "internal.example.lan"},
  18943. {"empty.example", ""}};
  18944. EXPECT_EQ("192.0.2.10:443",
  18945. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18946. EXPECT_EQ("[2001:db8::1]:443",
  18947. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18948. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18949. addr_map, "name.example", 8443));
  18950. // An empty or absent mapping keeps the hostname as the target
  18951. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18952. addr_map, "empty.example", 443));
  18953. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18954. addr_map, "other.example", 443));
  18955. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18956. }
  18957. #ifdef CPPHTTPLIB_SSL_ENABLED
  18958. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18959. httplib::SSLClient cli("roblox.com", 443);
  18960. cli.set_follow_location(true);
  18961. auto res = cli.Get("/");
  18962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18963. EXPECT_EQ(StatusCode::OK_200, res->status);
  18964. }
  18965. #endif
  18966. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18967. Server svr;
  18968. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18969. EXPECT_EQ(res.status, 400);
  18970. });
  18971. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18972. auto se = detail::scope_exit([&] {
  18973. svr.stop();
  18974. thread.join();
  18975. ASSERT_FALSE(svr.is_running());
  18976. });
  18977. svr.wait_until_ready();
  18978. Client cli(HOST, PORT);
  18979. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18980. }
  18981. TEST(InvalidHeaderCharsTest, is_field_name) {
  18982. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18983. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18984. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18985. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18986. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18987. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18988. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18989. EXPECT_FALSE(detail::fields::is_field_name(""));
  18990. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18991. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18992. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18993. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18994. }
  18995. TEST(InvalidHeaderCharsTest, is_field_value) {
  18996. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18997. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18998. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18999. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19000. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19001. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19002. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19003. EXPECT_TRUE(detail::fields::is_field_value(""));
  19004. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19005. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19006. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19007. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19008. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19009. }
  19010. TEST(InvalidHeaderCharsTest, OnServer) {
  19011. Server svr;
  19012. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19013. std::string header = "Not Set";
  19014. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19015. res.set_header(header, "value");
  19016. res.set_content("Page Content Page Content", "text/plain");
  19017. });
  19018. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19019. std::string header = "Not Set";
  19020. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19021. res.set_header("X-Test", header);
  19022. res.set_content("Page Content Page Content", "text/plain");
  19023. });
  19024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19025. auto se = detail::scope_exit([&] {
  19026. svr.stop();
  19027. thread.join();
  19028. ASSERT_FALSE(svr.is_running());
  19029. });
  19030. svr.wait_until_ready();
  19031. Client cli(HOST, PORT);
  19032. {
  19033. auto res = cli.Get(
  19034. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19036. EXPECT_EQ("Page Content Page Content", res->body);
  19037. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19038. }
  19039. {
  19040. auto res = cli.Get(
  19041. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19043. EXPECT_EQ("Page Content Page Content", res->body);
  19044. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19045. }
  19046. }
  19047. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19048. auto handled = false;
  19049. Server svr;
  19050. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19051. thread t = thread([&] { svr.listen(HOST, PORT); });
  19052. auto se = detail::scope_exit([&] {
  19053. svr.stop();
  19054. t.join();
  19055. ASSERT_FALSE(svr.is_running());
  19056. ASSERT_FALSE(handled);
  19057. });
  19058. svr.wait_until_ready();
  19059. auto req = "POST /test HTTP/1.1\r\n"
  19060. "Content-Length: x\r\n"
  19061. "\r\n";
  19062. std::string response;
  19063. ASSERT_TRUE(send_request(1, req, &response));
  19064. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19065. response.substr(0, response.find("\r\n")));
  19066. }
  19067. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19068. // case-insensitive, and a server that receives a 100-continue expectation in
  19069. // an HTTP/1.0 request MUST ignore it.
  19070. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19071. std::string response;
  19072. ASSERT_TRUE(send_request(1, req, &response, port));
  19073. *got_100 = response.find("100 Continue") != std::string::npos;
  19074. }
  19075. class ExpectTokenTest : public ::testing::Test {
  19076. protected:
  19077. void SetUp() override {
  19078. svr_.Post("/p", [](const Request &, Response &res) {
  19079. res.set_content("ok", "text/plain");
  19080. });
  19081. port_ = svr_.bind_to_any_port(HOST);
  19082. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19083. svr_.wait_until_ready();
  19084. }
  19085. void TearDown() override {
  19086. svr_.stop();
  19087. if (thread_.joinable()) { thread_.join(); }
  19088. }
  19089. std::string request(const char *version, const char *expect_value) const {
  19090. return std::string("POST /p ") + version +
  19091. "\r\n"
  19092. "Host: localhost\r\n"
  19093. "Content-Length: 2\r\n"
  19094. "Connection: close\r\n"
  19095. "Expect: " +
  19096. expect_value +
  19097. "\r\n"
  19098. "\r\n"
  19099. "hi";
  19100. }
  19101. Server svr_;
  19102. int port_ = 0;
  19103. thread thread_;
  19104. };
  19105. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19106. bool got_100 = false;
  19107. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19108. EXPECT_TRUE(got_100);
  19109. }
  19110. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19111. bool got_100 = true;
  19112. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19113. EXPECT_FALSE(got_100);
  19114. }
  19115. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19116. bool got_100 = false;
  19117. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19118. EXPECT_TRUE(got_100);
  19119. }
  19120. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19121. bool got_100 = false;
  19122. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19123. EXPECT_TRUE(got_100);
  19124. }
  19125. // `100 Continue` is sent only when the server starts reading the body, so a
  19126. // request rejected before that never invites the client to send it. The
  19127. // requests below carry the expectation but withhold the body, as a client
  19128. // waiting for `100 Continue` would.
  19129. // A POST that expects `100 Continue` and withholds its two-byte body.
  19130. static std::string expect_headers_only(const std::string &path) {
  19131. return "POST " + path +
  19132. " HTTP/1.1\r\n"
  19133. "Host: localhost\r\n"
  19134. "Content-Length: 2\r\n"
  19135. "Expect: 100-continue\r\n"
  19136. "\r\n";
  19137. }
  19138. class ExpectLazyContinueTest : public ::testing::Test {
  19139. protected:
  19140. void SetUp() override {
  19141. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19142. if (req.path == "/pre-routing") {
  19143. res.status = StatusCode::Unauthorized_401;
  19144. return Server::HandlerResponse::Handled;
  19145. }
  19146. return Server::HandlerResponse::Unhandled;
  19147. });
  19148. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19149. if (req.matched_route == "/pre-request") {
  19150. res.status = StatusCode::Forbidden_403;
  19151. return Server::HandlerResponse::Handled;
  19152. }
  19153. return Server::HandlerResponse::Unhandled;
  19154. });
  19155. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19156. res.set_content("ok", "text/plain");
  19157. });
  19158. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19159. res.set_content("ok", "text/plain");
  19160. });
  19161. svr_.Post("/reader-used", [](const Request &, Response &res,
  19162. const ContentReader &content_reader) {
  19163. std::string body;
  19164. content_reader([&](const char *data, size_t len) {
  19165. body.append(data, len);
  19166. return true;
  19167. });
  19168. res.set_content(body, "text/plain");
  19169. });
  19170. svr_.Post("/reader-unused",
  19171. [](const Request &, Response &res, const ContentReader &) {
  19172. res.set_content("ignored", "text/plain");
  19173. });
  19174. port_ = svr_.bind_to_any_port(HOST);
  19175. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19176. svr_.wait_until_ready();
  19177. }
  19178. void TearDown() override {
  19179. svr_.stop();
  19180. if (thread_.joinable()) { thread_.join(); }
  19181. }
  19182. // Sends `req` and reads until the server closes the connection. Returns
  19183. // false if the read had to wait for the client-side timeout instead.
  19184. bool send_until_closed(const std::string &req, std::string *resp) const {
  19185. auto start = std::chrono::steady_clock::now();
  19186. if (!send_request(3, req, resp, port_)) { return false; }
  19187. auto elapsed = std::chrono::steady_clock::now() - start;
  19188. return elapsed < std::chrono::seconds(2);
  19189. }
  19190. // The final response comes without `100 Continue`, and the server closes
  19191. // the connection since the body may or may not follow.
  19192. void expect_final_without_interim(const std::string &path,
  19193. const char *status_line) const {
  19194. std::string resp;
  19195. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19196. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19197. EXPECT_EQ(0u, resp.find(status_line));
  19198. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19199. }
  19200. Server svr_;
  19201. int port_ = 0;
  19202. thread thread_;
  19203. };
  19204. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19205. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19206. }
  19207. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19208. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19209. }
  19210. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19211. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19212. }
  19213. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19214. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19215. }
  19216. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19217. // The body follows once `100 Continue` has had time to arrive.
  19218. auto req = expect_headers_only("/reader-used");
  19219. req.insert(req.size() - 2, "Connection: close\r\n");
  19220. std::string resp;
  19221. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19222. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19223. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19224. EXPECT_NE(std::string::npos, resp.find("hi"));
  19225. }
  19226. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19227. // Large enough for the client to add `Expect: 100-continue` itself.
  19228. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19229. std::atomic<bool> body_sent{false};
  19230. Client cli(HOST, port_);
  19231. auto res = cli.Post(
  19232. "/pre-request", length,
  19233. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19234. body_sent = true;
  19235. std::string chunk(len, 'x');
  19236. sink.write(chunk.data(), chunk.size());
  19237. return true;
  19238. },
  19239. "application/octet-stream");
  19240. ASSERT_TRUE(res);
  19241. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19242. EXPECT_FALSE(body_sent);
  19243. }
  19244. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19245. Server svr;
  19246. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19247. return StatusCode::ExpectationFailed_417;
  19248. });
  19249. svr.Post("/p", [](const Request &, Response &res) {
  19250. res.set_content("ok", "text/plain");
  19251. });
  19252. auto port = svr.bind_to_any_port(HOST);
  19253. thread t = thread([&] { svr.listen_after_bind(); });
  19254. auto se = detail::scope_exit([&] {
  19255. svr.stop();
  19256. t.join();
  19257. });
  19258. svr.wait_until_ready();
  19259. std::string resp;
  19260. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19261. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19262. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19263. // Exactly one response: the route handler must not run after the 417.
  19264. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19265. }
  19266. #ifndef _WIN32
  19267. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19268. static constexpr char reject[] = "Unauthorized";
  19269. static constexpr char accept[] = "Upload accepted";
  19270. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19271. Server svr;
  19272. svr.set_expect_100_continue_handler(
  19273. [](const Request & /*req*/, Response &res) {
  19274. res.status = StatusCode::Unauthorized_401;
  19275. res.set_content(reject, "text/plain");
  19276. return res.status;
  19277. });
  19278. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19279. res.set_content(accept, "text/plain");
  19280. });
  19281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19282. auto se = detail::scope_exit([&] {
  19283. svr.stop();
  19284. thread.join();
  19285. ASSERT_FALSE(svr.is_running());
  19286. });
  19287. svr.wait_until_ready();
  19288. {
  19289. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19290. curl_easy_init(), &curl_easy_cleanup};
  19291. ASSERT_NE(curl, nullptr);
  19292. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19293. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19294. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19295. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19296. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19297. &curl_slist_free_all};
  19298. ASSERT_NE(list, nullptr);
  19299. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19300. struct read_data {
  19301. uint64_t read_size;
  19302. uint64_t total_size;
  19303. } data = {0, total_size};
  19304. using read_callback_t =
  19305. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19306. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19307. void *userdata) -> size_t {
  19308. read_data *d = (read_data *)userdata;
  19309. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19310. std::fill_n(ptr, size * nmemb, 'A');
  19311. d->read_size += size * nmemb;
  19312. return size * nmemb;
  19313. };
  19314. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19315. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19316. std::vector<char> buffer;
  19317. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19318. using write_callback_t =
  19319. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19320. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19321. void *userdata) -> size_t {
  19322. std::vector<char> *buf = (std::vector<char> *)userdata;
  19323. buf->reserve(buf->size() + size * nmemb + 1);
  19324. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19325. return size * nmemb;
  19326. };
  19327. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19328. {
  19329. const auto res = curl_easy_perform(curl.get());
  19330. ASSERT_EQ(res, CURLE_OK);
  19331. }
  19332. {
  19333. auto response_code = long{};
  19334. const auto res =
  19335. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19336. ASSERT_EQ(res, CURLE_OK);
  19337. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19338. }
  19339. {
  19340. auto dl = curl_off_t{};
  19341. const auto res =
  19342. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19343. ASSERT_EQ(res, CURLE_OK);
  19344. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19345. }
  19346. {
  19347. buffer.push_back('\0');
  19348. ASSERT_STRCASEEQ(buffer.data(), reject);
  19349. }
  19350. }
  19351. }
  19352. #endif
  19353. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19354. // Regression test for #2458.
  19355. //
  19356. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19357. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19358. // ticket can make the client socket spuriously readable during the
  19359. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19360. // the client withholds the body and then blocks reading a response that never
  19361. // comes, failing with `Failed to read connection`.
  19362. //
  19363. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19364. // within the timeout. This raw OpenSSL server deliberately never sends
  19365. // `100 Continue`; the client must still deliver the body and receive 200.
  19366. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19367. signal(SIGPIPE, SIG_IGN);
  19368. const auto port = PORT + 4;
  19369. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19370. ASSERT_NE(srv, INVALID_SOCKET);
  19371. int opt = 1;
  19372. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19373. sockaddr_in addr{};
  19374. addr.sin_family = AF_INET;
  19375. addr.sin_port = htons(static_cast<uint16_t>(port));
  19376. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19377. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19378. ASSERT_EQ(0, ::listen(srv, 1));
  19379. std::atomic<size_t> server_body_bytes{0};
  19380. auto server_thread = std::thread([&] {
  19381. sockaddr_in cli_addr{};
  19382. socklen_t cli_len = sizeof(cli_addr);
  19383. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19384. if (cli == INVALID_SOCKET) { return; }
  19385. // Bound the lifetime of the server side so a buggy client (which never
  19386. // sends the body) cannot make this thread block forever on join.
  19387. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19388. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19389. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19390. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19391. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19392. SSL *ssl = SSL_new(ctx);
  19393. SSL_set_fd(ssl, static_cast<int>(cli));
  19394. if (SSL_accept(ssl) > 0) {
  19395. // Read the request headers. Reading here also flushes the TLS 1.3
  19396. // session tickets to the client. Deliberately do NOT send
  19397. // `100 Continue`.
  19398. std::string buf;
  19399. char tmp[1024];
  19400. while (buf.find("\r\n\r\n") == std::string::npos) {
  19401. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19402. if (n <= 0) { break; }
  19403. buf.append(tmp, static_cast<size_t>(n));
  19404. }
  19405. // A correct client sends the body now; count what arrives.
  19406. auto pos = buf.find("\r\n\r\n");
  19407. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19408. while (body < 4096) {
  19409. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19410. if (n <= 0) { break; }
  19411. body += static_cast<size_t>(n);
  19412. }
  19413. server_body_bytes = body;
  19414. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19415. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19416. SSL_shutdown(ssl);
  19417. }
  19418. SSL_free(ssl);
  19419. detail::close_socket(cli);
  19420. SSL_CTX_free(ctx);
  19421. });
  19422. auto se = detail::scope_exit([&] {
  19423. server_thread.join();
  19424. detail::close_socket(srv);
  19425. });
  19426. SSLClient cli("127.0.0.1", port);
  19427. cli.enable_server_certificate_verification(false);
  19428. cli.set_connection_timeout(5, 0);
  19429. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19430. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19431. std::string body(4096, 'A');
  19432. auto res = cli.Put("/api/test", body, "application/json");
  19433. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19434. EXPECT_EQ(StatusCode::OK_200, res->status);
  19435. EXPECT_EQ(body.size(), server_body_bytes.load());
  19436. }
  19437. #endif
  19438. template <typename S, typename C>
  19439. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19440. svr.Get("/stream", [&](const Request &, Response &res) {
  19441. auto data = new std::string("01234567890123456789");
  19442. res.set_content_provider(
  19443. data->size(), "text/plain",
  19444. [&, data](size_t offset, size_t length, DataSink &sink) {
  19445. const size_t DATA_CHUNK_SIZE = 4;
  19446. const auto &d = *data;
  19447. std::this_thread::sleep_for(std::chrono::seconds(1));
  19448. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19449. return true;
  19450. },
  19451. [data](bool success) {
  19452. EXPECT_FALSE(success);
  19453. delete data;
  19454. });
  19455. });
  19456. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19457. auto i = new size_t(0);
  19458. res.set_content_provider(
  19459. "text/plain",
  19460. [i](size_t, DataSink &sink) {
  19461. if (*i < 5) {
  19462. std::this_thread::sleep_for(std::chrono::seconds(1));
  19463. sink.write("abcd", 4);
  19464. (*i)++;
  19465. } else {
  19466. sink.done();
  19467. }
  19468. return true;
  19469. },
  19470. [i](bool success) {
  19471. EXPECT_FALSE(success);
  19472. delete i;
  19473. });
  19474. });
  19475. svr.Get("/chunked", [&](const Request &, Response &res) {
  19476. auto i = new size_t(0);
  19477. res.set_chunked_content_provider(
  19478. "text/plain",
  19479. [i](size_t, DataSink &sink) {
  19480. if (*i < 5) {
  19481. std::this_thread::sleep_for(std::chrono::seconds(1));
  19482. sink.os << "abcd";
  19483. (*i)++;
  19484. } else {
  19485. sink.done();
  19486. }
  19487. return true;
  19488. },
  19489. [i](bool success) {
  19490. EXPECT_FALSE(success);
  19491. delete i;
  19492. });
  19493. });
  19494. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19495. auto se = detail::scope_exit([&] {
  19496. svr.stop();
  19497. listen_thread.join();
  19498. ASSERT_FALSE(svr.is_running());
  19499. });
  19500. svr.wait_until_ready();
  19501. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19502. {
  19503. auto start = std::chrono::steady_clock::now();
  19504. auto res = cli.Get("/stream");
  19505. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19506. std::chrono::steady_clock::now() - start)
  19507. .count();
  19508. ASSERT_FALSE(res);
  19509. EXPECT_EQ(Error::Read, res.error());
  19510. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19511. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19512. }
  19513. {
  19514. auto start = std::chrono::steady_clock::now();
  19515. auto res = cli.Get("/stream_without_length");
  19516. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19517. std::chrono::steady_clock::now() - start)
  19518. .count();
  19519. ASSERT_FALSE(res);
  19520. EXPECT_EQ(Error::Read, res.error());
  19521. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19522. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19523. }
  19524. {
  19525. auto start = std::chrono::steady_clock::now();
  19526. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19527. EXPECT_EQ("abcd", string(data, data_length));
  19528. return true;
  19529. });
  19530. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19531. std::chrono::steady_clock::now() - start)
  19532. .count();
  19533. ASSERT_FALSE(res);
  19534. EXPECT_EQ(Error::Read, res.error());
  19535. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19536. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19537. }
  19538. }
  19539. TEST(MaxTimeoutTest, ContentStream) {
  19540. time_t timeout = 2000;
  19541. time_t threshold = 200;
  19542. Server svr;
  19543. Client cli("localhost", PORT);
  19544. max_timeout_test(svr, cli, timeout, threshold);
  19545. }
  19546. #ifdef CPPHTTPLIB_SSL_ENABLED
  19547. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19548. time_t timeout = 2000;
  19549. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19551. SSLClient cli("localhost", PORT);
  19552. cli.enable_server_certificate_verification(false);
  19553. max_timeout_test(svr, cli, timeout, threshold);
  19554. }
  19555. #endif
  19556. class EventDispatcher {
  19557. public:
  19558. EventDispatcher() {}
  19559. bool wait_event(DataSink *sink) {
  19560. unique_lock<mutex> lk(m_);
  19561. int id = id_;
  19562. // Wait with timeout to prevent hanging if client disconnects
  19563. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19564. [&] { return cid_ == id; })) {
  19565. return false; // Timeout occurred
  19566. }
  19567. sink->write(message_.data(), message_.size());
  19568. return true;
  19569. }
  19570. void send_event(const string &message) {
  19571. lock_guard<mutex> lk(m_);
  19572. cid_ = id_++;
  19573. message_ = message;
  19574. cv_.notify_all();
  19575. }
  19576. private:
  19577. mutex m_;
  19578. condition_variable cv_;
  19579. atomic_int id_{0};
  19580. atomic_int cid_{-1};
  19581. string message_;
  19582. };
  19583. TEST(ClientInThreadTest, Issue2068) {
  19584. EventDispatcher ed;
  19585. Server svr;
  19586. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19587. res.set_chunked_content_provider("text/event-stream",
  19588. [&](size_t /*offset*/, DataSink &sink) {
  19589. return ed.wait_event(&sink);
  19590. });
  19591. });
  19592. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19593. svr.wait_until_ready();
  19594. thread event_thread([&] {
  19595. int id = 0;
  19596. while (svr.is_running()) {
  19597. this_thread::sleep_for(chrono::milliseconds(500));
  19598. std::stringstream ss;
  19599. ss << "data: " << id << "\n\n";
  19600. ed.send_event(ss.str());
  19601. id++;
  19602. }
  19603. });
  19604. auto se = detail::scope_exit([&] {
  19605. svr.stop();
  19606. listen_thread.join();
  19607. event_thread.join();
  19608. ASSERT_FALSE(svr.is_running());
  19609. });
  19610. {
  19611. auto client = detail::make_unique<Client>(HOST, PORT);
  19612. client->set_read_timeout(std::chrono::minutes(10));
  19613. std::atomic<bool> stop{false};
  19614. std::thread t([&] {
  19615. client->Get("/event1",
  19616. [&](const char *, size_t) -> bool { return !stop; });
  19617. });
  19618. std::this_thread::sleep_for(std::chrono::seconds(2));
  19619. stop = true;
  19620. client->stop();
  19621. t.join();
  19622. // Reset client after thread has finished
  19623. client.reset();
  19624. }
  19625. }
  19626. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19627. auto handled = false;
  19628. Server svr;
  19629. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19631. auto se = detail::scope_exit([&] {
  19632. svr.stop();
  19633. t.join();
  19634. ASSERT_FALSE(svr.is_running());
  19635. ASSERT_FALSE(handled);
  19636. });
  19637. svr.wait_until_ready();
  19638. // Two Content-Length headers with different values — must be rejected
  19639. auto req = "POST /test HTTP/1.1\r\n"
  19640. "Content-Length: 5\r\n"
  19641. "Content-Length: 10\r\n"
  19642. "\r\n"
  19643. "hello";
  19644. std::string response;
  19645. ASSERT_TRUE(send_request(1, req, &response));
  19646. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19647. response.substr(0, response.find("\r\n")));
  19648. }
  19649. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19650. auto handled = false;
  19651. Server svr;
  19652. svr.Post("/test", [&](const Request &, Response &res) {
  19653. handled = true;
  19654. res.set_content("ok", "text/plain");
  19655. });
  19656. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19657. auto se = detail::scope_exit([&] {
  19658. svr.stop();
  19659. t.join();
  19660. ASSERT_FALSE(svr.is_running());
  19661. ASSERT_TRUE(handled);
  19662. });
  19663. svr.wait_until_ready();
  19664. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19665. auto req = "POST /test HTTP/1.1\r\n"
  19666. "Host: localhost\r\n"
  19667. "Content-Length: 5\r\n"
  19668. "Content-Length: 5\r\n"
  19669. "\r\n"
  19670. "hello";
  19671. std::string response;
  19672. ASSERT_TRUE(send_request(1, req, &response));
  19673. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19674. }
  19675. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19676. Server svr;
  19677. svr.Get("/test", [](const Request &, Response &res) {
  19678. res.set_content("ok", "text/plain");
  19679. });
  19680. auto port = svr.bind_to_any_port(HOST);
  19681. thread t = thread([&] { svr.listen_after_bind(); });
  19682. auto se = detail::scope_exit([&] {
  19683. svr.stop();
  19684. t.join();
  19685. ASSERT_FALSE(svr.is_running());
  19686. });
  19687. svr.wait_until_ready();
  19688. auto status_line = [&](const std::string &host_lines) {
  19689. std::string res;
  19690. send_request(
  19691. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19692. &res, port);
  19693. return res.substr(0, res.find("\r\n"));
  19694. };
  19695. const char *accepted[] = {
  19696. "Host: localhost\r\n",
  19697. "Host: a.example:8080\r\n",
  19698. "Host: my_service\r\n",
  19699. "Host: [::1]:8080\r\n",
  19700. "Host: [fe80::1%25eth0]\r\n",
  19701. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19702. };
  19703. for (auto host_lines : accepted) {
  19704. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19705. }
  19706. const char *rejected[] = {
  19707. "Host: a.example\r\nHost: b.example\r\n",
  19708. "Host: a.example\r\nHost: a.example\r\n",
  19709. "Host: a@b.example\r\n",
  19710. "Host: a.example/b\r\n",
  19711. "Host: a.example\\b\r\n",
  19712. "Host: a.example?b\r\n",
  19713. "Host: a.example#b\r\n",
  19714. "Host: a.example b.example\r\n",
  19715. };
  19716. for (auto host_lines : rejected) {
  19717. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19718. << host_lines;
  19719. }
  19720. }
  19721. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19722. Server svr;
  19723. svr.Get("/", [](const Request &req, Response &res) {
  19724. EXPECT_EQ(2U, req.trailers.size());
  19725. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19726. // Denied
  19727. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19728. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19729. // Accepted
  19730. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19731. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19732. EXPECT_TRUE(req.has_trailer("X-World"));
  19733. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19734. res.set_content("ok", "text/plain");
  19735. });
  19736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19737. auto se = detail::scope_exit([&] {
  19738. svr.stop();
  19739. t.join();
  19740. ASSERT_FALSE(svr.is_running());
  19741. });
  19742. svr.wait_until_ready();
  19743. const std::string req = "GET / HTTP/1.1\r\n"
  19744. "Transfer-Encoding: chunked\r\n"
  19745. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19746. "\r\n"
  19747. "0\r\n"
  19748. "Content-Length: 10\r\n"
  19749. "Host: internal.local\r\n"
  19750. "Content-Type: malicious/content\r\n"
  19751. "Cookie: any\r\n"
  19752. "Set-Cookie: any\r\n"
  19753. "X-Forwarded-For: attacker.com\r\n"
  19754. "X-Real-Ip: 1.1.1.1\r\n"
  19755. "X-Hello: hello\r\n"
  19756. "X-World: world\r\n"
  19757. "\r\n";
  19758. std::string res;
  19759. ASSERT_TRUE(send_request(1, req, &res));
  19760. }
  19761. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19762. // several field lines, and the combined value is what has to be parsed. A
  19763. // Trailer field split across lines therefore declares every name it lists;
  19764. // reading only the first line silently drops the trailers the later lines
  19765. // declare. The prohibited-trailer filter still applies to every line.
  19766. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19767. Server svr;
  19768. size_t observed_trailer_count = 0;
  19769. std::string observed_hello;
  19770. std::string observed_world;
  19771. bool observed_content_length = true;
  19772. svr.Get("/", [&](const Request &req, Response &res) {
  19773. observed_trailer_count = req.trailers.size();
  19774. observed_hello = req.get_trailer_value("X-Hello");
  19775. observed_world = req.get_trailer_value("X-World");
  19776. observed_content_length = req.has_trailer("Content-Length");
  19777. res.set_content("ok", "text/plain");
  19778. });
  19779. auto port = svr.bind_to_any_port(HOST);
  19780. thread t = thread([&]() { svr.listen_after_bind(); });
  19781. auto se = detail::scope_exit([&] {
  19782. svr.stop();
  19783. t.join();
  19784. ASSERT_FALSE(svr.is_running());
  19785. });
  19786. svr.wait_until_ready();
  19787. const std::string req = "GET / HTTP/1.1\r\n"
  19788. "Host: localhost\r\n"
  19789. "Transfer-Encoding: chunked\r\n"
  19790. "Trailer: X-Hello\r\n"
  19791. "Trailer: X-World, Content-Length\r\n"
  19792. "\r\n"
  19793. "0\r\n"
  19794. "X-Hello: hello\r\n"
  19795. "X-World: world\r\n"
  19796. "Content-Length: 10\r\n"
  19797. "\r\n";
  19798. std::string res;
  19799. ASSERT_TRUE(send_request(1, req, &res, port));
  19800. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19801. // Accepted: both field lines contribute to the declared set
  19802. EXPECT_EQ(2U, observed_trailer_count);
  19803. EXPECT_EQ(observed_hello, "hello");
  19804. EXPECT_EQ(observed_world, "world");
  19805. // Denied: a prohibited name stays prohibited on a later field line
  19806. EXPECT_FALSE(observed_content_length);
  19807. }
  19808. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19809. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19810. // unbounded run of fields that are never declared, because the counter would
  19811. // only advance for declared fields.
  19812. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19813. Server svr;
  19814. bool handler_called = false;
  19815. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19816. handler_called = true;
  19817. res.set_content("ok", "text/plain");
  19818. });
  19819. auto port = svr.bind_to_any_port(HOST);
  19820. thread t = thread([&]() { svr.listen_after_bind(); });
  19821. auto se = detail::scope_exit([&] {
  19822. svr.stop();
  19823. t.join();
  19824. ASSERT_FALSE(svr.is_running());
  19825. });
  19826. svr.wait_until_ready();
  19827. // Declare nothing, then send far more undeclared trailer fields than the
  19828. // header-count limit. Parsing must stop and reject the request rather than
  19829. // read every line.
  19830. std::string req = "GET / HTTP/1.1\r\n"
  19831. "Transfer-Encoding: chunked\r\n"
  19832. "\r\n"
  19833. "0\r\n";
  19834. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19835. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19836. }
  19837. req += "\r\n";
  19838. std::string res;
  19839. ASSERT_TRUE(send_request(1, req, &res, port));
  19840. // The request is rejected before the handler runs.
  19841. EXPECT_FALSE(handler_called);
  19842. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19843. }
  19844. // The set of declared trailer names is capped so a peer cannot grow it without
  19845. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19846. // declared past the cap is not honored, even if the field is actually sent.
  19847. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19848. Server svr;
  19849. // One name inside the cap and one past it, so the test tracks the cap rather
  19850. // than a fixed count.
  19851. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19852. const std::string within_cap_name = "X-T-0";
  19853. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19854. bool observed_within_cap = false;
  19855. bool observed_past_cap = false;
  19856. svr.Get("/", [&](const Request &req, Response &res) {
  19857. observed_within_cap = req.has_trailer(within_cap_name);
  19858. observed_past_cap = req.has_trailer(past_cap_name);
  19859. res.set_content("ok", "text/plain");
  19860. });
  19861. auto port = svr.bind_to_any_port(HOST);
  19862. thread t = thread([&]() { svr.listen_after_bind(); });
  19863. auto se = detail::scope_exit([&] {
  19864. svr.stop();
  19865. t.join();
  19866. ASSERT_FALSE(svr.is_running());
  19867. });
  19868. svr.wait_until_ready();
  19869. // Declare more trailer names than the cap in a single Trailer field, then
  19870. // actually send the first (within the cap) and the last (past it).
  19871. std::string trailer_decl = "Trailer: ";
  19872. for (int i = 0; i < declared_count; i++) {
  19873. if (i != 0) { trailer_decl += ", "; }
  19874. trailer_decl += "X-T-" + std::to_string(i);
  19875. }
  19876. trailer_decl += "\r\n";
  19877. const std::string req = "GET / HTTP/1.1\r\n"
  19878. "Host: localhost\r\n"
  19879. "Transfer-Encoding: chunked\r\n" +
  19880. trailer_decl +
  19881. "\r\n"
  19882. "0\r\n" +
  19883. within_cap_name + ": a\r\n" + past_cap_name +
  19884. ": b\r\n"
  19885. "\r\n";
  19886. std::string res;
  19887. ASSERT_TRUE(send_request(1, req, &res, port));
  19888. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19889. // A name within the cap is honored; one declared past the cap is dropped.
  19890. EXPECT_TRUE(observed_within_cap);
  19891. EXPECT_FALSE(observed_past_cap);
  19892. }
  19893. // A direct client that is not listed in trusted_proxies must not be able to
  19894. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19895. // the peer address on the actual TCP connection determines whether the
  19896. // header is honored.
  19897. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19898. Server svr;
  19899. // Deliberately does NOT include the loopback address the test client
  19900. // actually connects from, so the direct connection is not a trusted proxy.
  19901. svr.set_trusted_proxies({"203.0.113.66"});
  19902. std::string observed_remote_addr;
  19903. svr.Get("/ip", [&](const Request &req, Response &res) {
  19904. observed_remote_addr = req.remote_addr;
  19905. res.set_content("ok", "text/plain");
  19906. });
  19907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19908. auto se = detail::scope_exit([&] {
  19909. svr.stop();
  19910. t.join();
  19911. ASSERT_FALSE(svr.is_running());
  19912. });
  19913. svr.wait_until_ready();
  19914. Client cli(HOST, PORT);
  19915. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19917. EXPECT_EQ(StatusCode::OK_200, res->status);
  19918. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19919. // ignored entirely and the real connection-level address retained.
  19920. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19921. observed_remote_addr == "127.0.0.1");
  19922. }
  19923. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19924. Server svr;
  19925. std::string observed_remote_addr;
  19926. std::string observed_xff;
  19927. svr.Get("/ip", [&](const Request &req, Response &res) {
  19928. observed_remote_addr = req.remote_addr;
  19929. observed_xff = req.get_header_value("X-Forwarded-For");
  19930. res.set_content("ok", "text/plain");
  19931. });
  19932. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19933. auto se = detail::scope_exit([&] {
  19934. svr.stop();
  19935. t.join();
  19936. ASSERT_FALSE(svr.is_running());
  19937. });
  19938. svr.wait_until_ready();
  19939. Client cli(HOST, PORT);
  19940. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19942. EXPECT_EQ(StatusCode::OK_200, res->status);
  19943. EXPECT_EQ(observed_xff, "203.0.113.66");
  19944. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19945. observed_remote_addr == "127.0.0.1");
  19946. }
  19947. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19948. Server svr;
  19949. svr.set_trusted_proxies({"203.0.113.66"});
  19950. std::string observed_remote_addr;
  19951. std::string observed_xff;
  19952. svr.Get("/ip", [&](const Request &req, Response &res) {
  19953. observed_remote_addr = req.remote_addr;
  19954. observed_xff = req.get_header_value("X-Forwarded-For");
  19955. res.set_content("ok", "text/plain");
  19956. });
  19957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19958. auto se = detail::scope_exit([&] {
  19959. svr.stop();
  19960. t.join();
  19961. ASSERT_FALSE(svr.is_running());
  19962. });
  19963. svr.wait_until_ready();
  19964. Client cli(HOST, PORT);
  19965. auto res = cli.Get("/ip");
  19966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19967. EXPECT_EQ(StatusCode::OK_200, res->status);
  19968. EXPECT_EQ(observed_xff, "");
  19969. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19970. observed_remote_addr == "127.0.0.1");
  19971. }
  19972. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19973. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19974. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19975. Server svr;
  19976. svr.set_trusted_proxies({"127.0.0.1"});
  19977. svr.Get("/ip", [](const Request &req, Response &res) {
  19978. res.set_content(req.remote_addr, "text/plain");
  19979. });
  19980. auto port = svr.bind_to_any_port("::");
  19981. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19982. thread t = thread([&] { svr.listen_after_bind(); });
  19983. auto se = detail::scope_exit([&] {
  19984. svr.stop();
  19985. t.join();
  19986. ASSERT_FALSE(svr.is_running());
  19987. });
  19988. svr.wait_until_ready();
  19989. Client cli("127.0.0.1", port);
  19990. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19992. EXPECT_EQ("198.51.100.23", res->body);
  19993. }
  19994. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19995. Server svr;
  19996. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19997. svr.Get("/ip", [](const Request &req, Response &res) {
  19998. res.set_content(req.remote_addr, "text/plain");
  19999. });
  20000. auto port = svr.bind_to_any_port(HOST);
  20001. ASSERT_GT(port, 0);
  20002. thread t = thread([&] { svr.listen_after_bind(); });
  20003. auto se = detail::scope_exit([&] {
  20004. svr.stop();
  20005. t.join();
  20006. ASSERT_FALSE(svr.is_running());
  20007. });
  20008. svr.wait_until_ready();
  20009. Client cli(HOST, port);
  20010. auto res = cli.Get(
  20011. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20013. EXPECT_EQ("198.51.100.23", res->body);
  20014. }
  20015. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20016. Server svr;
  20017. // Include the loopback address the test client actually connects from, so
  20018. // the direct connection itself is recognized as the trusted proxy hop.
  20019. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20020. std::string observed_remote_addr;
  20021. std::string observed_xff;
  20022. svr.Get("/ip", [&](const Request &req, Response &res) {
  20023. observed_remote_addr = req.remote_addr;
  20024. observed_xff = req.get_header_value("X-Forwarded-For");
  20025. res.set_content("ok", "text/plain");
  20026. });
  20027. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20028. auto se = detail::scope_exit([&] {
  20029. svr.stop();
  20030. t.join();
  20031. ASSERT_FALSE(svr.is_running());
  20032. });
  20033. svr.wait_until_ready();
  20034. Client cli(HOST, PORT);
  20035. auto res = cli.Get(
  20036. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20038. EXPECT_EQ(StatusCode::OK_200, res->status);
  20039. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20040. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20041. }
  20042. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20043. Server svr;
  20044. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20045. std::string observed_remote_addr;
  20046. std::string observed_xff;
  20047. svr.Get("/ip", [&](const Request &req, Response &res) {
  20048. observed_remote_addr = req.remote_addr;
  20049. observed_xff = req.get_header_value("X-Forwarded-For");
  20050. res.set_content("ok", "text/plain");
  20051. });
  20052. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20053. auto se = detail::scope_exit([&] {
  20054. svr.stop();
  20055. t.join();
  20056. ASSERT_FALSE(svr.is_running());
  20057. });
  20058. svr.wait_until_ready();
  20059. Client cli(HOST, PORT);
  20060. auto res = cli.Get(
  20061. "/ip",
  20062. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20064. EXPECT_EQ(StatusCode::OK_200, res->status);
  20065. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20066. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20067. }
  20068. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20069. Server svr;
  20070. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20071. std::string observed_remote_addr;
  20072. std::string observed_xff;
  20073. svr.Get("/ip", [&](const Request &req, Response &res) {
  20074. observed_remote_addr = req.remote_addr;
  20075. observed_xff = req.get_header_value("X-Forwarded-For");
  20076. res.set_content("ok", "text/plain");
  20077. });
  20078. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20079. auto se = detail::scope_exit([&] {
  20080. svr.stop();
  20081. t.join();
  20082. ASSERT_FALSE(svr.is_running());
  20083. });
  20084. svr.wait_until_ready();
  20085. Client cli(HOST, PORT);
  20086. auto res = cli.Get(
  20087. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20089. EXPECT_EQ(StatusCode::OK_200, res->status);
  20090. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20091. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20092. // and must not be selected.
  20093. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20094. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20095. }
  20096. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20097. Server svr;
  20098. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20099. std::string observed_remote_addr;
  20100. svr.Get("/ip", [&](const Request &req, Response &res) {
  20101. observed_remote_addr = req.remote_addr;
  20102. res.set_content("ok", "text/plain");
  20103. });
  20104. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20105. auto se = detail::scope_exit([&] {
  20106. svr.stop();
  20107. t.join();
  20108. ASSERT_FALSE(svr.is_running());
  20109. });
  20110. svr.wait_until_ready();
  20111. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20112. // a forged address and the trusted proxy's own address; the forged value must
  20113. // not win over the address the trusted proxy actually recorded.
  20114. Client cli(HOST, PORT);
  20115. auto res = cli.Get(
  20116. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20118. EXPECT_EQ(StatusCode::OK_200, res->status);
  20119. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20120. }
  20121. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20122. Server svr;
  20123. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20124. std::string observed_remote_addr;
  20125. std::string observed_xff;
  20126. svr.Get("/ip", [&](const Request &req, Response &res) {
  20127. observed_remote_addr = req.remote_addr;
  20128. observed_xff = req.get_header_value("X-Forwarded-For");
  20129. res.set_content("ok", "text/plain");
  20130. });
  20131. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20132. auto se = detail::scope_exit([&] {
  20133. svr.stop();
  20134. t.join();
  20135. ASSERT_FALSE(svr.is_running());
  20136. });
  20137. svr.wait_until_ready();
  20138. Client cli(HOST, PORT);
  20139. auto res = cli.Get(
  20140. "/ip",
  20141. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20143. EXPECT_EQ(StatusCode::OK_200, res->status);
  20144. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20145. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20146. }
  20147. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20148. Server svr;
  20149. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20150. std::string observed_remote_addr;
  20151. std::string observed_xff;
  20152. svr.Get("/ip", [&](const Request &req, Response &res) {
  20153. observed_remote_addr = req.remote_addr;
  20154. observed_xff = req.get_header_value("X-Forwarded-For");
  20155. res.set_content("ok", "text/plain");
  20156. });
  20157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20158. auto se = detail::scope_exit([&] {
  20159. svr.stop();
  20160. t.join();
  20161. ASSERT_FALSE(svr.is_running());
  20162. });
  20163. svr.wait_until_ready();
  20164. std::string raw_req =
  20165. "GET /ip HTTP/1.1\r\n"
  20166. "Host: localhost\r\n"
  20167. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20168. "Connection: close\r\n"
  20169. "\r\n";
  20170. std::string out;
  20171. ASSERT_TRUE(send_request(5, raw_req, &out));
  20172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20173. // Header parser trims surrounding whitespace of the header value
  20174. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20175. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20176. }
  20177. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20178. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20179. // their own X-Forwarded-For as a separate field line rather than extending the
  20180. // one the client sent, so every occurrence has to be taken into account.
  20181. // Reading only the first one hands back the address the client chose.
  20182. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20183. Server svr;
  20184. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20185. std::string observed_remote_addr;
  20186. size_t observed_xff_count = 0;
  20187. svr.Get("/ip", [&](const Request &req, Response &res) {
  20188. observed_remote_addr = req.remote_addr;
  20189. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20190. res.set_content("ok", "text/plain");
  20191. });
  20192. auto port = svr.bind_to_any_port(HOST);
  20193. thread t = thread([&]() { svr.listen_after_bind(); });
  20194. auto se = detail::scope_exit([&] {
  20195. svr.stop();
  20196. t.join();
  20197. ASSERT_FALSE(svr.is_running());
  20198. });
  20199. svr.wait_until_ready();
  20200. // The client supplies the first field line; the trusted proxy appends the
  20201. // address it observed as a second one.
  20202. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20203. "Host: localhost\r\n"
  20204. "X-Forwarded-For: 1.2.3.4\r\n"
  20205. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20206. "Connection: close\r\n"
  20207. "\r\n";
  20208. std::string out;
  20209. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20210. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20211. EXPECT_EQ(observed_xff_count, 2U);
  20212. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20213. // The same chain spread over one field line per hop derives the same client
  20214. // address, i.e. the split and the comma-joined representations agree.
  20215. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20216. "Host: localhost\r\n"
  20217. "X-Forwarded-For: 1.2.3.4\r\n"
  20218. "X-Forwarded-For: 198.51.100.23\r\n"
  20219. "X-Forwarded-For: 192.0.2.45\r\n"
  20220. "Connection: close\r\n"
  20221. "\r\n";
  20222. out.clear();
  20223. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20224. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20225. EXPECT_EQ(observed_xff_count, 3U);
  20226. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20227. }
  20228. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20229. // crash the server (it used to call front() on an empty vector inside
  20230. // get_client_ip). The connection-level remote address must be retained instead.
  20231. static void run_malformed_xff_test(const std::string &xff_value) {
  20232. Server svr;
  20233. svr.set_trusted_proxies({"192.0.2.45"});
  20234. std::string observed_remote_addr;
  20235. svr.Get("/ip", [&](const Request &req, Response &res) {
  20236. observed_remote_addr = req.remote_addr;
  20237. res.set_content("ok", "text/plain");
  20238. });
  20239. int port = 0;
  20240. thread t = thread([&]() {
  20241. port = svr.bind_to_any_port(HOST);
  20242. svr.listen_after_bind();
  20243. });
  20244. auto se = detail::scope_exit([&] {
  20245. svr.stop();
  20246. t.join();
  20247. ASSERT_FALSE(svr.is_running());
  20248. });
  20249. svr.wait_until_ready();
  20250. Client cli(HOST, port);
  20251. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20253. EXPECT_EQ(StatusCode::OK_200, res->status);
  20254. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20255. observed_remote_addr == "127.0.0.1");
  20256. }
  20257. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20258. run_malformed_xff_test("");
  20259. }
  20260. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20261. run_malformed_xff_test(",");
  20262. }
  20263. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20264. run_malformed_xff_test(", , ,");
  20265. }
  20266. // The same rule applies to Accept: a request whose acceptable types are spread
  20267. // over several field lines must be negotiated against all of them.
  20268. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20269. // case-insensitive connection options. Comparing the whole field value against
  20270. // one option misses a client that sends several of them, and misses every
  20271. // casing but the one written in the comparison.
  20272. //
  20273. // Sends req, reads the response, then reuses the same socket for a second
  20274. // request to find out whether the server kept the connection.
  20275. static void probe_connection_reuse(int port, const std::string &req,
  20276. bool *announced_close, bool *reusable) {
  20277. auto error = Error::Success;
  20278. auto sock = detail::create_client_socket(
  20279. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20280. /*connection_timeout_sec=*/5, 0,
  20281. /*read_timeout_sec=*/1, 0,
  20282. /*write_timeout_sec=*/5, 0, std::string(), error);
  20283. ASSERT_NE(sock, INVALID_SOCKET);
  20284. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20285. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20286. "Host: localhost\r\n"
  20287. "Connection: close\r\n"
  20288. "\r\n";
  20289. std::string first_response;
  20290. std::string second_response;
  20291. detail::process_client_socket(
  20292. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20293. [&](Stream &strm) {
  20294. if (strm.write(req.data(), req.size()) !=
  20295. static_cast<ssize_t>(req.size())) {
  20296. return false;
  20297. }
  20298. char buf[512];
  20299. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20300. // Headers plus the two-byte body of the handler below
  20301. while (reader.getline()) {
  20302. first_response += reader.ptr();
  20303. if (first_response.find("ok") != std::string::npos) { break; }
  20304. }
  20305. if (strm.write(second.data(), second.size()) !=
  20306. static_cast<ssize_t>(second.size())) {
  20307. return true;
  20308. }
  20309. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20310. while (reader2.getline()) {
  20311. second_response += reader2.ptr();
  20312. if (second_response.find("ok") != std::string::npos) { break; }
  20313. }
  20314. return true;
  20315. });
  20316. *announced_close =
  20317. first_response.find("Connection: close") != std::string::npos;
  20318. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20319. }
  20320. class ConnectionTokenTest : public ::testing::Test {
  20321. protected:
  20322. void SetUp() override {
  20323. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20324. res.set_content("ok", "text/plain");
  20325. });
  20326. port_ = svr_.bind_to_any_port(HOST);
  20327. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20328. svr_.wait_until_ready();
  20329. }
  20330. void TearDown() override {
  20331. svr_.stop();
  20332. if (thread_.joinable()) { thread_.join(); }
  20333. }
  20334. Server svr_;
  20335. int port_ = 0;
  20336. thread thread_;
  20337. };
  20338. // "close" alongside another option still closes the connection, and the
  20339. // response says so rather than leaving the peer to discover it.
  20340. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20341. bool announced_close = false;
  20342. bool reusable = true;
  20343. probe_connection_reuse(port_,
  20344. "GET /keepalive HTTP/1.1\r\n"
  20345. "Host: localhost\r\n"
  20346. "Connection: keep-alive, close\r\n"
  20347. "\r\n",
  20348. &announced_close, &reusable);
  20349. EXPECT_TRUE(announced_close);
  20350. EXPECT_FALSE(reusable);
  20351. }
  20352. // "close" split over two field lines is the same list, so it is honored too.
  20353. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20354. bool announced_close = false;
  20355. bool reusable = true;
  20356. probe_connection_reuse(port_,
  20357. "GET /keepalive HTTP/1.1\r\n"
  20358. "Host: localhost\r\n"
  20359. "Connection: keep-alive\r\n"
  20360. "Connection: close\r\n"
  20361. "\r\n",
  20362. &announced_close, &reusable);
  20363. EXPECT_TRUE(announced_close);
  20364. EXPECT_FALSE(reusable);
  20365. }
  20366. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20367. // keep-alive in the spelling everyone actually sends keeps its connection.
  20368. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20369. bool announced_close = false;
  20370. bool reusable = false;
  20371. probe_connection_reuse(port_,
  20372. "GET /keepalive HTTP/1.0\r\n"
  20373. "Host: localhost\r\n"
  20374. "Connection: keep-alive\r\n"
  20375. "\r\n",
  20376. &announced_close, &reusable);
  20377. EXPECT_FALSE(announced_close);
  20378. EXPECT_TRUE(reusable);
  20379. }
  20380. // A token the value merely contains is not the token itself.
  20381. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20382. bool announced_close = false;
  20383. bool reusable = false;
  20384. probe_connection_reuse(port_,
  20385. "GET /keepalive HTTP/1.1\r\n"
  20386. "Host: localhost\r\n"
  20387. "Connection: notclose\r\n"
  20388. "\r\n",
  20389. &announced_close, &reusable);
  20390. EXPECT_FALSE(announced_close);
  20391. EXPECT_TRUE(reusable);
  20392. }
  20393. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20394. Server svr;
  20395. std::vector<std::string> observed_types;
  20396. svr.Get("/", [&](const Request &req, Response &res) {
  20397. observed_types = req.accept_content_types;
  20398. res.set_content("ok", "text/plain");
  20399. });
  20400. auto port = svr.bind_to_any_port(HOST);
  20401. thread t = thread([&]() { svr.listen_after_bind(); });
  20402. auto se = detail::scope_exit([&] {
  20403. svr.stop();
  20404. t.join();
  20405. ASSERT_FALSE(svr.is_running());
  20406. });
  20407. svr.wait_until_ready();
  20408. Client cli(HOST, port);
  20409. Headers headers;
  20410. headers.emplace("Accept", "text/plain;q=0.5");
  20411. headers.emplace("Accept", "application/json");
  20412. auto res = cli.Get("/", headers);
  20413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20414. EXPECT_EQ(StatusCode::OK_200, res->status);
  20415. // Sorted by q-value, so the second field line's type comes first
  20416. ASSERT_EQ(2U, observed_types.size());
  20417. EXPECT_EQ("application/json", observed_types[0]);
  20418. EXPECT_EQ("text/plain", observed_types[1]);
  20419. }
  20420. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20421. // empty field line must not contribute a bare comma to the combined value.
  20422. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20423. Server svr;
  20424. std::vector<std::string> observed_types;
  20425. svr.Get("/", [&](const Request &req, Response &res) {
  20426. observed_types = req.accept_content_types;
  20427. res.set_content("ok", "text/plain");
  20428. });
  20429. auto port = svr.bind_to_any_port(HOST);
  20430. thread t = thread([&]() { svr.listen_after_bind(); });
  20431. auto se = detail::scope_exit([&] {
  20432. svr.stop();
  20433. t.join();
  20434. ASSERT_FALSE(svr.is_running());
  20435. });
  20436. svr.wait_until_ready();
  20437. // Empty first field line, then a real one
  20438. std::string raw_req = "GET / HTTP/1.1\r\n"
  20439. "Host: localhost\r\n"
  20440. "Accept:\r\n"
  20441. "Accept: application/json\r\n"
  20442. "Connection: close\r\n"
  20443. "\r\n";
  20444. std::string out;
  20445. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20446. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20447. ASSERT_EQ(1U, observed_types.size());
  20448. EXPECT_EQ("application/json", observed_types[0]);
  20449. }
  20450. // The skip in get_combined_header_value() is what keeps an empty field line
  20451. // from contributing a bare comma. Only a trailing empty field line exercises
  20452. // it: a leading one is already covered by the "combined is still empty" check,
  20453. // and parse_accept_header() now ignores the empty element either way, so the
  20454. // request-level test above can no longer tell the two apart.
  20455. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20456. Headers headers;
  20457. headers.emplace("Accept", "text/html");
  20458. headers.emplace("Accept", "");
  20459. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20460. headers.clear();
  20461. headers.emplace("Accept", "");
  20462. headers.emplace("Accept", "application/json");
  20463. EXPECT_EQ("application/json",
  20464. detail::get_combined_header_value(headers, "Accept"));
  20465. }
  20466. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20467. // An encoding offered on a later Accept-Encoding field line is still offered.
  20468. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20469. Server svr;
  20470. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20471. res.set_content(std::string(1024, 'x'), "text/plain");
  20472. });
  20473. auto port = svr.bind_to_any_port(HOST);
  20474. thread t = thread([&]() { svr.listen_after_bind(); });
  20475. auto se = detail::scope_exit([&] {
  20476. svr.stop();
  20477. t.join();
  20478. ASSERT_FALSE(svr.is_running());
  20479. });
  20480. svr.wait_until_ready();
  20481. Client cli(HOST, port);
  20482. cli.set_decompress(false);
  20483. Headers headers;
  20484. headers.emplace("Accept-Encoding", "identity");
  20485. headers.emplace("Accept-Encoding", "gzip");
  20486. auto res = cli.Get("/", headers);
  20487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20488. EXPECT_EQ(StatusCode::OK_200, res->status);
  20489. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20490. }
  20491. #endif
  20492. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20493. // Transfer-Encoding is not its body.
  20494. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20495. Server svr;
  20496. svr.set_payload_max_length(8);
  20497. svr.Post("/test", [](const Request &, Response &res) {
  20498. res.set_content("ok", "text/plain");
  20499. });
  20500. auto port = svr.bind_to_any_port(HOST);
  20501. ASSERT_GT(port, 0);
  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. std::string resp;
  20510. ASSERT_TRUE(send_request(1,
  20511. "POST /test HTTP/1.1\r\n"
  20512. "Host: localhost\r\n"
  20513. "Connection: close\r\n"
  20514. "\r\n" +
  20515. std::string(16, 'X'),
  20516. &resp, port));
  20517. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20518. }
  20519. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20520. Server svr;
  20521. svr.Post("/post", [&](const Request &req, Response &res) {
  20522. res.set_content(req.body, "text/plain");
  20523. });
  20524. svr.Put("/put", [&](const Request &req, Response &res) {
  20525. res.set_content(req.body, "text/plain");
  20526. });
  20527. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20528. res.set_content(req.body, "text/plain");
  20529. });
  20530. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20531. res.set_content(req.body, "text/plain");
  20532. });
  20533. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20534. auto se = detail::scope_exit([&] {
  20535. svr.stop();
  20536. t.join();
  20537. ASSERT_FALSE(svr.is_running());
  20538. });
  20539. svr.wait_until_ready();
  20540. std::string resp;
  20541. // POST without Content-Length
  20542. ASSERT_TRUE(send_request(5,
  20543. "POST /post HTTP/1.1\r\n"
  20544. "Host: localhost\r\n"
  20545. "Connection: close\r\n"
  20546. "\r\n",
  20547. &resp));
  20548. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20549. // PUT without Content-Length
  20550. resp.clear();
  20551. ASSERT_TRUE(send_request(5,
  20552. "PUT /put HTTP/1.1\r\n"
  20553. "Host: localhost\r\n"
  20554. "Connection: close\r\n"
  20555. "\r\n",
  20556. &resp));
  20557. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20558. // PATCH without Content-Length
  20559. resp.clear();
  20560. ASSERT_TRUE(send_request(5,
  20561. "PATCH /patch HTTP/1.1\r\n"
  20562. "Host: localhost\r\n"
  20563. "Connection: close\r\n"
  20564. "\r\n",
  20565. &resp));
  20566. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20567. // DELETE without Content-Length
  20568. resp.clear();
  20569. ASSERT_TRUE(send_request(5,
  20570. "DELETE /delete HTTP/1.1\r\n"
  20571. "Host: localhost\r\n"
  20572. "Connection: close\r\n"
  20573. "\r\n",
  20574. &resp));
  20575. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20576. }
  20577. //==============================================================================
  20578. // open_stream() Tests
  20579. //==============================================================================
  20580. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20581. std::string result;
  20582. char buf[8192];
  20583. ssize_t n;
  20584. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20585. result.append(buf, static_cast<size_t>(n));
  20586. }
  20587. return result;
  20588. }
  20589. // Mock stream for unit tests
  20590. class MockStream : public Stream {
  20591. public:
  20592. std::string data;
  20593. size_t pos = 0;
  20594. ssize_t error_after = -1; // -1 = no error
  20595. explicit MockStream(const std::string &d, ssize_t err = -1)
  20596. : data(d), error_after(err) {}
  20597. bool is_readable() const override { return true; }
  20598. bool wait_readable() const override { return true; }
  20599. bool wait_writable() const override { return true; }
  20600. ssize_t read(char *ptr, size_t size) override {
  20601. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20602. if (pos >= data.size()) return 0;
  20603. size_t limit =
  20604. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20605. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20606. std::memcpy(ptr, data.data() + pos, to_read);
  20607. pos += to_read;
  20608. return static_cast<ssize_t>(to_read);
  20609. }
  20610. ssize_t write(const char *, size_t) override { return -1; }
  20611. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20612. ip = "127.0.0.1";
  20613. port = 0;
  20614. }
  20615. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20616. ip = "127.0.0.1";
  20617. port = 0;
  20618. }
  20619. socket_t socket() const override { return INVALID_SOCKET; }
  20620. time_t duration() const override { return 0; }
  20621. };
  20622. TEST(StreamHandleTest, Basic) {
  20623. ClientImpl::StreamHandle handle;
  20624. EXPECT_FALSE(handle.is_valid());
  20625. handle.response = detail::make_unique<Response>();
  20626. handle.error = Error::Connection;
  20627. EXPECT_FALSE(handle.is_valid());
  20628. handle.error = Error::Success;
  20629. EXPECT_TRUE(handle.is_valid());
  20630. }
  20631. TEST(BodyReaderTest, Basic) {
  20632. MockStream stream("Hello, World!");
  20633. detail::BodyReader reader;
  20634. reader.stream = &stream;
  20635. reader.content_length = 13;
  20636. char buf[32];
  20637. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20638. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20639. EXPECT_TRUE(reader.eof);
  20640. }
  20641. TEST(BodyReaderTest, NoStream) {
  20642. detail::BodyReader reader;
  20643. char buf[32];
  20644. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20645. EXPECT_EQ(Error::Connection, reader.last_error);
  20646. }
  20647. TEST(BodyReaderTest, Error) {
  20648. MockStream stream("Hello, World!", 5);
  20649. detail::BodyReader reader;
  20650. reader.stream = &stream;
  20651. reader.content_length = 13;
  20652. char buf[32];
  20653. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20654. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20655. EXPECT_EQ(Error::Read, reader.last_error);
  20656. }
  20657. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20658. // Mock-based StreamHandle tests relying on private internals are removed.
  20659. class OpenStreamTest : public ::testing::Test {
  20660. protected:
  20661. void SetUp() override {
  20662. svr_.Get("/hello", [](const Request &, Response &res) {
  20663. res.set_content("Hello World!", "text/plain");
  20664. });
  20665. svr_.Get("/large", [](const Request &, Response &res) {
  20666. res.set_content(std::string(10000, 'X'), "text/plain");
  20667. });
  20668. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20669. res.set_content("Hello World!", "image/jpeg");
  20670. res.set_header("Content-Encoding", "UTF-8");
  20671. });
  20672. svr_.Get("/chunked", [](const Request &, Response &res) {
  20673. res.set_chunked_content_provider("text/plain",
  20674. [](size_t offset, DataSink &sink) {
  20675. if (offset < 15) {
  20676. sink.write("chunk", 5);
  20677. return true;
  20678. }
  20679. sink.done();
  20680. return true;
  20681. });
  20682. });
  20683. svr_.Get("/compressible", [](const Request &, Response &res) {
  20684. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20685. DataSink &sink) {
  20686. if (offset < 100 * 1024) {
  20687. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20688. sink.write(chunk.data(), chunk.size());
  20689. return true;
  20690. }
  20691. sink.done();
  20692. return true;
  20693. });
  20694. });
  20695. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20696. [](const Request & /*req*/, Response &res) {
  20697. auto i = new int(0);
  20698. res.set_header("Trailer", "Content-Length, X-Allowed");
  20699. res.set_chunked_content_provider(
  20700. "text/plain",
  20701. [i](size_t /*offset*/, DataSink &sink) {
  20702. switch (*i) {
  20703. case 0: sink.os << "123"; break;
  20704. case 1: sink.os << "456"; break;
  20705. case 2: sink.os << "789"; break;
  20706. case 3: {
  20707. sink.done_with_trailer(
  20708. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20709. } break;
  20710. }
  20711. (*i)++;
  20712. return true;
  20713. },
  20714. [i](bool success) {
  20715. EXPECT_TRUE(success);
  20716. delete i;
  20717. });
  20718. });
  20719. // Echo headers endpoint for header-related tests
  20720. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20721. std::string body;
  20722. for (const auto &h : req.headers) {
  20723. body.append(h.first);
  20724. body.push_back(':');
  20725. body.append(h.second);
  20726. body.push_back('\n');
  20727. }
  20728. res.set_content(body, "text/plain");
  20729. });
  20730. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20731. std::string body;
  20732. for (const auto &h : req.headers) {
  20733. body.append(h.first);
  20734. body.push_back(':');
  20735. body.append(h.second);
  20736. body.push_back('\n');
  20737. }
  20738. res.set_content(body, "text/plain");
  20739. });
  20740. port_ = svr_.bind_to_any_port("127.0.0.1");
  20741. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20742. svr_.wait_until_ready();
  20743. }
  20744. void TearDown() override {
  20745. svr_.stop();
  20746. if (thread_.joinable()) thread_.join();
  20747. }
  20748. Server svr_;
  20749. std::thread thread_;
  20750. int port_ = 0;
  20751. };
  20752. TEST_F(OpenStreamTest, Basic) {
  20753. Client cli("127.0.0.1", port_);
  20754. auto handle = cli.open_stream("GET", "/hello");
  20755. EXPECT_TRUE(handle.is_valid());
  20756. EXPECT_EQ("Hello World!", read_all(handle));
  20757. }
  20758. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20759. Client cli("127.0.0.1", port_);
  20760. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20761. ASSERT_TRUE(handle.is_valid());
  20762. EXPECT_EQ("Hello World!", read_all(handle));
  20763. }
  20764. TEST_F(OpenStreamTest, SmallBuffer) {
  20765. Client cli("127.0.0.1", port_);
  20766. auto handle = cli.open_stream("GET", "/hello");
  20767. std::string result;
  20768. char buf[4];
  20769. ssize_t n;
  20770. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20771. result.append(buf, static_cast<size_t>(n));
  20772. EXPECT_EQ("Hello World!", result);
  20773. }
  20774. TEST_F(OpenStreamTest, DefaultHeaders) {
  20775. Client cli("127.0.0.1", port_);
  20776. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20777. {
  20778. auto handle = cli.open_stream("GET", "/echo-headers");
  20779. ASSERT_TRUE(handle.is_valid());
  20780. auto body = read_all(handle);
  20781. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20782. std::string::npos);
  20783. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20784. std::string::npos);
  20785. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20786. }
  20787. // open_stream POST with body and no explicit content_type should NOT add
  20788. // text/plain Content-Type (behavior differs from non-streaming path), but
  20789. // should include Content-Length
  20790. {
  20791. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20792. ASSERT_TRUE(handle.is_valid());
  20793. auto body = read_all(handle);
  20794. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20795. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20796. }
  20797. // open_stream POST with explicit Content-Type should preserve it
  20798. {
  20799. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20800. {{"Content-Type", "application/custom"}},
  20801. "{}", "application/custom");
  20802. ASSERT_TRUE(handle.is_valid());
  20803. auto body = read_all(handle);
  20804. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20805. }
  20806. // User-specified User-Agent must not be overwritten for stream API
  20807. {
  20808. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20809. {{"User-Agent", "MyAgent/1.2"}});
  20810. ASSERT_TRUE(handle.is_valid());
  20811. auto body = read_all(handle);
  20812. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20813. }
  20814. }
  20815. TEST_F(OpenStreamTest, Large) {
  20816. Client cli("127.0.0.1", port_);
  20817. auto handle = cli.open_stream("GET", "/large");
  20818. EXPECT_EQ(10000u, read_all(handle).size());
  20819. }
  20820. TEST_F(OpenStreamTest, ConnectionError) {
  20821. Client cli("127.0.0.1", 9999);
  20822. auto handle = cli.open_stream("GET", "/hello");
  20823. EXPECT_FALSE(handle.is_valid());
  20824. }
  20825. TEST_F(OpenStreamTest, Chunked) {
  20826. Client cli("127.0.0.1", port_);
  20827. auto handle = cli.open_stream("GET", "/chunked");
  20828. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20829. "Transfer-Encoding") == "chunked");
  20830. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20831. }
  20832. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20833. Client cli("127.0.0.1", port_);
  20834. auto handle =
  20835. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20836. ASSERT_TRUE(handle.is_valid());
  20837. // Consume body to allow trailers to be received/parsed
  20838. auto body = read_all(handle);
  20839. // Explicitly parse trailers (ensure trailers are available for assertion)
  20840. handle.parse_trailers_if_needed();
  20841. EXPECT_EQ(std::string("123456789"), body);
  20842. // The response should include a Trailer header declaring both names
  20843. ASSERT_TRUE(handle.response);
  20844. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20845. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20846. handle.response->get_header_value("Trailer"));
  20847. // Prohibited trailer must not be present
  20848. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20849. // Allowed trailer should be present
  20850. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20851. EXPECT_EQ(std::string("yes"),
  20852. handle.response->get_trailer_value("X-Allowed"));
  20853. // Verify trailers are NOT present as regular headers
  20854. EXPECT_EQ(std::string(""),
  20855. handle.response->get_header_value("Content-Length"));
  20856. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20857. }
  20858. // Accepts one connection on an OS-assigned port, which it hands over through
  20859. // port_promise, reads the request head and sends back response. after_send,
  20860. // if given, runs on the connection before it is closed.
  20861. static std::thread
  20862. serve_single_response(std::promise<int> &port_promise,
  20863. const std::string &response,
  20864. std::function<void(socket_t)> after_send = nullptr) {
  20865. return std::thread([&port_promise, response, after_send] {
  20866. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20867. default_socket_options(srv);
  20868. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20869. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20870. sockaddr_in addr{};
  20871. addr.sin_family = AF_INET;
  20872. addr.sin_port = htons(0); // Let OS assign a free port
  20873. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20874. int opt = 1;
  20875. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20876. #ifdef _WIN32
  20877. reinterpret_cast<const char *>(&opt),
  20878. #else
  20879. &opt,
  20880. #endif
  20881. sizeof(opt));
  20882. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20883. ::listen(srv, 1) != 0) {
  20884. port_promise.set_value(-1);
  20885. detail::close_socket(srv);
  20886. return;
  20887. }
  20888. socklen_t addr_len = sizeof(addr);
  20889. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20890. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20891. sockaddr_in cli_addr{};
  20892. socklen_t cli_len = sizeof(cli_addr);
  20893. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20894. if (cli != INVALID_SOCKET) {
  20895. // Read the complete HTTP request (until the blank line that terminates
  20896. // headers) before sending the response. If the server closes the socket
  20897. // while the client's request data is still unread in the kernel receive
  20898. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20899. // connection on both sides: it discards the client's receive buffer
  20900. // (which already holds our response) and causes any in-progress write on
  20901. // the client to fail with ECONNRESET. Reading all request data first
  20902. // ensures close() emits a graceful FIN.
  20903. {
  20904. char rbuf[256];
  20905. std::string req;
  20906. while (req.find("\r\n\r\n") == std::string::npos) {
  20907. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20908. if (n <= 0) { break; }
  20909. req.append(rbuf, static_cast<size_t>(n));
  20910. }
  20911. }
  20912. ::send(cli,
  20913. #ifdef _WIN32
  20914. static_cast<const char *>(response.c_str()),
  20915. static_cast<int>(response.size()),
  20916. #else
  20917. response.c_str(), response.size(),
  20918. #endif
  20919. 0);
  20920. if (after_send) { after_send(cli); }
  20921. detail::close_socket(cli);
  20922. }
  20923. detail::close_socket(srv);
  20924. });
  20925. }
  20926. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20927. #ifndef _WIN32
  20928. signal(SIGPIPE, SIG_IGN);
  20929. #endif
  20930. std::promise<int> port_promise;
  20931. auto port_future = port_promise.get_future();
  20932. auto server_thread =
  20933. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20934. "Content-Type: text/plain\r\n"
  20935. "Content-Length: not-a-number\r\n"
  20936. "Connection: close\r\n"
  20937. "\r\n"
  20938. "hello");
  20939. auto port = port_future.get();
  20940. ASSERT_GT(port, 0);
  20941. Client cli("127.0.0.1", port);
  20942. auto handle = cli.open_stream("GET", "/");
  20943. EXPECT_FALSE(handle.is_valid());
  20944. server_thread.join();
  20945. }
  20946. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20947. #ifndef _WIN32
  20948. signal(SIGPIPE, SIG_IGN);
  20949. #endif
  20950. std::promise<int> port_promise;
  20951. auto port_future = port_promise.get_future();
  20952. auto server_thread = serve_single_response(
  20953. port_promise, "HTTP/1.1 200 OK\r\n"
  20954. "Content-Type: text/plain\r\n"
  20955. "Content-Length: 99999999999999999999999999\r\n"
  20956. "Connection: close\r\n"
  20957. "\r\n"
  20958. "hello");
  20959. auto port = port_future.get();
  20960. ASSERT_GT(port, 0);
  20961. // Historically std::stoull would throw std::out_of_range here and crash
  20962. // the process, then parsing silently clamped to a bogus framing length and
  20963. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20964. // so the stream fails to open, matching the not-a-number case above. The
  20965. // process still must NOT terminate.
  20966. Client cli("127.0.0.1", port);
  20967. auto handle = cli.open_stream("GET", "/");
  20968. EXPECT_FALSE(handle.is_valid());
  20969. server_thread.join();
  20970. }
  20971. #ifndef _WIN32
  20972. // As above for the body of a streamed request: a send() cut short by the write
  20973. // timeout must not leave the rest of the body unsent.
  20974. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20975. signal(SIGPIPE, SIG_IGN);
  20976. Server svr;
  20977. svr.set_socket_options([](socket_t sock) {
  20978. int size = 8192;
  20979. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20980. reinterpret_cast<const char *>(&size), sizeof(size));
  20981. });
  20982. svr.Post("/size", [](const Request &, Response &res,
  20983. const ContentReader &content_reader) {
  20984. // Outlast the client's write timeout before reading the body.
  20985. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20986. size_t received = 0;
  20987. content_reader([&](const char *, size_t len) {
  20988. received += len;
  20989. return true;
  20990. });
  20991. res.set_content(std::to_string(received), "text/plain");
  20992. });
  20993. auto port = svr.bind_to_any_port(HOST);
  20994. std::thread t([&]() { svr.listen_after_bind(); });
  20995. auto se = detail::scope_exit([&] {
  20996. svr.stop();
  20997. t.join();
  20998. });
  20999. svr.wait_until_ready();
  21000. Client cli(HOST, port);
  21001. cli.set_write_timeout(0, 500000);
  21002. cli.set_socket_options([](socket_t sock) {
  21003. int size = 8192;
  21004. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21005. reinterpret_cast<const char *>(&size), sizeof(size));
  21006. });
  21007. const std::string body(4 * 1024 * 1024, 'A');
  21008. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21009. "application/octet-stream");
  21010. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21011. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21012. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21013. }
  21014. #endif
  21015. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21016. std::promise<void> slow_started;
  21017. auto slow_started_future = slow_started.get_future();
  21018. Server svr;
  21019. svr.Get("/slow", [&](const Request &, Response &res) {
  21020. slow_started.set_value();
  21021. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21022. res.set_content("slow", "text/plain");
  21023. });
  21024. svr.Get("/fast", [](const Request &, Response &res) {
  21025. res.set_content("fast", "text/plain");
  21026. });
  21027. auto port = svr.bind_to_any_port(HOST);
  21028. std::thread t([&]() { svr.listen_after_bind(); });
  21029. auto se = detail::scope_exit([&] {
  21030. svr.stop();
  21031. t.join();
  21032. });
  21033. svr.wait_until_ready();
  21034. Client cli(HOST, port);
  21035. std::string slow_body;
  21036. std::thread slow_thread([&] {
  21037. auto res = cli.Get("/slow");
  21038. if (res) { slow_body = res->body; }
  21039. });
  21040. slow_started_future.wait();
  21041. auto result = stream::Get(cli, "/fast");
  21042. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21043. slow_thread.join();
  21044. EXPECT_EQ("slow", slow_body);
  21045. EXPECT_EQ("fast", fast_body);
  21046. }
  21047. // Serves `response` to the single request `fn` makes with a fresh client.
  21048. template <typename Fn>
  21049. static void with_single_response(const std::string &response, Fn fn) {
  21050. #ifndef _WIN32
  21051. signal(SIGPIPE, SIG_IGN);
  21052. #endif
  21053. std::promise<int> port_promise;
  21054. auto port_future = port_promise.get_future();
  21055. auto server_thread = serve_single_response(port_promise, response);
  21056. auto se = detail::scope_exit([&] { server_thread.join(); });
  21057. auto port = port_future.get();
  21058. ASSERT_GT(port, 0);
  21059. Client cli("127.0.0.1", port);
  21060. fn(cli);
  21061. }
  21062. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21063. // too, also in a build without the decoder for the advertised coding.
  21064. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21065. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21066. const auto response = "HTTP/1.1 200 OK\r\n"
  21067. "Content-Encoding: gzip\r\n"
  21068. "Content-Length: " +
  21069. std::to_string(gzipped.size()) +
  21070. "\r\n"
  21071. "Connection: close\r\n\r\n" +
  21072. gzipped;
  21073. with_single_response(response, [&](Client &cli) {
  21074. cli.set_decompress(false);
  21075. auto handle = cli.open_stream("GET", "/");
  21076. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21077. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21078. EXPECT_EQ(gzipped, read_all(handle));
  21079. EXPECT_FALSE(handle.has_read_error());
  21080. });
  21081. with_single_response(response, [&](Client &cli) {
  21082. cli.set_decompress(false);
  21083. auto res = stream::Get(cli, "/", 7);
  21084. ASSERT_TRUE(res) << to_string(res.error());
  21085. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21086. EXPECT_EQ(gzipped, res.read_all());
  21087. EXPECT_FALSE(res.has_read_error());
  21088. });
  21089. }
  21090. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21091. // Neither Content-Length nor chunked: the body ends at the close
  21092. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21093. "Connection: close\r\n"
  21094. "\r\n"
  21095. "hello";
  21096. with_single_response(close_delimited, [](Client &cli) {
  21097. auto handle = cli.open_stream("GET", "/");
  21098. ASSERT_TRUE(handle.is_valid());
  21099. EXPECT_EQ("hello", read_all(handle));
  21100. EXPECT_FALSE(handle.has_read_error());
  21101. });
  21102. // A close before the end of the Content-Length is still an error
  21103. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21104. "Content-Length: 10\r\n"
  21105. "\r\n"
  21106. "hello";
  21107. with_single_response(short_content_length, [](Client &cli) {
  21108. auto handle = cli.open_stream("GET", "/");
  21109. ASSERT_TRUE(handle.is_valid());
  21110. read_all(handle);
  21111. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21112. });
  21113. // So is a close before the last chunk
  21114. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21115. "Transfer-Encoding: chunked\r\n"
  21116. "\r\n"
  21117. "5\r\nhello\r\n";
  21118. with_single_response(short_chunked, [](Client &cli) {
  21119. auto handle = cli.open_stream("GET", "/");
  21120. ASSERT_TRUE(handle.is_valid());
  21121. read_all(handle);
  21122. EXPECT_TRUE(handle.has_read_error());
  21123. });
  21124. }
  21125. #ifdef CPPHTTPLIB_SSL_ENABLED
  21126. // Serves `response` to one request, then closes with or without a close_notify
  21127. template <typename Fn>
  21128. static void with_single_tls_response(const std::string &response,
  21129. bool close_notify, Fn fn) {
  21130. #ifndef _WIN32
  21131. signal(SIGPIPE, SIG_IGN);
  21132. #endif
  21133. std::promise<int> port_promise;
  21134. auto port_future = port_promise.get_future();
  21135. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21136. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21137. default_socket_options(srv);
  21138. sockaddr_in addr{};
  21139. addr.sin_family = AF_INET;
  21140. addr.sin_port = htons(0);
  21141. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21142. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21143. ::listen(srv, 1) != 0) {
  21144. port_promise.set_value(-1);
  21145. detail::close_socket(srv);
  21146. return;
  21147. }
  21148. socklen_t addr_len = sizeof(addr);
  21149. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21150. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21151. auto cli = ::accept(srv, nullptr, nullptr);
  21152. if (cli != INVALID_SOCKET) {
  21153. auto ctx = tls::create_server_context();
  21154. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21155. nullptr);
  21156. auto session = tls::create_session(ctx, cli);
  21157. tls::TlsError err;
  21158. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21159. // The request head first, so that closing the socket sends a FIN
  21160. // rather than an RST for the unread bytes.
  21161. std::string req;
  21162. char buf[256];
  21163. while (req.find("\r\n\r\n") == std::string::npos) {
  21164. auto n = tls::read(session, buf, sizeof(buf), err);
  21165. if (n <= 0) { break; }
  21166. req.append(buf, static_cast<size_t>(n));
  21167. }
  21168. size_t sent = 0;
  21169. while (sent < response.size()) {
  21170. auto n = tls::write(session, response.data() + sent,
  21171. response.size() - sent, err);
  21172. if (n <= 0) { break; }
  21173. sent += static_cast<size_t>(n);
  21174. }
  21175. if (close_notify) { tls::shutdown(session, true); }
  21176. }
  21177. tls::free_session(session);
  21178. detail::close_socket(cli);
  21179. tls::free_context(ctx);
  21180. }
  21181. detail::close_socket(srv);
  21182. });
  21183. auto se = detail::scope_exit([&] { server_thread.join(); });
  21184. auto port = port_future.get();
  21185. ASSERT_GT(port, 0);
  21186. SSLClient cli("127.0.0.1", port);
  21187. cli.enable_server_certificate_verification(false);
  21188. fn(cli);
  21189. }
  21190. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21191. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21192. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21193. "Connection: close\r\n"
  21194. "\r\n"
  21195. "hello";
  21196. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21197. auto res = cli.Get("/");
  21198. ASSERT_TRUE(res) << to_string(res.error());
  21199. EXPECT_EQ("hello", res->body);
  21200. });
  21201. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21202. auto res = cli.Get("/");
  21203. ASSERT_FALSE(res);
  21204. EXPECT_EQ(Error::Read, res.error());
  21205. });
  21206. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21207. auto handle = cli.open_stream("GET", "/");
  21208. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21209. read_all(handle);
  21210. EXPECT_TRUE(handle.has_read_error());
  21211. });
  21212. // A framed body ends where its framing says, with or without the alert
  21213. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21214. "Content-Length: 5\r\n"
  21215. "Connection: close\r\n"
  21216. "\r\n"
  21217. "hello";
  21218. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21219. auto res = cli.Get("/");
  21220. ASSERT_TRUE(res) << to_string(res.error());
  21221. EXPECT_EQ("hello", res->body);
  21222. });
  21223. }
  21224. #endif
  21225. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21226. const char *responses[] = {
  21227. "HTTP/1.1 103 Early Hints\r\n"
  21228. "Link: </style.css>; rel=preload\r\n"
  21229. "\r\n"
  21230. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21231. "HTTP/1.1 100 Continue\r\n"
  21232. "X-Note: interim\r\n"
  21233. "\r\n"
  21234. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21235. };
  21236. for (auto response : responses) {
  21237. with_single_response(response, [](Client &cli) {
  21238. auto res = cli.Get("/");
  21239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21240. EXPECT_EQ(StatusCode::OK_200, res->status);
  21241. EXPECT_EQ("ok", res->body);
  21242. });
  21243. }
  21244. }
  21245. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21246. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21247. const std::string final_response =
  21248. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21249. std::string interims;
  21250. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21251. interims += interim;
  21252. }
  21253. with_single_response(interims + final_response, [](Client &cli) {
  21254. auto res = cli.Get("/");
  21255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21256. EXPECT_EQ("ok", res->body);
  21257. });
  21258. with_single_response(interims + interim + final_response, [](Client &cli) {
  21259. auto res = cli.Get("/");
  21260. ASSERT_FALSE(res);
  21261. EXPECT_EQ(Error::Read, res.error());
  21262. });
  21263. }
  21264. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21265. #ifndef _WIN32
  21266. signal(SIGPIPE, SIG_IGN);
  21267. #endif
  21268. // The server answers the head without asking for the body. Bytes it then
  21269. // reads on the connection would be taken for the body the request declared.
  21270. auto closed_by_client = false;
  21271. std::promise<int> port_promise;
  21272. auto server_thread = serve_single_response(
  21273. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21274. [&](socket_t sock) {
  21275. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21276. char buf[256];
  21277. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21278. });
  21279. Client cli("127.0.0.1", port_promise.get_future().get());
  21280. cli.set_keep_alive(true);
  21281. cli.set_read_timeout(1, 0);
  21282. // Long enough for the client to send Expect: 100-continue.
  21283. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21285. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21286. cli.Get("/second");
  21287. server_thread.join();
  21288. EXPECT_TRUE(closed_by_client);
  21289. }
  21290. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21291. // Long enough for the client to send Expect: 100-continue
  21292. with_single_response(
  21293. "HTTP/1.1 103 Early Hints\r\n"
  21294. "Link: </style.css>; rel=preload\r\n"
  21295. "\r\n"
  21296. "HTTP/1.1 401 Unauthorized\r\n"
  21297. "Content-Length: 0\r\n\r\n",
  21298. [](Client &cli) {
  21299. cli.set_read_timeout(2, 0);
  21300. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21302. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21303. });
  21304. }
  21305. #ifdef CPPHTTPLIB_SSL_ENABLED
  21306. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21307. #ifndef _WIN32
  21308. signal(SIGPIPE, SIG_IGN);
  21309. #endif
  21310. auto reused = false;
  21311. std::promise<int> port_promise;
  21312. auto server_thread = serve_single_response(
  21313. port_promise,
  21314. "HTTP/1.1 401 Unauthorized\r\n"
  21315. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21316. "Content-Length: 0\r\n\r\n",
  21317. [&](socket_t sock) {
  21318. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21319. char buf[256];
  21320. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21321. });
  21322. Client cli("127.0.0.1", port_promise.get_future().get());
  21323. cli.set_keep_alive(true);
  21324. cli.set_digest_auth("user", "pass");
  21325. cli.set_read_timeout(1, 0);
  21326. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21327. server_thread.join();
  21328. EXPECT_FALSE(reused);
  21329. }
  21330. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21331. // Any other answer to CONNECT would read as the origin's response.
  21332. struct {
  21333. const char *response;
  21334. bool passed_on;
  21335. } cases[] = {
  21336. {"HTTP/1.1 201 Created\r\n"
  21337. "Set-Cookie: session=from-proxy\r\n"
  21338. "Content-Length: 0\r\n\r\n",
  21339. false},
  21340. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21341. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21342. "Content-Length: 0\r\n\r\n",
  21343. true},
  21344. };
  21345. for (const auto &c : cases) {
  21346. std::promise<int> port_promise;
  21347. auto server_thread = serve_single_response(port_promise, c.response);
  21348. SSLClient cli("example.com", 443);
  21349. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21350. auto res = cli.Get("/");
  21351. server_thread.join();
  21352. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21353. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21354. if (res) {
  21355. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21356. }
  21357. }
  21358. }
  21359. #endif
  21360. // Records the client's error logger calls as "error METHOD path", or
  21361. // "error null" for a call without a request
  21362. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21363. return [&log](const Error &err, const Request *req) {
  21364. log.push_back(to_string(err) + " " +
  21365. (req ? req->method + " " + req->path : "null"));
  21366. };
  21367. }
  21368. // A failed request is reported once, with the request the caller made
  21369. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21370. Server svr;
  21371. svr.Get("/big", [](const Request &, Response &res) {
  21372. res.set_content(std::string(100000, 'b'), "text/plain");
  21373. });
  21374. auto port = svr.bind_to_any_port(HOST);
  21375. std::thread t([&]() { svr.listen_after_bind(); });
  21376. auto se = detail::scope_exit([&] {
  21377. svr.stop();
  21378. t.join();
  21379. });
  21380. svr.wait_until_ready();
  21381. Client cli(HOST, port);
  21382. std::vector<std::string> log;
  21383. cli.set_error_logger(record_errors(log));
  21384. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21385. cli.Get("/big", [](const char *, size_t) { return false; });
  21386. EXPECT_EQ(expected, log);
  21387. log.clear();
  21388. cli.Get("/big", [](size_t, size_t) { return false; });
  21389. EXPECT_EQ(expected, log);
  21390. }
  21391. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21392. // Fails while the body is read
  21393. auto broken = [](const Request &, Response &res) {
  21394. res.set_content_provider(10, "text/plain",
  21395. [](size_t, size_t, DataSink &) { return false; });
  21396. };
  21397. Server other;
  21398. other.Get("/broken", broken);
  21399. auto other_port = other.bind_to_any_port(HOST);
  21400. std::thread other_t([&]() { other.listen_after_bind(); });
  21401. auto other_se = detail::scope_exit([&] {
  21402. other.stop();
  21403. other_t.join();
  21404. });
  21405. other.wait_until_ready();
  21406. Server svr;
  21407. svr.Get("/broken", broken);
  21408. svr.Get("/same-origin",
  21409. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21410. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21411. res.set_redirect("http://" + std::string(HOST) + ":" +
  21412. std::to_string(other_port) + "/broken");
  21413. });
  21414. auto port = svr.bind_to_any_port(HOST);
  21415. std::thread t([&]() { svr.listen_after_bind(); });
  21416. auto se = detail::scope_exit([&] {
  21417. svr.stop();
  21418. t.join();
  21419. });
  21420. svr.wait_until_ready();
  21421. Client cli(HOST, port);
  21422. cli.set_follow_location(true);
  21423. std::vector<std::string> log;
  21424. cli.set_error_logger(record_errors(log));
  21425. for (auto path : {"/same-origin", "/cross-origin"}) {
  21426. log.clear();
  21427. auto res = cli.Get(path);
  21428. ASSERT_FALSE(res);
  21429. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21430. log);
  21431. }
  21432. }
  21433. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21434. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21435. std::vector<std::string> log;
  21436. cli.set_error_logger(record_errors(log));
  21437. auto handle = cli.open_stream("GET", "/x");
  21438. EXPECT_FALSE(handle.is_valid());
  21439. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21440. log);
  21441. });
  21442. }
  21443. #ifdef CPPHTTPLIB_SSL_ENABLED
  21444. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21445. // Not a TLS server, so the handshake fails. It waits for a request line in
  21446. // the handshake bytes, so a short read timeout lets it close quickly.
  21447. Server svr;
  21448. svr.set_read_timeout(0, 100000);
  21449. svr.Get("/x", [](const Request &, Response &res) {
  21450. res.set_content("x", "text/plain");
  21451. });
  21452. auto port = svr.bind_to_any_port(HOST);
  21453. std::thread t([&]() { svr.listen_after_bind(); });
  21454. auto se = detail::scope_exit([&] {
  21455. svr.stop();
  21456. t.join();
  21457. });
  21458. svr.wait_until_ready();
  21459. std::vector<std::string> log;
  21460. SSLClient cli(HOST, port);
  21461. cli.enable_server_certificate_verification(false);
  21462. cli.set_error_logger(record_errors(log));
  21463. auto res = cli.Get("/x");
  21464. ASSERT_FALSE(res);
  21465. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21466. log.clear();
  21467. auto handle = cli.open_stream("GET", "/x");
  21468. EXPECT_FALSE(handle.is_valid());
  21469. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21470. log.clear();
  21471. SSLClient no_ca(HOST, port);
  21472. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21473. no_ca.set_error_logger(record_errors(log));
  21474. res = no_ca.Get("/x");
  21475. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21476. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21477. }
  21478. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21479. #ifndef _WIN32
  21480. signal(SIGPIPE, SIG_IGN);
  21481. #endif
  21482. // Refused, answered with a challenge, or closed without an answer
  21483. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21484. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21485. "Content-Length: 0\r\n\r\n",
  21486. ""}) {
  21487. std::promise<int> port_promise;
  21488. auto server_thread = serve_single_response(port_promise, response);
  21489. SSLClient cli("example.com", 443);
  21490. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21491. std::vector<std::string> log;
  21492. cli.set_error_logger(record_errors(log));
  21493. auto res = cli.Get("/");
  21494. server_thread.join();
  21495. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21496. << response;
  21497. }
  21498. }
  21499. #endif
  21500. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21501. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21502. // the chunked coding and drop Content-Length, so a front-end that trusts
  21503. // Content-Length would disagree about where the body ends (response
  21504. // smuggling). The client must reject such a response.
  21505. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21506. for (const char *te : {"chunked", "gzip, chunked"}) {
  21507. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21508. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21509. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21510. "5\r\nhello\r\n0\r\n\r\n";
  21511. with_single_response(response, [&](Client &cli) {
  21512. auto res = cli.Get("/");
  21513. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21514. EXPECT_EQ(Error::Read, res.error()) << te;
  21515. });
  21516. with_single_response(response, [&](Client &cli) {
  21517. auto handle = cli.open_stream("GET", "/");
  21518. EXPECT_FALSE(handle.is_valid()) << te;
  21519. EXPECT_EQ(Error::Read, handle.error) << te;
  21520. });
  21521. }
  21522. }
  21523. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21524. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21525. // closing the connection (unlike a request, which must be rejected).
  21526. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21527. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21528. "Transfer-Encoding: chunked\r\n"
  21529. "Connection: close\r\n"
  21530. "\r\n"
  21531. "5\r\nhello\r\n0\r\n\r\n",
  21532. "HTTP/1.1 200 OK\r\n"
  21533. "Transfer-Encoding: gzip\r\n"
  21534. "Connection: close\r\n"
  21535. "\r\n"
  21536. "hello"}) {
  21537. with_single_response(response, [&](Client &cli) {
  21538. auto res = cli.Get("/");
  21539. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21540. EXPECT_EQ("hello", res->body);
  21541. });
  21542. with_single_response(response, [&](Client &cli) {
  21543. auto handle = cli.open_stream("GET", "/");
  21544. ASSERT_TRUE(handle.is_valid()) << response;
  21545. EXPECT_EQ("hello", read_all(handle));
  21546. });
  21547. }
  21548. }
  21549. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21550. // framing headers describe nothing to read and must not be rejected.
  21551. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21552. const std::string framing = "Content-Length: 5\r\n"
  21553. "Transfer-Encoding: chunked\r\n"
  21554. "Connection: close\r\n"
  21555. "\r\n";
  21556. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21557. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21558. });
  21559. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21560. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21561. });
  21562. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21563. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21564. with_single_response(response, [&](Client &cli) {
  21565. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21566. });
  21567. with_single_response(response, [&](Client &cli) {
  21568. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21569. });
  21570. }
  21571. }
  21572. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21573. // header section, so a stream opened on one has nothing to read, whatever
  21574. // framing or coding headers it carries.
  21575. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21576. struct Case {
  21577. const char *method;
  21578. const char *status;
  21579. };
  21580. // A reader of the declared body reports an early close when nothing
  21581. // follows, and hands back what does.
  21582. struct Framing {
  21583. const char *headers;
  21584. const char *after;
  21585. };
  21586. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21587. Case{"GET", "304 Not Modified"}}) {
  21588. for (const auto &f :
  21589. {Framing{"Content-Length: 5\r\n", ""},
  21590. Framing{"Content-Length: 5\r\n", "hello"},
  21591. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21592. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21593. // Not decoded, so a build without Brotli opens it too
  21594. Framing{"Content-Encoding: br\r\n", ""}}) {
  21595. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21596. "Connection: close\r\n"
  21597. "\r\n" +
  21598. f.after;
  21599. with_single_response(response, [&](Client &cli) {
  21600. auto handle = cli.open_stream(c.method, "/");
  21601. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21602. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21603. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21604. });
  21605. }
  21606. }
  21607. }
  21608. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21609. // response, is faulty framing, so the connection is not reused after it.
  21610. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21611. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21612. "Content-Length: 0\r\n"
  21613. "Transfer-Encoding: chunked\r\n"
  21614. "\r\n"
  21615. "5\r\nhello\r\n0\r\n\r\n",
  21616. "HTTP/1.0 200 Connection established\r\n"
  21617. "Connection: keep-alive\r\n"
  21618. "Transfer-Encoding: chunked\r\n"
  21619. "\r\n"
  21620. "5\r\nhello\r\n0\r\n\r\n"}) {
  21621. with_single_response(response, [&](Client &cli) {
  21622. cli.set_keep_alive(true);
  21623. auto res = cli.Get("/");
  21624. ASSERT_TRUE(res) << response;
  21625. EXPECT_EQ("hello", res->body);
  21626. EXPECT_FALSE(cli.is_socket_open()) << response;
  21627. });
  21628. }
  21629. }
  21630. // A payload max length of 0 means no limit, however the body is framed.
  21631. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21632. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21633. "Transfer-Encoding: chunked\r\n"
  21634. "\r\n"
  21635. "5\r\nhello\r\n0\r\n\r\n",
  21636. "HTTP/1.1 200 OK\r\n"
  21637. "Connection: close\r\n"
  21638. "\r\n"
  21639. "hello"}) {
  21640. with_single_response(response, [&](Client &cli) {
  21641. cli.set_payload_max_length(0);
  21642. auto res = cli.Get("/");
  21643. ASSERT_TRUE(res) << response;
  21644. EXPECT_EQ("hello", res->body) << response;
  21645. });
  21646. }
  21647. }
  21648. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21649. Server svr;
  21650. svr.set_payload_max_length(0);
  21651. svr.Post("/echo", [](const Request &req, Response &res) {
  21652. res.set_content(req.body, "text/plain");
  21653. });
  21654. auto port = svr.bind_to_any_port(HOST);
  21655. thread t = thread([&] { svr.listen_after_bind(); });
  21656. auto se = detail::scope_exit([&] {
  21657. svr.stop();
  21658. t.join();
  21659. ASSERT_FALSE(svr.is_running());
  21660. });
  21661. svr.wait_until_ready();
  21662. Client cli(HOST, port);
  21663. auto res = cli.Post(
  21664. "/echo",
  21665. [](size_t /*offset*/, DataSink &sink) {
  21666. sink.write("hello", 5);
  21667. sink.done();
  21668. return true;
  21669. },
  21670. "text/plain");
  21671. ASSERT_TRUE(res);
  21672. EXPECT_EQ(StatusCode::OK_200, res->status);
  21673. EXPECT_EQ("hello", res->body);
  21674. }
  21675. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21676. TEST_F(OpenStreamTest, Gzip) {
  21677. Client cli("127.0.0.1", port_);
  21678. auto handle = cli.open_stream("GET", "/compressible", {},
  21679. {{"Accept-Encoding", "gzip"}});
  21680. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21681. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21682. }
  21683. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21684. Client cli("127.0.0.1", port_);
  21685. auto handle =
  21686. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21687. {{"Accept-Encoding", "gzip"}});
  21688. ASSERT_TRUE(handle.is_valid());
  21689. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21690. EXPECT_EQ("123456789", read_all(handle));
  21691. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21692. }
  21693. #endif
  21694. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21695. TEST_F(OpenStreamTest, Brotli) {
  21696. Client cli("127.0.0.1", port_);
  21697. auto handle =
  21698. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21699. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21700. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21701. }
  21702. #endif
  21703. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21704. TEST_F(OpenStreamTest, Zstd) {
  21705. Client cli("127.0.0.1", port_);
  21706. auto handle = cli.open_stream("GET", "/compressible", {},
  21707. {{"Accept-Encoding", "zstd"}});
  21708. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21709. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21710. }
  21711. #endif
  21712. #ifdef CPPHTTPLIB_SSL_ENABLED
  21713. class SSLOpenStreamTest : public ::testing::Test {
  21714. protected:
  21715. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21716. void SetUp() override {
  21717. svr_.Get("/hello", [](const Request &, Response &res) {
  21718. res.set_content("Hello SSL World!", "text/plain");
  21719. });
  21720. svr_.Get("/chunked", [](const Request &, Response &res) {
  21721. res.set_chunked_content_provider("text/plain",
  21722. [](size_t offset, DataSink &sink) {
  21723. if (offset < 15) {
  21724. sink.write("chunk", 5);
  21725. return true;
  21726. }
  21727. sink.done();
  21728. return true;
  21729. });
  21730. });
  21731. svr_.Post("/echo", [](const Request &req, Response &res) {
  21732. res.set_content(req.body, req.get_header_value("Content-Type"));
  21733. });
  21734. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21735. std::string body = req.body;
  21736. res.set_chunked_content_provider(
  21737. "text/plain", [body](size_t offset, DataSink &sink) {
  21738. if (offset < body.size()) {
  21739. sink.write(body.data() + offset, body.size() - offset);
  21740. }
  21741. sink.done();
  21742. return true;
  21743. });
  21744. });
  21745. port_ = svr_.bind_to_any_port("127.0.0.1");
  21746. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21747. svr_.wait_until_ready();
  21748. }
  21749. void TearDown() override {
  21750. svr_.stop();
  21751. if (thread_.joinable()) thread_.join();
  21752. }
  21753. SSLServer svr_;
  21754. std::thread thread_;
  21755. int port_ = 0;
  21756. };
  21757. TEST_F(SSLOpenStreamTest, Basic) {
  21758. SSLClient cli("127.0.0.1", port_);
  21759. cli.enable_server_certificate_verification(false);
  21760. auto handle = cli.open_stream("GET", "/hello");
  21761. ASSERT_TRUE(handle.is_valid());
  21762. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21763. }
  21764. TEST_F(SSLOpenStreamTest, Chunked) {
  21765. SSLClient cli("127.0.0.1", port_);
  21766. cli.enable_server_certificate_verification(false);
  21767. auto handle = cli.open_stream("GET", "/chunked");
  21768. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21769. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21770. "Transfer-Encoding") == "chunked");
  21771. auto body = read_all(handle);
  21772. EXPECT_EQ("chunkchunkchunk", body);
  21773. }
  21774. TEST_F(SSLOpenStreamTest, Post) {
  21775. SSLClient cli("127.0.0.1", port_);
  21776. cli.enable_server_certificate_verification(false);
  21777. auto handle =
  21778. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21779. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21780. EXPECT_EQ(200, handle.response->status);
  21781. auto body = read_all(handle);
  21782. EXPECT_EQ("Hello SSL POST", body);
  21783. }
  21784. TEST_F(SSLOpenStreamTest, PostChunked) {
  21785. SSLClient cli("127.0.0.1", port_);
  21786. cli.enable_server_certificate_verification(false);
  21787. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21788. "Chunked SSL Data", "text/plain");
  21789. ASSERT_TRUE(handle.is_valid());
  21790. EXPECT_EQ(200, handle.response->status);
  21791. auto body = read_all(handle);
  21792. EXPECT_EQ("Chunked SSL Data", body);
  21793. }
  21794. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21795. // Content-Length is terminated by the server closing the connection. When the
  21796. // SSL peer sends a close_notify after the body, the client must treat it as a
  21797. // clean EOF and return a successful response rather than an error.
  21798. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21800. ASSERT_TRUE(svr.is_valid());
  21801. svr.set_keep_alive_max_count(1);
  21802. const std::string expected_body = "Hello from connection-close response!";
  21803. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21804. res.set_content_provider("text/plain",
  21805. [&](size_t offset, DataSink &sink) -> bool {
  21806. if (offset < expected_body.size()) {
  21807. sink.write(expected_body.data() + offset,
  21808. expected_body.size() - offset);
  21809. }
  21810. sink.done();
  21811. return true;
  21812. });
  21813. });
  21814. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21815. auto se = detail::scope_exit([&] {
  21816. svr.stop();
  21817. listen_thread.join();
  21818. ASSERT_FALSE(svr.is_running());
  21819. });
  21820. svr.wait_until_ready();
  21821. SSLClient cli(HOST, PORT);
  21822. cli.enable_server_certificate_verification(false);
  21823. auto res = cli.Get("/no-content-length");
  21824. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21825. EXPECT_EQ(StatusCode::OK_200, res->status);
  21826. EXPECT_EQ(expected_body, res->body);
  21827. }
  21828. // Without Content-Length, the full buffer size reaches tls::read().
  21829. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21830. if (sizeof(size_t) <= sizeof(int)) {
  21831. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21832. }
  21833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21834. ASSERT_TRUE(svr.is_valid());
  21835. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21836. res.set_content_provider("text/plain",
  21837. [&](size_t offset, DataSink &sink) -> bool {
  21838. if (offset == 0) { sink.write("Hello", 5); }
  21839. sink.done();
  21840. return true;
  21841. });
  21842. });
  21843. auto port = svr.bind_to_any_port(HOST);
  21844. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21845. auto se = detail::scope_exit([&] {
  21846. svr.stop();
  21847. listen_thread.join();
  21848. });
  21849. svr.wait_until_ready();
  21850. SSLClient cli(HOST, port);
  21851. cli.enable_server_certificate_verification(false);
  21852. auto handle = cli.open_stream("GET", "/no-content-length");
  21853. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21854. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21855. std::unique_ptr<char[]> buf(new char[len]);
  21856. std::string body;
  21857. ssize_t n;
  21858. while ((n = handle.read(buf.get(), len)) > 0) {
  21859. body.append(buf.get(), static_cast<size_t>(n));
  21860. }
  21861. EXPECT_EQ(0, n);
  21862. EXPECT_EQ("Hello", body);
  21863. }
  21864. #endif // CPPHTTPLIB_SSL_ENABLED
  21865. //==============================================================================
  21866. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21867. // results for various scenarios.
  21868. //==============================================================================
  21869. TEST(ParityTest, GetVsOpenStream) {
  21870. Server svr;
  21871. const std::string path = "/parity";
  21872. const std::string content = "Parity test content: hello world";
  21873. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21874. res.set_content(content, "text/plain");
  21875. });
  21876. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21877. auto se = detail::scope_exit([&] {
  21878. svr.stop();
  21879. t.join();
  21880. ASSERT_FALSE(svr.is_running());
  21881. });
  21882. svr.wait_until_ready();
  21883. Client cli(HOST, PORT);
  21884. // Non-stream path
  21885. auto r1 = cli.Get(path);
  21886. ASSERT_TRUE(r1);
  21887. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21888. // Stream path
  21889. auto h = cli.open_stream("GET", path);
  21890. ASSERT_TRUE(h.is_valid());
  21891. EXPECT_EQ(r1->body, read_all(h));
  21892. }
  21893. // Helper to compress data with provided compressor type T
  21894. template <typename Compressor>
  21895. static std::string compress_payload_for_parity(const std::string &in) {
  21896. std::string out;
  21897. Compressor compressor;
  21898. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21899. [&](const char *data, size_t n) {
  21900. out.append(data, n);
  21901. return true;
  21902. });
  21903. EXPECT_TRUE(ok);
  21904. return out;
  21905. }
  21906. // Helper function for compression parity tests
  21907. template <typename Compressor>
  21908. static void test_compression_parity(const std::string &original,
  21909. const std::string &path,
  21910. const std::string &encoding) {
  21911. const std::string compressed =
  21912. compress_payload_for_parity<Compressor>(original);
  21913. Server svr;
  21914. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21915. res.set_content(compressed, "application/octet-stream");
  21916. res.set_header("Content-Encoding", encoding);
  21917. });
  21918. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21919. auto se = detail::scope_exit([&] {
  21920. svr.stop();
  21921. t.join();
  21922. ASSERT_FALSE(svr.is_running());
  21923. });
  21924. svr.wait_until_ready();
  21925. Client cli(HOST, PORT);
  21926. // Non-streaming
  21927. {
  21928. auto res = cli.Get(path);
  21929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21930. EXPECT_EQ(StatusCode::OK_200, res->status);
  21931. EXPECT_EQ(original, res->body);
  21932. }
  21933. // Streaming
  21934. {
  21935. auto h = cli.open_stream("GET", path);
  21936. ASSERT_TRUE(h.is_valid());
  21937. EXPECT_EQ(original, read_all(h));
  21938. }
  21939. }
  21940. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21941. TEST(ParityTest, Gzip) {
  21942. test_compression_parity<detail::gzip_compressor>(
  21943. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21944. }
  21945. #endif
  21946. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21947. TEST(ParityTest, Brotli) {
  21948. test_compression_parity<detail::brotli_compressor>(
  21949. "Hello, brotli parity test payload", "/parity-br", "br");
  21950. }
  21951. #endif
  21952. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21953. TEST(ParityTest, Zstd) {
  21954. test_compression_parity<detail::zstd_compressor>(
  21955. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21956. }
  21957. #endif
  21958. //==============================================================================
  21959. // New Stream API Tests
  21960. //==============================================================================
  21961. inline std::string read_body(httplib::stream::Result &result) {
  21962. std::string body;
  21963. while (result.next()) {
  21964. body.append(result.data(), result.size());
  21965. }
  21966. return body;
  21967. }
  21968. TEST(ClientConnectionTest, Basic) {
  21969. httplib::ClientConnection conn;
  21970. EXPECT_FALSE(conn.is_open());
  21971. conn.sock = 1;
  21972. EXPECT_TRUE(conn.is_open());
  21973. httplib::ClientConnection conn2(std::move(conn));
  21974. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21975. conn2.sock = INVALID_SOCKET;
  21976. }
  21977. // Unified test server for all stream::* tests
  21978. class StreamApiTest : public ::testing::Test {
  21979. protected:
  21980. void SetUp() override {
  21981. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21982. res.set_content("Hello World!", "text/plain");
  21983. });
  21984. svr_.Get("/echo-params",
  21985. [](const httplib::Request &req, httplib::Response &res) {
  21986. std::string r;
  21987. for (const auto &p : req.params) {
  21988. if (!r.empty()) r += "&";
  21989. r += p.first + "=" + p.second;
  21990. }
  21991. res.set_content(r, "text/plain");
  21992. });
  21993. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21994. res.set_content(req.body, req.get_header_value("Content-Type"));
  21995. });
  21996. svr_.Post("/echo-headers",
  21997. [](const httplib::Request &req, httplib::Response &res) {
  21998. std::string r;
  21999. for (const auto &h : req.headers)
  22000. r += h.first + ": " + h.second + "\n";
  22001. res.set_content(r, "text/plain");
  22002. });
  22003. svr_.Post("/echo-params",
  22004. [](const httplib::Request &req, httplib::Response &res) {
  22005. std::string r = "params:";
  22006. for (const auto &p : req.params)
  22007. r += p.first + "=" + p.second + ";";
  22008. res.set_content(r + " body:" + req.body, "text/plain");
  22009. });
  22010. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22011. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22012. });
  22013. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22014. res.set_content("PUT:" + req.body, "text/plain");
  22015. });
  22016. svr_.Patch("/echo",
  22017. [](const httplib::Request &req, httplib::Response &res) {
  22018. res.set_content("PATCH:" + req.body, "text/plain");
  22019. });
  22020. svr_.Delete(
  22021. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22022. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22023. "text/plain");
  22024. });
  22025. svr_.Get("/head-test",
  22026. [](const httplib::Request &, httplib::Response &res) {
  22027. res.set_content("body for HEAD", "text/plain");
  22028. });
  22029. svr_.Options("/options",
  22030. [](const httplib::Request &, httplib::Response &res) {
  22031. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22032. });
  22033. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22034. svr_.wait_until_ready();
  22035. }
  22036. void TearDown() override {
  22037. svr_.stop();
  22038. if (thread_.joinable()) thread_.join();
  22039. }
  22040. httplib::Server svr_;
  22041. std::thread thread_;
  22042. };
  22043. // stream::Get tests
  22044. TEST_F(StreamApiTest, GetBasic) {
  22045. httplib::Client cli(HOST, PORT);
  22046. auto result = httplib::stream::Get(cli, "/hello");
  22047. ASSERT_TRUE(result.is_valid());
  22048. EXPECT_EQ(200, result.status());
  22049. EXPECT_EQ("Hello World!", read_body(result));
  22050. }
  22051. TEST_F(StreamApiTest, GetWithParams) {
  22052. httplib::Client cli(HOST, PORT);
  22053. httplib::Params params{{"foo", "bar"}};
  22054. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22055. ASSERT_TRUE(result.is_valid());
  22056. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22057. }
  22058. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22059. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22060. httplib::Client cli(HOST, PORT);
  22061. cli.set_payload_max_length(0);
  22062. auto result = httplib::stream::Get(cli, "/hello");
  22063. ASSERT_TRUE(result.is_valid());
  22064. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22065. EXPECT_EQ("Hello World!", read_body(result));
  22066. }
  22067. #endif
  22068. TEST_F(StreamApiTest, GetConnectionError) {
  22069. httplib::Client cli(HOST, 9999);
  22070. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22071. }
  22072. TEST_F(StreamApiTest, Get404) {
  22073. httplib::Client cli(HOST, PORT);
  22074. auto result = httplib::stream::Get(cli, "/nonexistent");
  22075. EXPECT_TRUE(result.is_valid());
  22076. EXPECT_EQ(404, result.status());
  22077. }
  22078. // stream::Post tests
  22079. TEST_F(StreamApiTest, PostBasic) {
  22080. httplib::Client cli(HOST, PORT);
  22081. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22082. "application/json");
  22083. ASSERT_TRUE(result.is_valid());
  22084. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22085. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22086. }
  22087. TEST_F(StreamApiTest, PostWithHeaders) {
  22088. httplib::Client cli(HOST, PORT);
  22089. httplib::Headers headers{{"X-Custom", "value"}};
  22090. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22091. "text/plain");
  22092. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22093. }
  22094. TEST_F(StreamApiTest, PostWithParams) {
  22095. httplib::Client cli(HOST, PORT);
  22096. httplib::Params params{{"k", "v"}};
  22097. auto result =
  22098. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22099. auto body = read_body(result);
  22100. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22101. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22102. }
  22103. TEST_F(StreamApiTest, PostLarge) {
  22104. httplib::Client cli(HOST, PORT);
  22105. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22106. size_t total = 0;
  22107. while (result.next()) {
  22108. total += result.size();
  22109. }
  22110. EXPECT_EQ(100u * 1024u, total);
  22111. }
  22112. // stream::Put/Patch tests
  22113. TEST_F(StreamApiTest, PutAndPatch) {
  22114. httplib::Client cli(HOST, PORT);
  22115. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22116. EXPECT_EQ("PUT:test", read_body(put));
  22117. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22118. EXPECT_EQ("PATCH:test", read_body(patch));
  22119. }
  22120. // stream::Delete tests
  22121. TEST_F(StreamApiTest, Delete) {
  22122. httplib::Client cli(HOST, PORT);
  22123. auto del1 = httplib::stream::Delete(cli, "/resource");
  22124. EXPECT_EQ("Deleted", read_body(del1));
  22125. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22126. EXPECT_EQ("Deleted:data", read_body(del2));
  22127. }
  22128. // stream::Head/Options tests
  22129. TEST_F(StreamApiTest, HeadAndOptions) {
  22130. httplib::Client cli(HOST, PORT);
  22131. auto head = httplib::stream::Head(cli, "/head-test");
  22132. EXPECT_TRUE(head.is_valid());
  22133. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22134. auto opts = httplib::stream::Options(cli, "/options");
  22135. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22136. }
  22137. // SSL stream::* tests
  22138. #ifdef CPPHTTPLIB_SSL_ENABLED
  22139. class SSLStreamApiTest : public ::testing::Test {
  22140. protected:
  22141. void SetUp() override {
  22142. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22143. res.set_content("Hello SSL!", "text/plain");
  22144. });
  22145. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22146. res.set_content(req.body, "text/plain");
  22147. });
  22148. port_ = svr_.bind_to_any_port("127.0.0.1");
  22149. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22150. svr_.wait_until_ready();
  22151. }
  22152. void TearDown() override {
  22153. svr_.stop();
  22154. if (thread_.joinable()) thread_.join();
  22155. }
  22156. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22157. std::thread thread_;
  22158. int port_ = 0;
  22159. };
  22160. TEST_F(SSLStreamApiTest, GetAndPost) {
  22161. httplib::SSLClient cli("127.0.0.1", port_);
  22162. cli.enable_server_certificate_verification(false);
  22163. auto get = httplib::stream::Get(cli, "/hello");
  22164. EXPECT_EQ("Hello SSL!", read_body(get));
  22165. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22166. EXPECT_EQ("test", read_body(post));
  22167. }
  22168. #endif
  22169. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22170. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22171. // BodyReader
  22172. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22173. // Test that read timeout during streaming is detected
  22174. // Use a large content-length response where server delays mid-stream
  22175. Server svr;
  22176. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22177. // Send a large response with delay in the middle
  22178. res.set_content_provider(
  22179. 1000, // content_length
  22180. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22181. if (offset < 100) {
  22182. // Send first 100 bytes immediately
  22183. std::string data(100, 'A');
  22184. sink.write(data.c_str(), data.size());
  22185. return true;
  22186. }
  22187. // Then delay longer than client timeout
  22188. std::this_thread::sleep_for(std::chrono::seconds(3));
  22189. std::string data(900, 'B');
  22190. sink.write(data.c_str(), data.size());
  22191. return true;
  22192. });
  22193. });
  22194. auto port = 8091;
  22195. std::thread t([&]() { svr.listen("localhost", port); });
  22196. svr.wait_until_ready();
  22197. Client cli("localhost", port);
  22198. cli.set_read_timeout(1, 0); // 1 second timeout
  22199. auto handle = cli.open_stream("GET", "/slow-stream");
  22200. ASSERT_TRUE(handle.is_valid());
  22201. char buf[256];
  22202. ssize_t total = 0;
  22203. ssize_t n;
  22204. bool got_error = false;
  22205. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22206. total += n;
  22207. }
  22208. if (n < 0) {
  22209. got_error = true;
  22210. // Should be timeout or read error
  22211. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22212. handle.get_read_error() == Error::Read)
  22213. << "Actual error: " << to_string(handle.get_read_error());
  22214. }
  22215. // Either we got an error, or we got less data than expected
  22216. EXPECT_TRUE(got_error || total < 1000)
  22217. << "Expected timeout but got all " << total << " bytes";
  22218. svr.stop();
  22219. t.join();
  22220. }
  22221. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22222. // Test connection closed detection via BodyReader
  22223. Server svr;
  22224. std::atomic<bool> close_now{false};
  22225. svr.Get("/will-close", [&](const Request &, Response &res) {
  22226. res.set_content_provider(
  22227. 10000, // Large content_length that we won't fully send
  22228. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22229. if (offset < 100) {
  22230. std::string data(100, 'X');
  22231. sink.write(data.c_str(), data.size());
  22232. return true;
  22233. }
  22234. // Wait for signal then abort
  22235. while (!close_now) {
  22236. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22237. }
  22238. return false; // Abort - server will close connection
  22239. });
  22240. });
  22241. auto port = 8092;
  22242. std::thread t([&]() { svr.listen("localhost", port); });
  22243. svr.wait_until_ready();
  22244. Client cli("localhost", port);
  22245. auto handle = cli.open_stream("GET", "/will-close");
  22246. ASSERT_TRUE(handle.is_valid());
  22247. char buf[256];
  22248. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22249. EXPECT_GT(n, 0) << "First read should succeed";
  22250. // Signal server to close
  22251. close_now = true;
  22252. // Keep reading until error or EOF
  22253. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22254. // Keep reading
  22255. }
  22256. // Should get an error since content_length wasn't satisfied
  22257. if (n < 0) {
  22258. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22259. handle.get_read_error() == Error::Read)
  22260. << "Actual error: " << to_string(handle.get_read_error());
  22261. }
  22262. svr.stop();
  22263. t.join();
  22264. }
  22265. #ifdef CPPHTTPLIB_SSL_ENABLED
  22266. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22267. // Test that read timeout during SSL streaming is detected
  22268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22269. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22270. res.set_content_provider(
  22271. 1000, "text/plain",
  22272. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22273. if (offset < 100) {
  22274. std::string data(100, 'A');
  22275. sink.write(data.c_str(), data.size());
  22276. return true;
  22277. }
  22278. std::this_thread::sleep_for(std::chrono::seconds(3));
  22279. std::string data(900, 'B');
  22280. sink.write(data.c_str(), data.size());
  22281. return true;
  22282. });
  22283. });
  22284. auto port = 8093;
  22285. std::thread t([&]() { svr.listen("localhost", port); });
  22286. svr.wait_until_ready();
  22287. SSLClient cli("localhost", port);
  22288. cli.enable_server_certificate_verification(false);
  22289. cli.set_read_timeout(1, 0); // 1 second timeout
  22290. auto handle = cli.open_stream("GET", "/slow-stream");
  22291. ASSERT_TRUE(handle.is_valid());
  22292. char buf[256];
  22293. ssize_t total = 0;
  22294. ssize_t n;
  22295. bool got_error = false;
  22296. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22297. total += n;
  22298. }
  22299. if (n < 0) {
  22300. got_error = true;
  22301. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22302. handle.get_read_error() == Error::Read)
  22303. << "Actual error: " << to_string(handle.get_read_error());
  22304. }
  22305. EXPECT_TRUE(got_error || total < 1000)
  22306. << "Expected timeout but got all " << total << " bytes";
  22307. svr.stop();
  22308. t.join();
  22309. }
  22310. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22311. // Test SSL connection closed detection
  22312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22313. std::atomic<bool> close_now{false};
  22314. svr.Get("/will-close", [&](const Request &, Response &res) {
  22315. res.set_content_provider(
  22316. 10000, "text/plain",
  22317. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22318. if (offset < 100) {
  22319. std::string data(100, 'X');
  22320. sink.write(data.c_str(), data.size());
  22321. return true;
  22322. }
  22323. while (!close_now) {
  22324. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22325. }
  22326. return false;
  22327. });
  22328. });
  22329. auto port = 8094;
  22330. std::thread t([&]() { svr.listen("localhost", port); });
  22331. svr.wait_until_ready();
  22332. SSLClient cli("localhost", port);
  22333. cli.enable_server_certificate_verification(false);
  22334. auto handle = cli.open_stream("GET", "/will-close");
  22335. ASSERT_TRUE(handle.is_valid());
  22336. char buf[256];
  22337. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22338. EXPECT_GT(n, 0);
  22339. // Signal server to close
  22340. close_now = true;
  22341. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22342. // Keep reading
  22343. }
  22344. if (n < 0) {
  22345. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22346. handle.get_read_error() == Error::Read)
  22347. << "Actual error: " << to_string(handle.get_read_error());
  22348. }
  22349. svr.stop();
  22350. t.join();
  22351. }
  22352. #endif
  22353. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22354. using namespace httplib;
  22355. // Create a test file
  22356. const char *fname = "etag_testfile.txt";
  22357. const char *content = "etag-content";
  22358. {
  22359. std::ofstream ofs(fname);
  22360. ofs << content;
  22361. ASSERT_TRUE(ofs.good());
  22362. }
  22363. Server svr;
  22364. svr.set_mount_point("/static", ".");
  22365. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22366. svr.wait_until_ready();
  22367. Client cli(HOST, PORT);
  22368. // First request: should get 200 with ETag header
  22369. auto res1 = cli.Get("/static/etag_testfile.txt");
  22370. ASSERT_TRUE(res1);
  22371. ASSERT_EQ(200, res1->status);
  22372. ASSERT_TRUE(res1->has_header("ETag"));
  22373. std::string etag = res1->get_header_value("ETag");
  22374. EXPECT_FALSE(etag.empty());
  22375. // Verify ETag format: W/"hex-hex"
  22376. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22377. EXPECT_EQ('W', etag[0]);
  22378. EXPECT_EQ('/', etag[1]);
  22379. EXPECT_EQ('"', etag[2]);
  22380. EXPECT_EQ('"', etag.back());
  22381. // Exact match: expect 304 Not Modified
  22382. Headers h2 = {{"If-None-Match", etag}};
  22383. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22384. ASSERT_TRUE(res2);
  22385. EXPECT_EQ(304, res2->status);
  22386. // Wildcard match: expect 304 Not Modified
  22387. Headers h3 = {{"If-None-Match", "*"}};
  22388. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22389. ASSERT_TRUE(res3);
  22390. EXPECT_EQ(304, res3->status);
  22391. // Non-matching ETag: expect 200
  22392. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22393. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22394. ASSERT_TRUE(res4);
  22395. EXPECT_EQ(200, res4->status);
  22396. // Multiple ETags with one matching: expect 304
  22397. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22398. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22399. ASSERT_TRUE(res5);
  22400. EXPECT_EQ(304, res5->status);
  22401. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22402. // that equivalent to the single comma-separated list above, so the match on
  22403. // the second line must still be found.
  22404. Headers h6;
  22405. h6.emplace("If-None-Match", "W/\"other\"");
  22406. h6.emplace("If-None-Match", etag);
  22407. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22408. ASSERT_TRUE(res6);
  22409. EXPECT_EQ(304, res6->status);
  22410. svr.stop();
  22411. t.join();
  22412. std::remove(fname);
  22413. }
  22414. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22415. using namespace httplib;
  22416. Server svr;
  22417. svr.set_mount_point("/static", ".");
  22418. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22419. svr.wait_until_ready();
  22420. Client cli(HOST, PORT);
  22421. // Send If-None-Match: * to a non-existent file
  22422. Headers h = {{"If-None-Match", "*"}};
  22423. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22425. EXPECT_EQ(404, res->status);
  22426. svr.stop();
  22427. t.join();
  22428. }
  22429. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22430. using namespace httplib;
  22431. // Create a test file
  22432. const char *fname = "etag_boundary_testfile.txt";
  22433. const char *content = "boundary-test";
  22434. {
  22435. std::ofstream ofs(fname);
  22436. ofs << content;
  22437. ASSERT_TRUE(ofs.good());
  22438. }
  22439. Server svr;
  22440. svr.set_mount_point("/static", ".");
  22441. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22442. svr.wait_until_ready();
  22443. Client cli(HOST, PORT);
  22444. // Get the actual ETag
  22445. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22446. ASSERT_TRUE(res1);
  22447. ASSERT_EQ(200, res1->status);
  22448. ASSERT_TRUE(res1->has_header("ETag"));
  22449. std::string etag = res1->get_header_value("ETag");
  22450. // Test 1: Very long ETag value (longer than actual ETag)
  22451. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22452. Headers h1 = {{"If-None-Match", "W/"
  22453. "\"very-long-etag-value-that-is-much-longer-"
  22454. "than-the-actual-etag-value\""}};
  22455. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22456. ASSERT_TRUE(res2);
  22457. EXPECT_EQ(200, res2->status); // Should not match
  22458. // Test 2: Long string followed by wildcard
  22459. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22460. // string)
  22461. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22462. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22463. ASSERT_TRUE(res3);
  22464. EXPECT_EQ(304, res3->status); // Should match on "*"
  22465. // Test 3: Wildcard followed by long string
  22466. // Should match on "*" immediately and return 304
  22467. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22468. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22469. ASSERT_TRUE(res4);
  22470. EXPECT_EQ(304, res4->status); // Should match on "*"
  22471. // Test 4: Multiple long non-matching values
  22472. // Should NOT match and return 200 (test that all comparisons are safe)
  22473. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22474. "W/\"second-long-non-matching-value\", "
  22475. "W/\"third-long-non-matching-value\""}};
  22476. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22477. ASSERT_TRUE(res5);
  22478. EXPECT_EQ(200, res5->status); // Should not match
  22479. // Test 5: Single character that is not "*" (edge case)
  22480. Headers h5 = {{"If-None-Match", "X"}};
  22481. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22482. ASSERT_TRUE(res6);
  22483. EXPECT_EQ(200, res6->status); // Should not match
  22484. svr.stop();
  22485. t.join();
  22486. std::remove(fname);
  22487. }
  22488. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22489. using namespace httplib;
  22490. // Create a test file
  22491. const char *fname = "ims_testfile.txt";
  22492. const char *content = "if-modified-since-test";
  22493. {
  22494. std::ofstream ofs(fname);
  22495. ofs << content;
  22496. ASSERT_TRUE(ofs.good());
  22497. }
  22498. Server svr;
  22499. svr.set_mount_point("/static", ".");
  22500. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22501. svr.wait_until_ready();
  22502. Client cli(HOST, PORT);
  22503. // First request: should get 200 with Last-Modified header
  22504. auto res1 = cli.Get("/static/ims_testfile.txt");
  22505. ASSERT_TRUE(res1);
  22506. ASSERT_EQ(200, res1->status);
  22507. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22508. std::string last_modified = res1->get_header_value("Last-Modified");
  22509. EXPECT_FALSE(last_modified.empty());
  22510. // If-Modified-Since with same time: expect 304
  22511. Headers h2 = {{"If-Modified-Since", last_modified}};
  22512. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22513. ASSERT_TRUE(res2);
  22514. EXPECT_EQ(304, res2->status);
  22515. // If-Modified-Since with future time: expect 304
  22516. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22517. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22518. ASSERT_TRUE(res3);
  22519. EXPECT_EQ(304, res3->status);
  22520. // If-Modified-Since with past time: expect 200
  22521. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22522. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22523. ASSERT_TRUE(res4);
  22524. EXPECT_EQ(200, res4->status);
  22525. // If-None-Match takes precedence over If-Modified-Since
  22526. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22527. ASSERT_TRUE(res1->has_header("ETag"));
  22528. std::string etag = res1->get_header_value("ETag");
  22529. Headers h5 = {{"If-None-Match", etag},
  22530. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22531. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22532. ASSERT_TRUE(res5);
  22533. EXPECT_EQ(304, res5->status);
  22534. svr.stop();
  22535. t.join();
  22536. std::remove(fname);
  22537. }
  22538. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22539. using namespace httplib;
  22540. Server svr;
  22541. // Endpoint that returns compressible content
  22542. svr.Get("/compressible", [](const Request &, Response &res) {
  22543. // Return a large enough body to trigger compression
  22544. std::string body(1000, 'a');
  22545. res.set_content(body, "text/plain");
  22546. });
  22547. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22548. svr.wait_until_ready();
  22549. Client cli(HOST, PORT);
  22550. // Request with gzip support: should get Vary header when compressed
  22551. cli.set_compress(true);
  22552. auto res1 = cli.Get("/compressible");
  22553. ASSERT_TRUE(res1);
  22554. EXPECT_EQ(200, res1->status);
  22555. // If Content-Encoding is set, Vary should also be set
  22556. if (res1->has_header("Content-Encoding")) {
  22557. EXPECT_TRUE(res1->has_header("Vary"));
  22558. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22559. }
  22560. // Request without Accept-Encoding header: should not have compression
  22561. Headers h_no_compress;
  22562. auto res2 = cli.Get("/compressible", h_no_compress);
  22563. ASSERT_TRUE(res2);
  22564. EXPECT_EQ(200, res2->status);
  22565. // Verify Vary header is present when compression is applied
  22566. // (the exact behavior depends on server configuration)
  22567. svr.stop();
  22568. t.join();
  22569. }
  22570. TEST(ETagTest, IfRangeWithETag) {
  22571. using namespace httplib;
  22572. // Create a test file with known content
  22573. const char *fname = "if_range_testfile.txt";
  22574. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22575. {
  22576. std::ofstream ofs(fname);
  22577. ofs << content;
  22578. ASSERT_TRUE(ofs.good());
  22579. }
  22580. Server svr;
  22581. svr.set_mount_point("/static", ".");
  22582. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22583. svr.wait_until_ready();
  22584. Client cli(HOST, PORT);
  22585. // First request: get ETag
  22586. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22587. ASSERT_TRUE(res1);
  22588. ASSERT_EQ(200, res1->status);
  22589. ASSERT_TRUE(res1->has_header("ETag"));
  22590. std::string etag = res1->get_header_value("ETag");
  22591. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22592. // Since our server generates weak ETags (W/"..."), If-Range with our
  22593. // ETag should NOT result in partial content - it should return full content.
  22594. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22595. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22596. ASSERT_TRUE(res2);
  22597. // Weak ETag in If-Range -> full content (200), not partial (206)
  22598. EXPECT_EQ(200, res2->status);
  22599. EXPECT_EQ(content, res2->body);
  22600. EXPECT_FALSE(res2->has_header("Content-Range"));
  22601. // Range request with non-matching If-Range (ETag): should get 200 (full
  22602. // content)
  22603. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22604. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22605. ASSERT_TRUE(res3);
  22606. EXPECT_EQ(200, res3->status);
  22607. EXPECT_EQ(content, res3->body);
  22608. EXPECT_FALSE(res3->has_header("Content-Range"));
  22609. // Range request with strong ETag (hypothetical - our server doesn't generate
  22610. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22611. // should return full content)
  22612. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22613. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22614. ASSERT_TRUE(res4);
  22615. EXPECT_EQ(200, res4->status);
  22616. EXPECT_EQ(content, res4->body);
  22617. EXPECT_FALSE(res4->has_header("Content-Range"));
  22618. svr.stop();
  22619. t.join();
  22620. std::remove(fname);
  22621. }
  22622. TEST(ETagTest, IfRangeWithDate) {
  22623. using namespace httplib;
  22624. // Create a test file
  22625. const char *fname = "if_range_date_testfile.txt";
  22626. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22627. {
  22628. std::ofstream ofs(fname);
  22629. ofs << content;
  22630. ASSERT_TRUE(ofs.good());
  22631. }
  22632. Server svr;
  22633. svr.set_mount_point("/static", ".");
  22634. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22635. svr.wait_until_ready();
  22636. Client cli(HOST, PORT);
  22637. // First request: get Last-Modified
  22638. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22639. ASSERT_TRUE(res1);
  22640. ASSERT_EQ(200, res1->status);
  22641. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22642. std::string last_modified = res1->get_header_value("Last-Modified");
  22643. // Range request with matching If-Range (date): should get 206
  22644. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22645. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22646. ASSERT_TRUE(res2);
  22647. EXPECT_EQ(206, res2->status);
  22648. EXPECT_EQ("FGHIJ", res2->body);
  22649. // Range request with old If-Range date: should get 200 (full content)
  22650. Headers h3 = {{"Range", "bytes=5-9"},
  22651. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22652. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22653. ASSERT_TRUE(res3);
  22654. EXPECT_EQ(200, res3->status);
  22655. EXPECT_EQ(content, res3->body);
  22656. // Range request with future If-Range date: should get 206
  22657. Headers h4 = {{"Range", "bytes=0-4"},
  22658. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22659. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22660. ASSERT_TRUE(res4);
  22661. EXPECT_EQ(206, res4->status);
  22662. EXPECT_EQ("ABCDE", res4->body);
  22663. svr.stop();
  22664. t.join();
  22665. std::remove(fname);
  22666. }
  22667. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22668. using namespace httplib;
  22669. const char *fname = "etag_malformed.txt";
  22670. const char *content = "malformed-etag";
  22671. {
  22672. std::ofstream ofs(fname);
  22673. ofs << content;
  22674. ASSERT_TRUE(ofs.good());
  22675. }
  22676. Server svr;
  22677. svr.set_mount_point("/static", ".");
  22678. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22679. svr.wait_until_ready();
  22680. Client cli(HOST, PORT);
  22681. // baseline: should get 200 and an ETag
  22682. auto res1 = cli.Get("/static/etag_malformed.txt");
  22683. ASSERT_TRUE(res1);
  22684. ASSERT_EQ(200, res1->status);
  22685. ASSERT_TRUE(res1->has_header("ETag"));
  22686. // Malformed ETag value (missing quotes) should be treated as non-matching
  22687. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22688. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22689. ASSERT_TRUE(res_bad);
  22690. EXPECT_EQ(200, res_bad->status);
  22691. // Whitespace-only header value should be considered invalid / non-matching
  22692. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22693. "Host: localhost\r\n"
  22694. "If-None-Match: \r\n"
  22695. "Connection: close\r\n"
  22696. "\r\n";
  22697. std::string out;
  22698. ASSERT_TRUE(send_request(5, raw_req, &out));
  22699. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22700. svr.stop();
  22701. t.join();
  22702. std::remove(fname);
  22703. }
  22704. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22705. using namespace httplib;
  22706. const char *fname = "ims_invalid_format.txt";
  22707. const char *content = "ims-bad-format";
  22708. {
  22709. std::ofstream ofs(fname);
  22710. ofs << content;
  22711. ASSERT_TRUE(ofs.good());
  22712. }
  22713. Server svr;
  22714. svr.set_mount_point("/static", ".");
  22715. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22716. svr.wait_until_ready();
  22717. Client cli(HOST, PORT);
  22718. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22719. ASSERT_TRUE(res1);
  22720. ASSERT_EQ(200, res1->status);
  22721. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22722. // If-Modified-Since with invalid format should not result in 304
  22723. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22724. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22725. ASSERT_TRUE(res_bad);
  22726. EXPECT_EQ(200, res_bad->status);
  22727. // If-Range with invalid date format should be treated as mismatch -> full
  22728. // content (200)
  22729. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22730. {"If-Range", "invalid-date"}};
  22731. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22732. ASSERT_TRUE(res_ifrange);
  22733. EXPECT_EQ(200, res_ifrange->status);
  22734. svr.stop();
  22735. t.join();
  22736. std::remove(fname);
  22737. }
  22738. TEST(ETagTest, IfRangeWithMalformedETag) {
  22739. using namespace httplib;
  22740. const char *fname = "ifrange_malformed.txt";
  22741. const std::string content = "0123456789";
  22742. {
  22743. std::ofstream ofs(fname);
  22744. ofs << content;
  22745. ASSERT_TRUE(ofs.good());
  22746. }
  22747. Server svr;
  22748. svr.set_mount_point("/static", ".");
  22749. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22750. svr.wait_until_ready();
  22751. Client cli(HOST, PORT);
  22752. // First request: get ETag
  22753. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22754. ASSERT_TRUE(res1);
  22755. ASSERT_EQ(200, res1->status);
  22756. ASSERT_TRUE(res1->has_header("ETag"));
  22757. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22758. // full content (200)
  22759. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22760. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22761. ASSERT_TRUE(res2);
  22762. EXPECT_EQ(200, res2->status);
  22763. EXPECT_EQ(content, res2->body);
  22764. svr.stop();
  22765. t.join();
  22766. std::remove(fname);
  22767. }
  22768. TEST(ETagTest, ExtremeLargeDateValues) {
  22769. using namespace httplib;
  22770. const char *fname = "ims_extreme_date.txt";
  22771. const char *content = "ims-extreme-date";
  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. auto res1 = cli.Get(std::string("/static/") + fname);
  22783. ASSERT_TRUE(res1);
  22784. ASSERT_EQ(200, res1->status);
  22785. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22786. // Extremely large year that may overflow date parsing routines.
  22787. Headers h_large_date = {
  22788. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22789. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22790. ASSERT_TRUE(res_bad);
  22791. // Expect server to treat this as invalid/mismatch and return full content
  22792. EXPECT_EQ(200, res_bad->status);
  22793. // If-Range with extremely large date should be treated as mismatch -> full
  22794. // content (200)
  22795. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22796. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22797. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22798. ASSERT_TRUE(res_ifrange);
  22799. EXPECT_EQ(200, res_ifrange->status);
  22800. svr.stop();
  22801. t.join();
  22802. std::remove(fname);
  22803. }
  22804. TEST(ETagTest, NegativeFileModificationTime) {
  22805. using namespace httplib;
  22806. const char *fname = "ims_negative_mtime.txt";
  22807. const std::string content = "negative-mtime";
  22808. {
  22809. std::ofstream ofs(fname);
  22810. ofs << content;
  22811. ASSERT_TRUE(ofs.good());
  22812. }
  22813. // Try to set file mtime to a negative value. This may fail on some
  22814. // platforms/filesystems; if it fails, the test will still verify server
  22815. // behaves safely by performing a regular conditional request.
  22816. #if defined(__APPLE__) || defined(__linux__)
  22817. bool set_negative = false;
  22818. do {
  22819. struct timeval times[2];
  22820. // access time: now
  22821. times[0].tv_sec = time(nullptr);
  22822. times[0].tv_usec = 0;
  22823. // modification time: negative (e.g., -1)
  22824. times[1].tv_sec = -1;
  22825. times[1].tv_usec = 0;
  22826. if (utimes(fname, times) == 0) { set_negative = true; }
  22827. } while (0);
  22828. #else
  22829. bool set_negative = false;
  22830. #endif
  22831. Server svr;
  22832. svr.set_mount_point("/static", ".");
  22833. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22834. svr.wait_until_ready();
  22835. Client cli(HOST, PORT);
  22836. auto res1 = cli.Get(std::string("/static/") + fname);
  22837. ASSERT_TRUE(res1);
  22838. ASSERT_EQ(200, res1->status);
  22839. bool has_last_modified = res1->has_header("Last-Modified");
  22840. std::string last_modified;
  22841. if (has_last_modified) {
  22842. last_modified = res1->get_header_value("Last-Modified");
  22843. }
  22844. if (set_negative) {
  22845. // If we successfully set a negative mtime, ensure server returns a
  22846. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22847. // with an old date and ensure server handles it without crash.
  22848. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22849. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22850. ASSERT_TRUE(res2);
  22851. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22852. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22853. } else {
  22854. // Could not set negative mtime on this platform; fall back to verifying
  22855. // that normal invalid/malformed dates are treated safely (non-304).
  22856. Headers h_bad_date = {
  22857. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22858. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22859. ASSERT_TRUE(res_bad);
  22860. EXPECT_EQ(200, res_bad->status);
  22861. }
  22862. svr.stop();
  22863. t.join();
  22864. std::remove(fname);
  22865. }
  22866. //==============================================================================
  22867. // Integration Tests with Server
  22868. //==============================================================================
  22869. class SSEIntegrationTest : public ::testing::Test {
  22870. protected:
  22871. void SetUp() override {
  22872. stop_server_.store(false);
  22873. events_.clear();
  22874. server_ = httplib::detail::make_unique<Server>();
  22875. setup_server();
  22876. start_server();
  22877. }
  22878. void TearDown() override {
  22879. stop_server_.store(true);
  22880. event_cv_.notify_all();
  22881. server_->stop();
  22882. if (server_thread_.joinable()) { server_thread_.join(); }
  22883. }
  22884. void setup_server() {
  22885. // Simple SSE endpoint
  22886. server_->Get("/events", [this](const Request &req, Response &res) {
  22887. auto last_id = req.get_header_value("Last-Event-ID");
  22888. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22889. res.set_chunked_content_provider(
  22890. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22891. std::unique_lock<std::mutex> lock(event_mutex_);
  22892. if (event_cv_.wait_for(
  22893. lock, std::chrono::milliseconds(200), [this] {
  22894. return !events_.empty() || stop_server_.load();
  22895. })) {
  22896. if (stop_server_.load()) { return false; }
  22897. if (!events_.empty()) {
  22898. std::string event = events_.front();
  22899. events_.erase(events_.begin());
  22900. sink.write(event.data(), event.size());
  22901. return true;
  22902. }
  22903. }
  22904. return !stop_server_.load();
  22905. });
  22906. });
  22907. // Endpoint that returns error
  22908. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22909. res.status = 500;
  22910. res.set_content("Internal Server Error", "text/plain");
  22911. });
  22912. // Endpoint for custom event types
  22913. server_->Get("/custom-events", [](const Request &, Response &res) {
  22914. res.set_chunked_content_provider(
  22915. "text/event-stream", [](size_t offset, DataSink &sink) {
  22916. if (offset == 0) {
  22917. std::string event = "event: update\ndata: updated\n\n"
  22918. "event: delete\ndata: deleted\n\n";
  22919. sink.write(event.data(), event.size());
  22920. }
  22921. return false; // End stream after sending
  22922. });
  22923. });
  22924. }
  22925. void start_server() {
  22926. port_ = server_->bind_to_any_port(HOST);
  22927. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22928. // Wait for server to start
  22929. while (!server_->is_running()) {
  22930. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22931. }
  22932. }
  22933. int get_port() const { return port_; }
  22934. void send_event(const std::string &event) {
  22935. std::lock_guard<std::mutex> lock(event_mutex_);
  22936. events_.push_back(event);
  22937. event_cv_.notify_all();
  22938. }
  22939. std::unique_ptr<Server> server_;
  22940. std::thread server_thread_;
  22941. std::mutex event_mutex_;
  22942. std::condition_variable event_cv_;
  22943. std::vector<std::string> events_;
  22944. std::atomic<bool> stop_server_{false};
  22945. std::string last_received_event_id_;
  22946. int port_ = 0;
  22947. };
  22948. //==============================================================================
  22949. // SSE Parser Tests
  22950. //==============================================================================
  22951. struct SSEParseResult {
  22952. std::vector<sse::SSEMessage> events;
  22953. std::vector<std::string> ids;
  22954. std::vector<int> retries;
  22955. bool ok = true;
  22956. std::string trace; // Every handler call in order
  22957. };
  22958. static SSEParseResult
  22959. sse_parse(const std::vector<std::string> &chunks,
  22960. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  22961. SSEParseResult r;
  22962. detail::SSEParser parser(
  22963. [&](const sse::SSEMessage &msg) {
  22964. r.events.push_back(msg);
  22965. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  22966. },
  22967. [&](const std::string &id) {
  22968. r.ids.push_back(id);
  22969. r.trace += "id[" + id + "]";
  22970. },
  22971. [&](int retry_ms) {
  22972. r.retries.push_back(retry_ms);
  22973. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  22974. },
  22975. max_event_length);
  22976. for (const auto &chunk : chunks) {
  22977. if (!parser.parse(chunk.data(), chunk.size())) {
  22978. r.ok = false;
  22979. break;
  22980. }
  22981. }
  22982. return r;
  22983. }
  22984. static SSEParseResult sse_parse(const std::string &stream) {
  22985. return sse_parse(std::vector<std::string>{stream});
  22986. }
  22987. TEST(SSEParserTest, SingleLineData) {
  22988. auto r = sse_parse("data: hello\n\n");
  22989. ASSERT_EQ(r.events.size(), 1u);
  22990. EXPECT_EQ(r.events[0].data, "hello");
  22991. EXPECT_EQ(r.events[0].event, "message");
  22992. }
  22993. TEST(SSEParserTest, MultiLineData) {
  22994. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  22995. ASSERT_EQ(r.events.size(), 1u);
  22996. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  22997. }
  22998. TEST(SSEParserTest, CustomEventType) {
  22999. auto r = sse_parse("event: update\ndata: payload\n\n");
  23000. ASSERT_EQ(r.events.size(), 1u);
  23001. EXPECT_EQ(r.events[0].event, "update");
  23002. EXPECT_EQ(r.events[0].data, "payload");
  23003. }
  23004. TEST(SSEParserTest, EventIdHandling) {
  23005. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23006. ASSERT_EQ(r.events.size(), 1u);
  23007. EXPECT_EQ(r.events[0].id, "12345");
  23008. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23009. }
  23010. TEST(SSEParserTest, EmptyEventId) {
  23011. auto r = sse_parse("id:\ndata: test\n\n");
  23012. ASSERT_EQ(r.events.size(), 1u);
  23013. EXPECT_EQ(r.events[0].id, "");
  23014. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23015. }
  23016. TEST(SSEParserTest, CommentsIgnored) {
  23017. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23018. ASSERT_EQ(r.events.size(), 1u);
  23019. EXPECT_EQ(r.events[0].data, "hello");
  23020. EXPECT_EQ(r.events[0].event, "message");
  23021. }
  23022. TEST(SSEParserTest, ColonInValue) {
  23023. auto r = sse_parse("data: hello:world:test\n\n");
  23024. ASSERT_EQ(r.events.size(), 1u);
  23025. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23026. }
  23027. TEST(SSEParserTest, FieldNameOnly) {
  23028. // A line without a colon is a field name with an empty value
  23029. auto r = sse_parse("data\n\n");
  23030. ASSERT_EQ(r.events.size(), 1u);
  23031. EXPECT_EQ(r.events[0].data, "");
  23032. }
  23033. TEST(SSEParserTest, TrailingCarriageReturn) {
  23034. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23035. ASSERT_EQ(r.events.size(), 1u);
  23036. EXPECT_EQ(r.events[0].event, "update");
  23037. EXPECT_EQ(r.events[0].data, "hello");
  23038. }
  23039. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23040. auto r = sse_parse("data\r\n\r\n");
  23041. ASSERT_EQ(r.events.size(), 1u);
  23042. EXPECT_EQ(r.events[0].data, "");
  23043. }
  23044. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23045. auto r = sse_parse("event: update\rdata: hello\r\r");
  23046. ASSERT_EQ(r.events.size(), 1u);
  23047. EXPECT_EQ(r.events[0].event, "update");
  23048. EXPECT_EQ(r.events[0].data, "hello");
  23049. }
  23050. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23051. // Chunk boundaries fall inside every \r\n and right before the first one
  23052. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23053. "\ndata: hello\r", "\n\r", "\n"});
  23054. ASSERT_EQ(r.events.size(), 1u);
  23055. EXPECT_EQ(r.events[0].event, "update");
  23056. EXPECT_EQ(r.events[0].data, "hello");
  23057. }
  23058. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23059. // Only a BOM at the start of the stream is ignored
  23060. auto r = sse_parse("\xEF\xBB\xBF"
  23061. "data: first\n\n"
  23062. "\xEF\xBB\xBF"
  23063. "data: second\n\n");
  23064. ASSERT_EQ(r.events.size(), 1u);
  23065. EXPECT_EQ(r.events[0].data, "first");
  23066. }
  23067. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23068. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23069. ASSERT_EQ(r.events.size(), 1u);
  23070. EXPECT_EQ(r.events[0].data, "hello");
  23071. EXPECT_EQ(r.events[0].event, "message");
  23072. }
  23073. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23074. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23075. ASSERT_EQ(r.events.size(), 2u);
  23076. EXPECT_EQ(r.events[0].data, "hello");
  23077. EXPECT_EQ(r.events[1].data, "hello");
  23078. }
  23079. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23080. // An event without data is not dispatched, and its type must not leak
  23081. // into the next event
  23082. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23083. ASSERT_EQ(r.events.size(), 1u);
  23084. EXPECT_EQ(r.events[0].event, "message");
  23085. EXPECT_EQ(r.events[0].data, "hello");
  23086. }
  23087. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23088. // Also when the empty field replaces an earlier type
  23089. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23090. ASSERT_EQ(r.events.size(), 2u);
  23091. EXPECT_EQ(r.events[0].event, "message");
  23092. EXPECT_EQ(r.events[1].event, "message");
  23093. }
  23094. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23095. auto r = sse_parse("id: 42\n\n");
  23096. EXPECT_TRUE(r.events.empty());
  23097. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23098. }
  23099. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23100. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23101. ASSERT_EQ(r.events.size(), 2u);
  23102. EXPECT_EQ(r.events[0].id, "1");
  23103. EXPECT_EQ(r.events[1].id, "");
  23104. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23105. }
  23106. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23107. // Ids that cannot be carried in a Last-Event-ID header
  23108. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23109. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23110. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23111. }
  23112. TEST(SSEParserTest, RetryDigitsOnly) {
  23113. auto r = sse_parse("retry: 1000\n");
  23114. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23115. // A value that is not all ASCII digits, or does not fit, is ignored
  23116. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23117. EXPECT_TRUE(r.retries.empty());
  23118. }
  23119. TEST(SSEParserTest, CompleteEventParsing) {
  23120. auto r = sse_parse("event: notification\nid: evt-42\n"
  23121. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23122. ASSERT_EQ(r.events.size(), 1u);
  23123. EXPECT_EQ(r.events[0].event, "notification");
  23124. EXPECT_EQ(r.events[0].id, "evt-42");
  23125. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23126. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23127. }
  23128. TEST(SSEParserTest, IncompleteEventNotReported) {
  23129. // An event still waiting for its blank line when the stream ends is
  23130. // discarded per the SSE spec
  23131. auto r = sse_parse("id: 1\ndata: x\n");
  23132. EXPECT_TRUE(r.events.empty());
  23133. EXPECT_TRUE(r.ids.empty());
  23134. }
  23135. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23136. const std::vector<std::string> streams = {
  23137. "\xEF\xBB\xBF"
  23138. "data: bom\r\n\r\n",
  23139. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23140. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23141. };
  23142. for (const auto &stream : streams) {
  23143. auto expected = sse_parse(stream).trace;
  23144. ASSERT_FALSE(expected.empty());
  23145. for (size_t i = 0; i <= stream.size(); i++) {
  23146. auto r = sse_parse(
  23147. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23148. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23149. }
  23150. std::vector<std::string> bytes;
  23151. for (auto c : stream) {
  23152. bytes.emplace_back(1, c);
  23153. }
  23154. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23155. }
  23156. }
  23157. TEST(SSEParserTest, MaxEventLength) {
  23158. // A line still waiting for its end
  23159. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23160. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23161. // Data accumulated over the lines of one event
  23162. EXPECT_TRUE(
  23163. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23164. EXPECT_FALSE(
  23165. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23166. // 0 means no limit
  23167. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23168. // Events completed in the same chunk are still reported
  23169. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23170. EXPECT_FALSE(r.ok);
  23171. ASSERT_EQ(r.events.size(), 1u);
  23172. EXPECT_EQ(r.events[0].data, "a");
  23173. }
  23174. TEST(SSEMessageTest, Clear) {
  23175. sse::SSEMessage msg;
  23176. msg.event = "custom";
  23177. msg.data = "some data";
  23178. msg.id = "123";
  23179. msg.clear();
  23180. EXPECT_EQ(msg.event, "message");
  23181. EXPECT_EQ(msg.data, "");
  23182. EXPECT_EQ(msg.id, "");
  23183. }
  23184. //==============================================================================
  23185. // SSE Integration Tests
  23186. //==============================================================================
  23187. // Test: Successful connection and on_open callback
  23188. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23189. // Add a simple endpoint that sends one event and closes
  23190. server_->Get("/simple-event", [](const Request &, Response &res) {
  23191. res.set_chunked_content_provider(
  23192. "text/event-stream", [](size_t offset, DataSink &sink) {
  23193. if (offset == 0) {
  23194. std::string event = "data: hello\n\n";
  23195. sink.write(event.data(), event.size());
  23196. }
  23197. return false; // Close stream after sending
  23198. });
  23199. });
  23200. Client client("localhost", get_port());
  23201. sse::SSEClient sse(client, "/simple-event");
  23202. std::atomic<bool> open_called{false};
  23203. std::atomic<bool> message_received{false};
  23204. sse.on_open([&open_called]() { open_called.store(true); });
  23205. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23206. if (msg.data == "hello") { message_received.store(true); }
  23207. });
  23208. sse.set_reconnect_interval(100);
  23209. sse.set_max_reconnect_attempts(1);
  23210. // Start async
  23211. sse.start_async();
  23212. // Wait for message to be processed
  23213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23214. sse.stop();
  23215. EXPECT_TRUE(open_called.load());
  23216. EXPECT_TRUE(message_received.load());
  23217. }
  23218. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23219. // A data line that never ends.
  23220. server_->Get("/endless-line", [](const Request &, Response &res) {
  23221. res.set_chunked_content_provider(
  23222. "text/event-stream", [](size_t offset, DataSink &sink) {
  23223. if (offset == 0) { sink.write("data: ", 6); }
  23224. std::string chunk(64 * 1024, 'A');
  23225. return sink.write(chunk.data(), chunk.size());
  23226. });
  23227. });
  23228. Client client("localhost", get_port());
  23229. sse::SSEClient sse(client, "/endless-line");
  23230. std::atomic<bool> too_long{false};
  23231. sse.on_error([&](Error err) {
  23232. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23233. });
  23234. sse.set_max_reconnect_attempts(1);
  23235. sse.start_async();
  23236. for (int i = 0; i < 500 && !too_long; i++) {
  23237. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23238. }
  23239. sse.stop();
  23240. EXPECT_TRUE(too_long);
  23241. }
  23242. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23243. // Far more in all than the client's payload limit below.
  23244. server_->Get("/many-events", [](const Request &, Response &res) {
  23245. res.set_chunked_content_provider(
  23246. "text/event-stream", [](size_t offset, DataSink &sink) {
  23247. if (offset == 0) {
  23248. std::string events;
  23249. for (int i = 0; i < 1000; i++) {
  23250. events += "data: message\n\n";
  23251. }
  23252. sink.write(events.data(), events.size());
  23253. }
  23254. return false;
  23255. });
  23256. });
  23257. Client client("localhost", get_port());
  23258. client.set_payload_max_length(1024);
  23259. sse::SSEClient sse(client, "/many-events");
  23260. std::atomic<int> messages{0};
  23261. std::atomic<bool> too_large{false};
  23262. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23263. sse.on_error([&](Error err) {
  23264. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23265. });
  23266. sse.set_max_reconnect_attempts(1);
  23267. sse.start_async();
  23268. for (int i = 0; i < 500 && messages < 1000; i++) {
  23269. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23270. }
  23271. sse.stop();
  23272. EXPECT_GE(messages.load(), 1000);
  23273. EXPECT_FALSE(too_large);
  23274. }
  23275. // Test: on_message callback
  23276. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23277. // Endpoint that sends multiple events then closes
  23278. server_->Get("/multi-event", [](const Request &, Response &res) {
  23279. res.set_chunked_content_provider(
  23280. "text/event-stream", [](size_t offset, DataSink &sink) {
  23281. if (offset == 0) {
  23282. std::string events = "data: message1\n\ndata: message2\n\n";
  23283. sink.write(events.data(), events.size());
  23284. }
  23285. return false;
  23286. });
  23287. });
  23288. Client client("localhost", get_port());
  23289. sse::SSEClient sse(client, "/multi-event");
  23290. std::vector<std::string> received_messages;
  23291. std::mutex messages_mutex;
  23292. sse.on_message([&](const sse::SSEMessage &msg) {
  23293. std::lock_guard<std::mutex> lock(messages_mutex);
  23294. received_messages.push_back(msg.data);
  23295. });
  23296. sse.set_reconnect_interval(100);
  23297. sse.set_max_reconnect_attempts(1);
  23298. sse.start_async();
  23299. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23300. sse.stop();
  23301. std::lock_guard<std::mutex> lock(messages_mutex);
  23302. EXPECT_GE(received_messages.size(), 2u);
  23303. if (received_messages.size() >= 2) {
  23304. EXPECT_EQ(received_messages[0], "message1");
  23305. EXPECT_EQ(received_messages[1], "message2");
  23306. }
  23307. }
  23308. // Test: on_event for specific types
  23309. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23310. Client client("localhost", get_port());
  23311. sse::SSEClient sse(client, "/custom-events");
  23312. std::atomic<bool> update_received{false};
  23313. std::atomic<bool> delete_received{false};
  23314. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23315. if (msg.data == "updated") { update_received.store(true); }
  23316. });
  23317. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23318. if (msg.data == "deleted") { delete_received.store(true); }
  23319. });
  23320. sse.set_max_reconnect_attempts(1);
  23321. sse.start_async();
  23322. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23323. sse.stop();
  23324. EXPECT_TRUE(update_received.load());
  23325. EXPECT_TRUE(delete_received.load());
  23326. }
  23327. // Test: on_error callback on connection failure
  23328. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23329. // Connect to a non-existent port
  23330. Client client("localhost", 59999);
  23331. sse::SSEClient sse(client, "/events");
  23332. std::atomic<bool> error_called{false};
  23333. Error received_error = Error::Success;
  23334. sse.on_error([&](Error err) {
  23335. error_called.store(true);
  23336. received_error = err;
  23337. });
  23338. sse.set_reconnect_interval(50);
  23339. sse.set_max_reconnect_attempts(1);
  23340. sse.start_async();
  23341. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23342. sse.stop();
  23343. EXPECT_TRUE(error_called.load());
  23344. EXPECT_NE(received_error, Error::Success);
  23345. }
  23346. // Test: Last-Event-ID header sent on reconnect
  23347. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23348. // Endpoint that sends event with ID
  23349. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23350. res.set_chunked_content_provider(
  23351. "text/event-stream", [](size_t offset, DataSink &sink) {
  23352. if (offset == 0) {
  23353. std::string event = "id: evt-123\ndata: test\n\n";
  23354. sink.write(event.data(), event.size());
  23355. }
  23356. return false;
  23357. });
  23358. });
  23359. Client client("localhost", get_port());
  23360. sse::SSEClient sse(client, "/event-with-id");
  23361. std::atomic<bool> id_received{false};
  23362. sse.on_message([&](const sse::SSEMessage &msg) {
  23363. if (!msg.id.empty()) { id_received.store(true); }
  23364. });
  23365. sse.set_reconnect_interval(100);
  23366. sse.set_max_reconnect_attempts(1);
  23367. sse.start_async();
  23368. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23369. sse.stop();
  23370. EXPECT_TRUE(id_received.load());
  23371. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23372. }
  23373. // Test: last_event_id() read from another thread while start_async() runs
  23374. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23375. // Ids of every length up to 200, so the stored id keeps changing size
  23376. server_->Get("/many-ids", [](const Request &, Response &res) {
  23377. res.set_chunked_content_provider(
  23378. "text/event-stream", [](size_t offset, DataSink &sink) {
  23379. if (offset == 0) {
  23380. std::string events;
  23381. for (size_t i = 0; i < 2000; i++) {
  23382. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23383. events += "data: x\n\n";
  23384. }
  23385. events += "id: end\ndata: x\n\n";
  23386. sink.write(events.data(), events.size());
  23387. }
  23388. return false;
  23389. });
  23390. });
  23391. Client client("localhost", get_port());
  23392. sse::SSEClient sse(client, "/many-ids");
  23393. // Wait out the rest of the test rather than replay the stream
  23394. sse.set_reconnect_interval(10000);
  23395. sse.set_max_reconnect_attempts(1);
  23396. sse.start_async();
  23397. auto well_formed = true;
  23398. std::string id;
  23399. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23400. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23401. id = sse.last_event_id();
  23402. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23403. well_formed = false;
  23404. }
  23405. }
  23406. sse.stop();
  23407. EXPECT_TRUE(well_formed);
  23408. EXPECT_EQ(sse.last_event_id(), "end");
  23409. }
  23410. // Test: Manual stop
  23411. TEST_F(SSEIntegrationTest, ManualStop) {
  23412. // Endpoint that sends one event and stays open briefly. The server outlives
  23413. // this test body, so the provider uses the fixture's flag, not a local.
  23414. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23415. res.set_chunked_content_provider(
  23416. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23417. if (offset == 0) {
  23418. std::string event = "data: connected\n\n";
  23419. sink.write(event.data(), event.size());
  23420. }
  23421. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23422. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23423. }
  23424. return false;
  23425. });
  23426. });
  23427. Client client("localhost", get_port());
  23428. sse::SSEClient sse(client, "/stay-open");
  23429. std::atomic<bool> connected{false};
  23430. sse.on_open([&connected]() { connected.store(true); });
  23431. sse.set_reconnect_interval(100);
  23432. sse.set_max_reconnect_attempts(1);
  23433. sse.start_async();
  23434. // Wait for connection to establish
  23435. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23436. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23437. }
  23438. EXPECT_TRUE(connected.load());
  23439. EXPECT_TRUE(sse.is_connected());
  23440. // Signal handler to stop
  23441. stop_server_.store(true);
  23442. // Stop SSE client
  23443. sse.stop();
  23444. EXPECT_FALSE(sse.is_connected());
  23445. }
  23446. // Sends one event, then nothing until stop is set
  23447. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23448. return [&stop](const Request &, Response &res) {
  23449. res.set_chunked_content_provider(
  23450. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23451. if (offset == 0) {
  23452. std::string event = "data: hello\n\n";
  23453. sink.write(event.data(), event.size());
  23454. }
  23455. while (!stop.load()) {
  23456. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23457. }
  23458. return false;
  23459. });
  23460. };
  23461. }
  23462. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23463. static void check_stop_interrupts_blocked_read(Client &client) {
  23464. client.set_read_timeout(30, 0);
  23465. for (auto by_destructor : {false, true}) {
  23466. std::atomic<bool> received{false};
  23467. std::chrono::steady_clock::time_point start;
  23468. {
  23469. sse::SSEClient sse(client, "/idle-stream");
  23470. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23471. sse.start_async();
  23472. for (int i = 0; i < 500 && !received.load(); ++i) {
  23473. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23474. }
  23475. ASSERT_TRUE(received.load());
  23476. // Let the client block in the next read
  23477. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23478. start = std::chrono::steady_clock::now();
  23479. if (!by_destructor) { sse.stop(); }
  23480. }
  23481. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23482. std::chrono::seconds(2));
  23483. }
  23484. }
  23485. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23486. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23487. Client client("localhost", get_port());
  23488. check_stop_interrupts_blocked_read(client);
  23489. }
  23490. #ifdef CPPHTTPLIB_SSL_ENABLED
  23491. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23493. std::atomic<bool> done{false};
  23494. svr.Get("/idle-stream", idle_event_stream(done));
  23495. auto port = svr.bind_to_any_port(HOST);
  23496. std::thread t([&] { svr.listen_after_bind(); });
  23497. auto se = detail::scope_exit([&] {
  23498. done.store(true);
  23499. svr.stop();
  23500. t.join();
  23501. });
  23502. svr.wait_until_ready();
  23503. Client client("https://localhost:" + std::to_string(port));
  23504. client.enable_server_certificate_verification(false);
  23505. check_stop_interrupts_blocked_read(client);
  23506. }
  23507. #endif
  23508. // Test: SSEClient with custom headers
  23509. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23510. // Setup a server endpoint that checks for custom header
  23511. std::atomic<bool> header_received{false};
  23512. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23513. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23514. header_received.store(true);
  23515. }
  23516. res.set_chunked_content_provider("text/event-stream",
  23517. [](size_t, DataSink &) { return false; });
  23518. });
  23519. Client client("localhost", get_port());
  23520. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23521. sse::SSEClient sse(client, "/header-check", headers);
  23522. sse.set_max_reconnect_attempts(1);
  23523. sse.start_async();
  23524. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23525. sse.stop();
  23526. EXPECT_TRUE(header_received.load());
  23527. }
  23528. // Test: Reconnect interval configuration
  23529. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23530. Client client("localhost", get_port());
  23531. sse::SSEClient sse(client, "/events");
  23532. auto &result = sse.set_reconnect_interval(500);
  23533. // Builder pattern should return reference to self
  23534. EXPECT_EQ(&result, &sse);
  23535. }
  23536. // Test: Max reconnect attempts
  23537. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23538. // Connect to non-existent port to force reconnects
  23539. Client client("localhost", 59998);
  23540. sse::SSEClient sse(client, "/events");
  23541. std::atomic<int> error_count{0};
  23542. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23543. sse.set_reconnect_interval(50);
  23544. sse.set_max_reconnect_attempts(2);
  23545. auto start = std::chrono::steady_clock::now();
  23546. sse.start(); // Blocking call
  23547. auto end = std::chrono::steady_clock::now();
  23548. // Should have stopped after 2 failed attempts
  23549. EXPECT_GE(error_count.load(), 2);
  23550. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23551. auto duration =
  23552. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23553. #ifdef _WIN32
  23554. // Windows is much slower for socket connection failures
  23555. EXPECT_LT(duration.count(), 7000);
  23556. #else
  23557. EXPECT_LT(duration.count(), 1000);
  23558. #endif
  23559. }
  23560. // Test: Multi-line data in integration
  23561. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23562. // Endpoint with multi-line data
  23563. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23564. res.set_chunked_content_provider(
  23565. "text/event-stream", [](size_t offset, DataSink &sink) {
  23566. if (offset == 0) {
  23567. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23568. sink.write(event.data(), event.size());
  23569. }
  23570. return false;
  23571. });
  23572. });
  23573. Client client("localhost", get_port());
  23574. sse::SSEClient sse(client, "/multiline-data");
  23575. std::string received_data;
  23576. std::mutex data_mutex;
  23577. sse.on_message([&](const sse::SSEMessage &msg) {
  23578. std::lock_guard<std::mutex> lock(data_mutex);
  23579. received_data = msg.data;
  23580. });
  23581. sse.set_reconnect_interval(100);
  23582. sse.set_max_reconnect_attempts(1);
  23583. sse.start_async();
  23584. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23585. sse.stop();
  23586. std::lock_guard<std::mutex> lock(data_mutex);
  23587. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23588. }
  23589. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23590. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23591. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23592. DataSink &sink) {
  23593. if (offset == 0) {
  23594. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23595. sink.write(events.data(), events.size());
  23596. }
  23597. return false;
  23598. });
  23599. });
  23600. Client client("localhost", get_port());
  23601. sse::SSEClient sse(client, "/empty-data-lines");
  23602. std::mutex mutex;
  23603. std::condition_variable cv;
  23604. std::vector<std::string> received;
  23605. sse.on_message([&](const sse::SSEMessage &msg) {
  23606. std::lock_guard<std::mutex> lock(mutex);
  23607. received.push_back(msg.data);
  23608. cv.notify_all();
  23609. });
  23610. sse.set_max_reconnect_attempts(1);
  23611. sse.start_async();
  23612. {
  23613. std::unique_lock<std::mutex> lock(mutex);
  23614. cv.wait_for(lock, std::chrono::seconds(2),
  23615. [&] { return received.size() >= 3; });
  23616. }
  23617. sse.stop();
  23618. ASSERT_GE(received.size(), 3u);
  23619. EXPECT_EQ(received[0], "");
  23620. EXPECT_EQ(received[1], "\nhello");
  23621. EXPECT_EQ(received[2], "");
  23622. }
  23623. // Test: Auto-reconnect after server disconnection
  23624. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23625. std::atomic<int> connection_count{0};
  23626. std::atomic<int> message_count{0};
  23627. // Endpoint that sends one event and closes, forcing reconnect
  23628. server_->Get("/reconnect-test",
  23629. [&connection_count](const Request &, Response &res) {
  23630. connection_count.fetch_add(1);
  23631. res.set_chunked_content_provider(
  23632. "text/event-stream", [](size_t offset, DataSink &sink) {
  23633. if (offset == 0) {
  23634. std::string event = "data: hello\n\n";
  23635. sink.write(event.data(), event.size());
  23636. }
  23637. return false; // Close connection after sending
  23638. });
  23639. });
  23640. Client client("localhost", get_port());
  23641. sse::SSEClient sse(client, "/reconnect-test");
  23642. sse.on_message([&message_count](const sse::SSEMessage &) {
  23643. message_count.fetch_add(1);
  23644. });
  23645. sse.set_reconnect_interval(100);
  23646. sse.set_max_reconnect_attempts(3);
  23647. sse.start_async();
  23648. // Wait long enough for multiple reconnects
  23649. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23650. sse.stop();
  23651. // Should have connected multiple times (initial + reconnects)
  23652. EXPECT_GE(connection_count.load(), 2);
  23653. // Should have received messages from multiple connections
  23654. EXPECT_GE(message_count.load(), 2);
  23655. }
  23656. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23657. std::atomic<int> connection_count{0};
  23658. // Neither Content-Length nor chunked: the close ends the stream
  23659. server_->Get("/close-delimited",
  23660. [&connection_count](const Request &, Response &res) {
  23661. connection_count.fetch_add(1);
  23662. res.set_content_provider(
  23663. "text/event-stream", [](size_t offset, DataSink &sink) {
  23664. if (offset == 0) {
  23665. std::string event = "data: hello\n\n";
  23666. sink.write(event.data(), event.size());
  23667. } else {
  23668. sink.done();
  23669. }
  23670. return true;
  23671. });
  23672. });
  23673. Client client("localhost", get_port());
  23674. sse::SSEClient sse(client, "/close-delimited");
  23675. std::atomic<int> error_count{0};
  23676. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23677. sse.set_reconnect_interval(100);
  23678. sse.start_async();
  23679. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23681. }
  23682. sse.stop();
  23683. // Reconnects as after any end of the stream, but reports no error
  23684. EXPECT_GE(connection_count.load(), 2);
  23685. EXPECT_EQ(0, error_count.load());
  23686. }
  23687. // Test: A retry field of all ASCII digits sets the reconnection time
  23688. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23689. std::mutex mutex;
  23690. std::condition_variable cv;
  23691. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23692. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23693. {
  23694. std::lock_guard<std::mutex> lock(mutex);
  23695. connected_at.push_back(std::chrono::steady_clock::now());
  23696. cv.notify_all();
  23697. }
  23698. res.set_chunked_content_provider(
  23699. "text/event-stream", [](size_t offset, DataSink &sink) {
  23700. if (offset == 0) {
  23701. std::string event = "retry: 0\ndata: hello\n\n";
  23702. sink.write(event.data(), event.size());
  23703. }
  23704. return false;
  23705. });
  23706. });
  23707. Client client("localhost", get_port());
  23708. sse::SSEClient sse(client, "/zero-retry");
  23709. sse.set_reconnect_interval(10000);
  23710. sse.start_async();
  23711. {
  23712. std::unique_lock<std::mutex> lock(mutex);
  23713. cv.wait_for(lock, std::chrono::seconds(5),
  23714. [&] { return connected_at.size() >= 2; });
  23715. }
  23716. sse.stop();
  23717. // The server-supplied interval is applied, but never below 100ms, so
  23718. // "retry: 0" does not cause a busy reconnect loop
  23719. std::lock_guard<std::mutex> lock(mutex);
  23720. ASSERT_GE(connected_at.size(), 2u);
  23721. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23722. connected_at[1] - connected_at[0])
  23723. .count();
  23724. EXPECT_GE(interval_ms, 100);
  23725. }
  23726. // Test: Last-Event-ID sent on reconnect
  23727. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23728. std::atomic<int> connection_count{0};
  23729. std::vector<std::string> received_last_event_ids;
  23730. std::mutex id_mutex;
  23731. // Endpoint that checks Last-Event-ID header and sends event with ID
  23732. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23733. int conn = connection_count.fetch_add(1);
  23734. // Capture the Last-Event-ID header from each connection
  23735. {
  23736. std::lock_guard<std::mutex> lock(id_mutex);
  23737. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23738. }
  23739. res.set_chunked_content_provider(
  23740. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23741. if (offset == 0) {
  23742. std::string event =
  23743. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23744. sink.write(event.data(), event.size());
  23745. }
  23746. return false;
  23747. });
  23748. });
  23749. Client client("localhost", get_port());
  23750. sse::SSEClient sse(client, "/reconnect-with-id");
  23751. sse.set_reconnect_interval(100);
  23752. sse.set_max_reconnect_attempts(3);
  23753. sse.start_async();
  23754. // Wait for at least 2 connections
  23755. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23756. sse.stop();
  23757. // Verify behavior
  23758. std::lock_guard<std::mutex> lock(id_mutex);
  23759. EXPECT_GE(received_last_event_ids.size(), 2u);
  23760. // First connection should have no Last-Event-ID
  23761. if (!received_last_event_ids.empty()) {
  23762. EXPECT_EQ(received_last_event_ids[0], "");
  23763. }
  23764. // Second connection should have Last-Event-ID from first connection
  23765. if (received_last_event_ids.size() >= 2) {
  23766. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23767. }
  23768. }
  23769. // Test: set_headers updates headers used on reconnect
  23770. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23771. std::vector<std::string> received_tokens;
  23772. std::mutex token_mutex;
  23773. // Endpoint that captures Authorization header
  23774. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23775. {
  23776. std::lock_guard<std::mutex> lock(token_mutex);
  23777. received_tokens.push_back(req.get_header_value("Authorization"));
  23778. }
  23779. res.set_chunked_content_provider(
  23780. "text/event-stream", [](size_t offset, DataSink &sink) {
  23781. if (offset == 0) {
  23782. std::string event = "data: hello\n\n";
  23783. sink.write(event.data(), event.size());
  23784. }
  23785. return false; // Close connection to trigger reconnect
  23786. });
  23787. });
  23788. Client client("localhost", get_port());
  23789. Headers headers = {{"Authorization", "Bearer old-token"}};
  23790. sse::SSEClient sse(client, "/auth-check", headers);
  23791. // Update headers on each successful connection
  23792. sse.on_open(
  23793. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23794. sse.set_reconnect_interval(100);
  23795. sse.set_max_reconnect_attempts(3);
  23796. sse.start_async();
  23797. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23798. sse.stop();
  23799. std::lock_guard<std::mutex> lock(token_mutex);
  23800. ASSERT_GE(received_tokens.size(), 2u);
  23801. // First connection uses original header
  23802. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23803. // Second connection uses updated header from set_headers
  23804. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23805. }
  23806. // Test: 401 allows reconnection (so on_error can refresh headers)
  23807. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23808. std::atomic<int> connection_count{0};
  23809. // Endpoint: returns 401 on first attempt, 200 on second
  23810. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23811. int conn = connection_count.fetch_add(1);
  23812. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23813. res.status = StatusCode::Unauthorized_401;
  23814. res.set_content("Unauthorized", "text/plain");
  23815. return;
  23816. }
  23817. res.set_chunked_content_provider(
  23818. "text/event-stream", [](size_t offset, DataSink &sink) {
  23819. if (offset == 0) {
  23820. std::string event = "data: authenticated\n\n";
  23821. sink.write(event.data(), event.size());
  23822. }
  23823. return false;
  23824. });
  23825. });
  23826. Client client("localhost", get_port());
  23827. Headers headers = {{"Authorization", "Bearer expired"}};
  23828. sse::SSEClient sse(client, "/auth-retry", headers);
  23829. std::atomic<bool> message_received{false};
  23830. // Refresh token on error
  23831. sse.on_error(
  23832. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23833. sse.on_message([&](const sse::SSEMessage &msg) {
  23834. if (msg.data == "authenticated") { message_received.store(true); }
  23835. });
  23836. sse.set_reconnect_interval(100);
  23837. sse.set_max_reconnect_attempts(3);
  23838. sse.start_async();
  23839. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23840. sse.stop();
  23841. // Should have reconnected after 401 and succeeded with new token
  23842. EXPECT_GE(connection_count.load(), 2);
  23843. EXPECT_TRUE(message_received.load());
  23844. }
  23845. TEST(Issue2318Test, EmptyHostString) {
  23846. {
  23847. httplib::Client cli_empty("", PORT);
  23848. auto res = cli_empty.Get("/");
  23849. ASSERT_FALSE(res);
  23850. EXPECT_EQ(httplib::Error::Connection, res.error());
  23851. }
  23852. {
  23853. httplib::Client cli(" ", PORT);
  23854. auto res = cli.Get("/");
  23855. ASSERT_FALSE(res);
  23856. EXPECT_EQ(httplib::Error::Connection, res.error());
  23857. }
  23858. }
  23859. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23860. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23861. Server svr;
  23862. // Set a small payload limit (1KB)
  23863. svr.set_payload_max_length(1024);
  23864. svr.Post("/test", [&](const Request &req, Response &res) {
  23865. res.set_content("Body size: " + std::to_string(req.body.size()),
  23866. "text/plain");
  23867. });
  23868. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23869. auto se = detail::scope_exit([&] {
  23870. svr.stop();
  23871. listen_thread.join();
  23872. });
  23873. svr.wait_until_ready();
  23874. // Create data that compresses well but exceeds limit when decompressed
  23875. // 8KB of repeated null bytes compresses to a very small size
  23876. std::string original_data(8 * 1024, '\0');
  23877. // Compress the data using gzip
  23878. std::string compressed_data;
  23879. detail::gzip_compressor compressor;
  23880. compressor.compress(original_data.data(), original_data.size(), true,
  23881. [&](const char *data, size_t size) {
  23882. compressed_data.append(data, size);
  23883. return true;
  23884. });
  23885. // Verify compression worked (compressed should be much smaller)
  23886. ASSERT_LT(compressed_data.size(), original_data.size());
  23887. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23888. // Send compressed data with Content-Encoding: gzip
  23889. Client cli(HOST, PORT);
  23890. Headers headers = {{"Content-Encoding", "gzip"}};
  23891. auto res =
  23892. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23893. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23895. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23896. }
  23897. #endif
  23898. // ============================================================================
  23899. // OpenSSL-Specific Tests
  23900. // ============================================================================
  23901. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23902. X509 *readCertificate(const std::string &strFileName) {
  23903. std::ifstream inStream(strFileName);
  23904. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23905. std::istreambuf_iterator<char>());
  23906. if (strCertPEM.empty()) return (nullptr);
  23907. BIO *pbCert = BIO_new(BIO_s_mem());
  23908. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23909. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23910. BIO_free(pbCert);
  23911. return (pCert);
  23912. }
  23913. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23914. std::ifstream inStream(strFileName);
  23915. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23916. std::istreambuf_iterator<char>());
  23917. if (strPrivateKeyPEM.empty()) return (nullptr);
  23918. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23919. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23920. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23921. BIO_free(pbPrivKey);
  23922. return (pPrivateKey);
  23923. }
  23924. TEST(BindServerTest, UpdateCerts) {
  23925. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23926. int port = svr.bind_to_any_port("0.0.0.0");
  23927. ASSERT_TRUE(svr.is_valid());
  23928. ASSERT_TRUE(port > 0);
  23929. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23930. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23931. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23932. ASSERT_TRUE(cert != nullptr);
  23933. ASSERT_TRUE(ca_cert != nullptr);
  23934. ASSERT_TRUE(key != nullptr);
  23935. X509_STORE *cert_store = X509_STORE_new();
  23936. X509_STORE_add_cert(cert_store, ca_cert);
  23937. // svr.update_certs(cert, key, cert_store); // deprecated
  23938. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23939. CLIENT_CA_CERT_FILE);
  23940. ASSERT_TRUE(svr.is_valid());
  23941. svr.stop();
  23942. X509_STORE_free(cert_store);
  23943. X509_free(cert);
  23944. X509_free(ca_cert);
  23945. EVP_PKEY_free(key);
  23946. }
  23947. // Test that update_certs() updates client CA list correctly
  23948. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23949. // Start with file-based constructor
  23950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23951. ASSERT_TRUE(svr.is_valid());
  23952. // Initially no client CA list should be set
  23953. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23954. ASSERT_TRUE(ssl_ctx != nullptr);
  23955. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23956. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23957. // Now update with client CA (PEM string)
  23958. std::string cert_pem, key_pem, ca_pem;
  23959. read_file(SERVER_CERT_FILE, cert_pem);
  23960. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23961. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23962. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23963. ASSERT_TRUE(svr.is_valid());
  23964. // Now client CA list should be set
  23965. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23966. ASSERT_TRUE(ca_list_after != nullptr);
  23967. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23968. }
  23969. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23970. // Test that the file-path SSLServer constructor properly sets the client CA
  23971. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23972. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23973. ASSERT_TRUE(svr.is_valid());
  23974. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23975. ASSERT_TRUE(ssl_ctx != nullptr);
  23976. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23977. ASSERT_TRUE(ca_list != nullptr);
  23978. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23979. }
  23980. #endif
  23981. // ============================================================================
  23982. // MbedTLS-Specific Tests
  23983. // ============================================================================
  23984. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23985. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23986. using namespace httplib::tls;
  23987. // Track if callback was invoked
  23988. bool callback_invoked = false;
  23989. // The callback receives void* ctx which is actually MbedTlsContext*
  23990. // We can access the mbedtls_ssl_config via the context
  23991. auto setup_callback = [&callback_invoked](void *ctx) {
  23992. callback_invoked = true;
  23993. // Cast to MbedTlsContext* to access the ssl config
  23994. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23995. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23996. // Use static variables to hold certificate data (simplified for test)
  23997. static mbedtls_x509_crt own_cert;
  23998. static mbedtls_pk_context own_key;
  23999. static mbedtls_x509_crt ca_chain;
  24000. static bool initialized = false;
  24001. if (!initialized) {
  24002. mbedtls_x509_crt_init(&own_cert);
  24003. mbedtls_pk_init(&own_key);
  24004. mbedtls_x509_crt_init(&ca_chain);
  24005. // Load server certificate
  24006. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24007. return false;
  24008. }
  24009. // Load server private key.
  24010. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24011. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24012. #if MBEDTLS_VERSION_MAJOR == 3
  24013. ,
  24014. mbedtls_ctr_drbg_random, nullptr
  24015. #endif
  24016. ) != 0) {
  24017. return false;
  24018. }
  24019. // Load CA chain for client verification
  24020. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24021. return false;
  24022. }
  24023. initialized = true;
  24024. }
  24025. // Configure the SSL config
  24026. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24027. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24028. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24029. // Set minimum TLS version using mbedTLS native API
  24030. #if MBEDTLS_VERSION_MAJOR >= 3
  24031. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24032. #else
  24033. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24034. MBEDTLS_SSL_MINOR_VERSION_3);
  24035. #endif
  24036. return true;
  24037. };
  24038. SSLServer svr(setup_callback);
  24039. ASSERT_TRUE(svr.is_valid());
  24040. ASSERT_TRUE(callback_invoked);
  24041. svr.Get("/test", [&](const Request &req, Response &res) {
  24042. res.set_content("test", "text/plain");
  24043. auto cert = req.peer_cert();
  24044. ASSERT_TRUE(static_cast<bool>(cert));
  24045. auto common_name = cert.subject_cn();
  24046. EXPECT_EQ("Common Name", common_name);
  24047. });
  24048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24049. auto se = detail::scope_exit([&] {
  24050. svr.stop();
  24051. t.join();
  24052. ASSERT_FALSE(svr.is_running());
  24053. });
  24054. svr.wait_until_ready();
  24055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24056. cli.enable_server_certificate_verification(false);
  24057. cli.set_connection_timeout(30);
  24058. auto res = cli.Get("/test");
  24059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24060. ASSERT_EQ(StatusCode::OK_200, res->status);
  24061. }
  24062. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24063. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24064. // keep-alive SSL session, which reads through that config in
  24065. // mbedtls_ssl_close_notify.
  24066. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24068. ASSERT_TRUE(svr.is_valid());
  24069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24070. res.set_content("test", "text/plain");
  24071. });
  24072. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24073. auto se = detail::scope_exit([&] {
  24074. svr.stop();
  24075. t.join();
  24076. ASSERT_FALSE(svr.is_running());
  24077. });
  24078. svr.wait_until_ready();
  24079. {
  24080. SSLClient cli(HOST, PORT);
  24081. cli.enable_server_certificate_verification(false);
  24082. cli.set_keep_alive(true);
  24083. auto res = cli.Get("/test");
  24084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24085. ASSERT_EQ(StatusCode::OK_200, res->status);
  24086. // cli is destructed here with the keep-alive SSL session still open.
  24087. }
  24088. }
  24089. #endif
  24090. // WebSocket Tests
  24091. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24092. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24093. // defining the meaning of these bits has been negotiated.
  24094. auto make_frame = [](uint8_t first_byte) {
  24095. std::string frame;
  24096. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24097. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24098. frame += "Hello";
  24099. return frame;
  24100. };
  24101. // RSV1 set (0x40)
  24102. {
  24103. detail::BufferStream strm;
  24104. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24105. ws::Opcode opcode;
  24106. std::string payload;
  24107. bool fin;
  24108. EXPECT_EQ(
  24109. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24110. ws::impl::FrameRead::Fail);
  24111. }
  24112. // RSV2 set (0x20)
  24113. {
  24114. detail::BufferStream strm;
  24115. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24116. ws::Opcode opcode;
  24117. std::string payload;
  24118. bool fin;
  24119. EXPECT_EQ(
  24120. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24121. ws::impl::FrameRead::Fail);
  24122. }
  24123. // RSV3 set (0x10)
  24124. {
  24125. detail::BufferStream strm;
  24126. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24127. ws::Opcode opcode;
  24128. std::string payload;
  24129. bool fin;
  24130. EXPECT_EQ(
  24131. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24132. ws::impl::FrameRead::Fail);
  24133. }
  24134. // No RSV bits set - should succeed
  24135. {
  24136. detail::BufferStream strm;
  24137. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24138. ws::Opcode opcode;
  24139. std::string payload;
  24140. bool fin;
  24141. EXPECT_EQ(
  24142. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24143. ws::impl::FrameRead::Ok);
  24144. EXPECT_EQ(ws::Opcode::Text, opcode);
  24145. EXPECT_EQ("Hello", payload);
  24146. EXPECT_TRUE(fin);
  24147. }
  24148. }
  24149. TEST(WebSocketTest, ControlFrameValidation) {
  24150. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24151. // payload length <= 125.
  24152. // Ping with FIN=0 - must be rejected
  24153. {
  24154. detail::BufferStream strm;
  24155. std::string frame;
  24156. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24157. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24158. strm.write(frame.data(), frame.size());
  24159. ws::Opcode opcode;
  24160. std::string payload;
  24161. bool fin;
  24162. EXPECT_EQ(
  24163. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24164. ws::impl::FrameRead::Fail);
  24165. }
  24166. // Close with FIN=0 - must be rejected
  24167. {
  24168. detail::BufferStream strm;
  24169. std::string frame;
  24170. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24171. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24172. strm.write(frame.data(), frame.size());
  24173. ws::Opcode opcode;
  24174. std::string payload;
  24175. bool fin;
  24176. EXPECT_EQ(
  24177. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24178. ws::impl::FrameRead::Fail);
  24179. }
  24180. // Ping with payload_len=126 (extended length) - must be rejected
  24181. {
  24182. detail::BufferStream strm;
  24183. std::string frame;
  24184. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24185. frame += static_cast<char>(126); // payload_len=126 (>125)
  24186. frame += static_cast<char>(0x00); // extended length high byte
  24187. frame += static_cast<char>(126); // extended length low byte
  24188. frame += std::string(126, 'x');
  24189. strm.write(frame.data(), frame.size());
  24190. ws::Opcode opcode;
  24191. std::string payload;
  24192. bool fin;
  24193. EXPECT_EQ(
  24194. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24195. ws::impl::FrameRead::Fail);
  24196. }
  24197. // Ping with FIN=1 and payload_len=125 - should succeed
  24198. {
  24199. detail::BufferStream strm;
  24200. std::string frame;
  24201. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24202. frame += static_cast<char>(125); // payload_len=125
  24203. frame += std::string(125, 'x');
  24204. strm.write(frame.data(), frame.size());
  24205. ws::Opcode opcode;
  24206. std::string payload;
  24207. bool fin;
  24208. EXPECT_EQ(
  24209. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24210. ws::impl::FrameRead::Ok);
  24211. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24212. EXPECT_EQ(125u, payload.size());
  24213. EXPECT_TRUE(fin);
  24214. }
  24215. }
  24216. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24217. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24218. // length MUST be 0.
  24219. // MSB set - must be rejected
  24220. {
  24221. detail::BufferStream strm;
  24222. std::string frame;
  24223. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24224. frame += static_cast<char>(127); // 64-bit extended length
  24225. frame += static_cast<char>(0x80); // MSB set (invalid)
  24226. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24227. strm.write(frame.data(), frame.size());
  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. // MSB clear - should pass length parsing (will be rejected by max_len,
  24236. // but that's a different check; use a small length to verify)
  24237. {
  24238. detail::BufferStream strm;
  24239. std::string frame;
  24240. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24241. frame += static_cast<char>(127); // 64-bit extended length
  24242. frame += std::string(7, '\0'); // high bytes = 0
  24243. frame += static_cast<char>(0x03); // length = 3
  24244. frame += "abc";
  24245. strm.write(frame.data(), frame.size());
  24246. ws::Opcode opcode;
  24247. std::string payload;
  24248. bool fin;
  24249. EXPECT_EQ(
  24250. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24251. ws::impl::FrameRead::Ok);
  24252. EXPECT_EQ(ws::Opcode::Text, opcode);
  24253. EXPECT_EQ("abc", payload);
  24254. }
  24255. }
  24256. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24257. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24258. // Valid UTF-8
  24259. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24260. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24261. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24262. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24263. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24264. // Invalid UTF-8
  24265. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24266. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24267. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24268. EXPECT_FALSE(
  24269. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24270. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24271. }
  24272. TEST(WebSocketTest, ConnectAndDisconnect) {
  24273. Server svr;
  24274. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24275. std::string msg;
  24276. while (ws.read(msg)) {}
  24277. });
  24278. auto port = svr.bind_to_any_port(HOST);
  24279. std::thread t([&]() { svr.listen_after_bind(); });
  24280. svr.wait_until_ready();
  24281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24282. auto res = client.connect();
  24283. ASSERT_TRUE(res);
  24284. EXPECT_EQ(Error::Success, res.error());
  24285. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24286. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24287. EXPECT_TRUE(client.is_open());
  24288. client.close();
  24289. EXPECT_FALSE(client.is_open());
  24290. svr.stop();
  24291. t.join();
  24292. }
  24293. TEST(WebSocketTest, ValidURL) {
  24294. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24295. EXPECT_TRUE(ws1.is_valid());
  24296. ws::WebSocketClient ws2("ws://example.com/path");
  24297. EXPECT_TRUE(ws2.is_valid());
  24298. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24299. EXPECT_TRUE(ws3.is_valid());
  24300. #ifdef CPPHTTPLIB_SSL_ENABLED
  24301. ws::WebSocketClient wss1("wss://example.com/path");
  24302. EXPECT_TRUE(wss1.is_valid());
  24303. ws::WebSocketClient wss2("wss://example.com:443/path");
  24304. EXPECT_TRUE(wss2.is_valid());
  24305. #endif
  24306. }
  24307. TEST(WebSocketTest, InvalidURL) {
  24308. // No scheme
  24309. ws::WebSocketClient ws1("localhost:8080/path");
  24310. EXPECT_FALSE(ws1.is_valid());
  24311. // No path
  24312. ws::WebSocketClient ws2("ws://localhost:8080");
  24313. EXPECT_FALSE(ws2.is_valid());
  24314. // Empty string
  24315. ws::WebSocketClient ws3("");
  24316. EXPECT_FALSE(ws3.is_valid());
  24317. // Missing host
  24318. ws::WebSocketClient ws4("ws://:8080/path");
  24319. EXPECT_FALSE(ws4.is_valid());
  24320. // Port number overflow — should not crash
  24321. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24322. EXPECT_FALSE(ws5.is_valid());
  24323. // Port out of range
  24324. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24325. EXPECT_FALSE(ws6.is_valid());
  24326. }
  24327. TEST(WebSocketTest, UnsupportedScheme) {
  24328. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24329. ws::WebSocketClient ws1("http://localhost:8080/path");
  24330. EXPECT_FALSE(ws1.is_valid());
  24331. ws::WebSocketClient ws2("https://localhost:8080/path");
  24332. EXPECT_FALSE(ws2.is_valid());
  24333. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24334. EXPECT_FALSE(ws3.is_valid());
  24335. #else
  24336. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24337. std::invalid_argument);
  24338. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24339. std::invalid_argument);
  24340. #endif
  24341. }
  24342. TEST(WebSocketTest, ConnectWhenInvalid) {
  24343. ws::WebSocketClient ws("not a valid url");
  24344. EXPECT_FALSE(ws.is_valid());
  24345. auto res = ws.connect();
  24346. EXPECT_FALSE(res);
  24347. EXPECT_EQ(Error::Connection, res.error());
  24348. EXPECT_EQ(-1, res.status());
  24349. }
  24350. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24351. // Grab a port that is free, then close it again so nothing listens there
  24352. Server svr;
  24353. auto port = svr.bind_to_any_port(HOST);
  24354. svr.stop();
  24355. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24356. auto res = client.connect();
  24357. ASSERT_FALSE(res);
  24358. EXPECT_EQ(Error::Connection, res.error());
  24359. EXPECT_EQ(-1, res.status());
  24360. }
  24361. TEST(WebSocketTest, DefaultPort) {
  24362. ws::WebSocketClient ws1("ws://example.com/path");
  24363. EXPECT_TRUE(ws1.is_valid());
  24364. // ws:// defaults to port 80 (verified by successful parse)
  24365. #ifdef CPPHTTPLIB_SSL_ENABLED
  24366. ws::WebSocketClient ws2("wss://example.com/path");
  24367. EXPECT_TRUE(ws2.is_valid());
  24368. // wss:// defaults to port 443 (verified by successful parse)
  24369. #endif
  24370. }
  24371. TEST(WebSocketTest, IPv6LiteralAddress) {
  24372. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24373. EXPECT_TRUE(ws1.is_valid());
  24374. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24375. EXPECT_TRUE(ws2.is_valid());
  24376. }
  24377. TEST(WebSocketTest, ComplexPath) {
  24378. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24379. EXPECT_TRUE(ws1.is_valid());
  24380. ws::WebSocketClient ws2("ws://localhost:8080/");
  24381. EXPECT_TRUE(ws2.is_valid());
  24382. }
  24383. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24384. Server svr;
  24385. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24386. std::string msg;
  24387. while (ws.read(msg)) {}
  24388. });
  24389. auto port = svr.bind_to_any_port(HOST);
  24390. std::thread t([&]() { svr.listen_after_bind(); });
  24391. svr.wait_until_ready();
  24392. auto another_host = "example.com";
  24393. auto wrong_ip = "192.0.2.1";
  24394. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24395. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24396. ASSERT_TRUE(client.connect());
  24397. EXPECT_TRUE(client.is_open());
  24398. client.close();
  24399. svr.stop();
  24400. t.join();
  24401. }
  24402. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24403. Server svr;
  24404. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24405. std::string msg;
  24406. while (ws.read(msg)) {}
  24407. });
  24408. auto port = svr.bind_to_any_port(HOST);
  24409. std::thread t([&]() { svr.listen_after_bind(); });
  24410. svr.wait_until_ready();
  24411. auto wrong_ip = "192.0.2.1";
  24412. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24413. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24414. client.set_connection_timeout(1);
  24415. client.set_read_timeout(1);
  24416. client.set_write_timeout(1);
  24417. EXPECT_FALSE(client.connect());
  24418. EXPECT_FALSE(client.is_open());
  24419. svr.stop();
  24420. t.join();
  24421. }
  24422. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24423. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24424. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24425. // (RFC 6761) is only a map key and the Host header value.
  24426. auto host = "target.invalid";
  24427. Server svr;
  24428. std::string received_host;
  24429. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24430. received_host = req.get_header_value("Host");
  24431. std::string msg;
  24432. while (ws.read(msg)) {}
  24433. });
  24434. auto port = svr.bind_to_any_port(HOST);
  24435. std::thread t([&]() { svr.listen_after_bind(); });
  24436. // ASSERT_* below returns from the test body, which would leave t joinable
  24437. // and make ~thread call std::terminate.
  24438. auto se = detail::scope_exit([&] {
  24439. svr.stop();
  24440. if (t.joinable()) { t.join(); }
  24441. });
  24442. svr.wait_until_ready();
  24443. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24444. std::to_string(port) + "/ws");
  24445. client.set_direct_hostname_addr_map({{host, HOST}});
  24446. ASSERT_TRUE(client.connect());
  24447. EXPECT_TRUE(client.is_open());
  24448. client.close();
  24449. svr.stop();
  24450. t.join();
  24451. // The mapping only redirects the connection; the identity stays host_.
  24452. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24453. }
  24454. class WebSocketIntegrationTest : public ::testing::Test {
  24455. protected:
  24456. void SetUp() override {
  24457. server_ = httplib::detail::make_unique<Server>();
  24458. setup_server();
  24459. start_server();
  24460. }
  24461. void TearDown() override {
  24462. server_->stop();
  24463. if (server_thread_.joinable()) { server_thread_.join(); }
  24464. }
  24465. void setup_server() {
  24466. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24467. std::string msg;
  24468. ws::ReadResult ret;
  24469. while ((ret = ws.read(msg))) {
  24470. if (ret == ws::Binary) {
  24471. ws.send(msg.data(), msg.size());
  24472. } else {
  24473. ws.send(msg);
  24474. }
  24475. }
  24476. });
  24477. server_->WebSocket("/ws-echo-string",
  24478. [](const Request &, ws::WebSocket &ws) {
  24479. std::string msg;
  24480. while (ws.read(msg)) {
  24481. ws.send("echo: " + msg);
  24482. }
  24483. });
  24484. server_->WebSocket(
  24485. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24486. // Echo back request metadata
  24487. ws.send("path:" + req.path);
  24488. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24489. std::string msg;
  24490. while (ws.read(msg)) {}
  24491. });
  24492. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24493. std::string msg;
  24494. ws.read(msg); // wait for a message
  24495. ws.close();
  24496. });
  24497. server_->WebSocket("/ws-close-status",
  24498. [](const Request &, ws::WebSocket &ws) {
  24499. std::string msg;
  24500. ws.read(msg); // wait for a message
  24501. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24502. });
  24503. server_->WebSocket(
  24504. "/ws-subprotocol",
  24505. [](const Request &, ws::WebSocket &ws) {
  24506. std::string msg;
  24507. while (ws.read(msg)) {
  24508. ws.send(msg);
  24509. }
  24510. },
  24511. [](const std::vector<std::string> &protocols) -> std::string {
  24512. for (const auto &p : protocols) {
  24513. if (p == "graphql-ws") { return p; }
  24514. }
  24515. return "";
  24516. });
  24517. server_->WebSocket(
  24518. "/ws-subprotocol-unoffered",
  24519. [](const Request &, ws::WebSocket &ws) {
  24520. std::string msg;
  24521. while (ws.read(msg)) {
  24522. ws.send(msg);
  24523. }
  24524. },
  24525. [](const std::vector<std::string> &) -> std::string {
  24526. return "admin";
  24527. });
  24528. }
  24529. void start_server() {
  24530. port_ = server_->bind_to_any_port(HOST);
  24531. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24532. server_->wait_until_ready();
  24533. }
  24534. std::unique_ptr<Server> server_;
  24535. std::thread server_thread_;
  24536. int port_ = 0;
  24537. };
  24538. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24539. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24540. "/ws-echo");
  24541. ASSERT_TRUE(client.connect());
  24542. ASSERT_TRUE(client.is_open());
  24543. ASSERT_TRUE(client.send("Hello WebSocket"));
  24544. std::string msg;
  24545. EXPECT_EQ(ws::Text, client.read(msg));
  24546. EXPECT_EQ("Hello WebSocket", msg);
  24547. client.close();
  24548. }
  24549. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24551. "/ws-echo");
  24552. ASSERT_TRUE(client.connect());
  24553. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24554. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24555. std::string msg;
  24556. EXPECT_EQ(ws::Binary, client.read(msg));
  24557. EXPECT_EQ(binary_data, msg);
  24558. client.close();
  24559. }
  24560. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24561. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24562. "/ws-echo");
  24563. ASSERT_TRUE(client.connect());
  24564. for (int i = 0; i < 10; i++) {
  24565. auto text = "message " + std::to_string(i);
  24566. ASSERT_TRUE(client.send(text));
  24567. std::string msg;
  24568. ASSERT_TRUE(client.read(msg));
  24569. EXPECT_EQ(text, msg);
  24570. }
  24571. client.close();
  24572. }
  24573. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24575. "/ws-close");
  24576. ASSERT_TRUE(client.connect());
  24577. // Send a message to trigger the server to close
  24578. ASSERT_TRUE(client.send("trigger close"));
  24579. // The server will close, so read should return false
  24580. std::string msg;
  24581. EXPECT_FALSE(client.read(msg));
  24582. EXPECT_FALSE(client.is_open());
  24583. }
  24584. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24586. "/ws-echo");
  24587. ASSERT_TRUE(client.connect());
  24588. // 128KB message
  24589. std::string large_data(128 * 1024, 'X');
  24590. ASSERT_TRUE(client.send(large_data));
  24591. std::string msg;
  24592. ASSERT_TRUE(client.read(msg));
  24593. EXPECT_EQ(large_data, msg);
  24594. client.close();
  24595. }
  24596. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24598. "/ws-echo");
  24599. ASSERT_TRUE(client.connect());
  24600. const int num_threads = 4;
  24601. std::vector<std::thread> threads;
  24602. std::atomic<int> send_count{0};
  24603. for (int t = 0; t < num_threads; t++) {
  24604. threads.emplace_back([&client, &send_count, t]() {
  24605. for (int i = 0; i < 5; i++) {
  24606. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24607. if (client.send(text)) { send_count++; }
  24608. }
  24609. });
  24610. }
  24611. for (auto &th : threads) {
  24612. th.join();
  24613. }
  24614. int received = 0;
  24615. std::string msg;
  24616. while (received < send_count.load()) {
  24617. if (!client.read(msg)) { break; }
  24618. received++;
  24619. }
  24620. EXPECT_EQ(send_count.load(), received);
  24621. client.close();
  24622. }
  24623. TEST_F(WebSocketIntegrationTest, ReadString) {
  24624. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24625. "/ws-echo-string");
  24626. ASSERT_TRUE(client.connect());
  24627. ASSERT_TRUE(client.send("hello"));
  24628. std::string msg;
  24629. ASSERT_TRUE(client.read(msg));
  24630. EXPECT_EQ("echo: hello", msg);
  24631. ASSERT_TRUE(client.send("world"));
  24632. ASSERT_TRUE(client.read(msg));
  24633. EXPECT_EQ("echo: world", msg);
  24634. client.close();
  24635. }
  24636. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24637. Headers headers = {{"X-Test-Header", "test-value"}};
  24638. ws::WebSocketClient client(
  24639. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24640. ASSERT_TRUE(client.connect());
  24641. std::string msg;
  24642. ASSERT_TRUE(client.read(msg));
  24643. EXPECT_EQ("path:/ws-request-info", msg);
  24644. ASSERT_TRUE(client.read(msg));
  24645. EXPECT_EQ("header:test-value", msg);
  24646. client.close();
  24647. }
  24648. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24649. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24650. "/ws-echo");
  24651. client.set_read_timeout(1, 0); // 1 second
  24652. ASSERT_TRUE(client.connect());
  24653. // Don't send anything — server echo handler waits for a message, so read()
  24654. // should time out. The connection survives it: nothing was consumed.
  24655. std::string msg;
  24656. EXPECT_EQ(client.read(msg), ws::Timeout);
  24657. EXPECT_TRUE(client.is_open());
  24658. // And it is still usable afterwards.
  24659. EXPECT_TRUE(client.send("after timeout"));
  24660. EXPECT_EQ(client.read(msg), ws::Text);
  24661. EXPECT_EQ(msg, "after timeout");
  24662. }
  24663. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24664. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24665. "/ws-echo");
  24666. client.set_read_timeout(1, 0);
  24667. ASSERT_TRUE(client.connect());
  24668. ASSERT_TRUE(client.send("first"));
  24669. std::string msg;
  24670. ASSERT_EQ(client.read(msg), ws::Text);
  24671. ASSERT_EQ(msg, "first");
  24672. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24673. // not be used with a read timeout: it would reprocess the previous message.
  24674. EXPECT_EQ(client.read(msg), ws::Timeout);
  24675. EXPECT_EQ(msg, "first");
  24676. }
  24677. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24678. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24679. "/ws-echo");
  24680. ASSERT_TRUE(client.connect());
  24681. // Setting it once the connection is open reaches the live stream, not just
  24682. // the seed for the next connect().
  24683. client.set_read_timeout(1, 0);
  24684. std::string msg;
  24685. EXPECT_EQ(client.read(msg), ws::Timeout);
  24686. EXPECT_TRUE(client.is_open());
  24687. }
  24688. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24690. "/ws-echo");
  24691. client.set_read_timeout(5, 0);
  24692. ASSERT_TRUE(client.connect());
  24693. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24694. // The server should reject it and close the connection.
  24695. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24696. client.send(oversized);
  24697. // The server's read() should have failed due to payload limit,
  24698. // so our read() should return false (connection closed).
  24699. std::string msg;
  24700. EXPECT_FALSE(client.read(msg));
  24701. }
  24702. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24703. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24704. "/ws-echo");
  24705. client.set_read_timeout(10, 0);
  24706. ASSERT_TRUE(client.connect());
  24707. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24708. // This should succeed.
  24709. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24710. ASSERT_TRUE(client.send(at_limit));
  24711. std::string msg;
  24712. ASSERT_TRUE(client.read(msg));
  24713. EXPECT_EQ(at_limit.size(), msg.size());
  24714. client.close();
  24715. }
  24716. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24718. "/nonexistent");
  24719. auto res = client.connect();
  24720. EXPECT_FALSE(res);
  24721. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24722. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24723. EXPECT_FALSE(client.is_open());
  24724. }
  24725. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24727. "/ws-echo");
  24728. ASSERT_TRUE(client.connect());
  24729. ASSERT_TRUE(client.send(""));
  24730. std::string msg;
  24731. EXPECT_EQ(ws::Text, client.read(msg));
  24732. EXPECT_EQ("", msg);
  24733. client.close();
  24734. }
  24735. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24736. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24737. "/ws-echo");
  24738. // First connection
  24739. ASSERT_TRUE(client.connect());
  24740. ASSERT_TRUE(client.send("first"));
  24741. std::string msg;
  24742. ASSERT_TRUE(client.read(msg));
  24743. EXPECT_EQ("first", msg);
  24744. client.close();
  24745. EXPECT_FALSE(client.is_open());
  24746. // Reconnect using the same client object
  24747. ASSERT_TRUE(client.connect());
  24748. ASSERT_TRUE(client.is_open());
  24749. ASSERT_TRUE(client.send("second"));
  24750. ASSERT_TRUE(client.read(msg));
  24751. EXPECT_EQ("second", msg);
  24752. client.close();
  24753. }
  24754. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24756. "/ws-close-status");
  24757. ASSERT_TRUE(client.connect());
  24758. // Trigger the server to close with GoingAway status
  24759. ASSERT_TRUE(client.send("trigger"));
  24760. // read() should return false after receiving the close frame
  24761. std::string msg;
  24762. EXPECT_FALSE(client.read(msg));
  24763. EXPECT_FALSE(client.is_open());
  24764. }
  24765. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24766. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24767. "/ws-echo");
  24768. ASSERT_TRUE(client.connect());
  24769. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24770. EXPECT_FALSE(client.is_open());
  24771. }
  24772. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24773. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24774. ws::WebSocketClient client(
  24775. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24776. ASSERT_TRUE(client.connect());
  24777. // Server should have selected graphql-ws
  24778. EXPECT_EQ("graphql-ws", client.subprotocol());
  24779. client.close();
  24780. }
  24781. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24782. Headers headers;
  24783. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24784. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24785. ws::WebSocketClient client(
  24786. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24787. ASSERT_TRUE(client.connect());
  24788. // The offer on the second field line counts too, so graphql-ws is selected
  24789. EXPECT_EQ("graphql-ws", client.subprotocol());
  24790. client.close();
  24791. }
  24792. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24793. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24794. ws::WebSocketClient client(
  24795. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24796. ASSERT_TRUE(client.connect());
  24797. // Server should not have selected any subprotocol
  24798. EXPECT_TRUE(client.subprotocol().empty());
  24799. client.close();
  24800. }
  24801. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24802. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24804. "/ws-subprotocol-unoffered",
  24805. headers);
  24806. ASSERT_TRUE(client.connect());
  24807. EXPECT_TRUE(client.subprotocol().empty());
  24808. client.close();
  24809. }
  24810. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24811. // Connect without requesting any subprotocol
  24812. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24813. "/ws-subprotocol");
  24814. ASSERT_TRUE(client.connect());
  24815. EXPECT_TRUE(client.subprotocol().empty());
  24816. client.close();
  24817. }
  24818. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24820. "/ws-echo");
  24821. client.set_tcp_nodelay(true);
  24822. client.set_connection_timeout(3, 0);
  24823. bool socket_options_called = false;
  24824. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24825. ASSERT_TRUE(client.connect());
  24826. ASSERT_TRUE(client.is_open());
  24827. EXPECT_TRUE(socket_options_called);
  24828. ASSERT_TRUE(client.send("hello"));
  24829. std::string msg;
  24830. auto result = client.read(msg);
  24831. EXPECT_EQ(result, ws::ReadResult::Text);
  24832. EXPECT_EQ(msg, "hello");
  24833. client.close();
  24834. }
  24835. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24837. "/ws-echo");
  24838. client.set_connection_timeout(std::chrono::seconds(3));
  24839. client.set_write_timeout(std::chrono::seconds(3));
  24840. // A sub-second remainder exercises the seconds/microseconds split.
  24841. client.set_read_timeout(std::chrono::milliseconds(1500));
  24842. ASSERT_TRUE(client.connect());
  24843. auto start = std::chrono::steady_clock::now();
  24844. std::string msg;
  24845. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24846. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24847. std::chrono::steady_clock::now() - start)
  24848. .count();
  24849. // Above 1s so that dropping the microseconds half of the split fails here.
  24850. // Ignoring the setter altogether would not reach this line at all: a client
  24851. // waits forever by default.
  24852. EXPECT_GE(elapsed, 1400);
  24853. EXPECT_LT(elapsed, 30000);
  24854. }
  24855. #ifndef _WIN32
  24856. // A send() that times out after part of the data went out returns the count
  24857. // written so far. Every byte of the frame must still be sent, or the peer reads
  24858. // the next frame's header and payload as the rest of this one.
  24859. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24860. signal(SIGPIPE, SIG_IGN);
  24861. const std::string large(4 * 1024 * 1024, 'A');
  24862. std::atomic<bool> large_sent{false};
  24863. std::atomic<bool> small_sent{false};
  24864. Server svr;
  24865. svr.set_write_timeout(0, 500000);
  24866. svr.set_socket_options([](socket_t sock) {
  24867. int size = 8192;
  24868. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24869. reinterpret_cast<const char *>(&size), sizeof(size));
  24870. });
  24871. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24872. large_sent = ws.send(large.data(), large.size());
  24873. small_sent = ws.send("after");
  24874. std::string msg;
  24875. while (ws.read(msg)) {}
  24876. });
  24877. auto port = svr.bind_to_any_port(HOST);
  24878. std::thread t([&]() { svr.listen_after_bind(); });
  24879. auto se = detail::scope_exit([&] {
  24880. svr.stop();
  24881. t.join();
  24882. });
  24883. svr.wait_until_ready();
  24884. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24885. std::to_string(port) + "/ws");
  24886. client.set_read_timeout(5);
  24887. client.set_socket_options([](socket_t sock) {
  24888. int size = 8192;
  24889. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24890. reinterpret_cast<const char *>(&size), sizeof(size));
  24891. });
  24892. ASSERT_TRUE(client.connect());
  24893. // Outlast the server's write timeout, then drain.
  24894. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24895. std::string msg;
  24896. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24897. EXPECT_TRUE(msg == large);
  24898. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24899. EXPECT_EQ("after", msg);
  24900. EXPECT_TRUE(large_sent);
  24901. EXPECT_TRUE(small_sent);
  24902. client.close();
  24903. }
  24904. #endif
  24905. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24906. Server svr;
  24907. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24908. if (!req.has_header("Authorization")) {
  24909. res.status = StatusCode::Unauthorized_401;
  24910. res.set_content("Unauthorized", "text/plain");
  24911. return Server::HandlerResponse::Handled;
  24912. }
  24913. return Server::HandlerResponse::Unhandled;
  24914. });
  24915. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24916. std::string msg;
  24917. while (ws.read(msg)) {
  24918. ws.send(msg);
  24919. }
  24920. });
  24921. auto port = svr.bind_to_any_port("localhost");
  24922. std::thread t([&]() { svr.listen_after_bind(); });
  24923. svr.wait_until_ready();
  24924. // Without Authorization header - should be rejected before upgrade
  24925. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24926. EXPECT_FALSE(client1.connect());
  24927. // The rejection is framed like any other HTTP response
  24928. {
  24929. Client cli("localhost", port);
  24930. Headers headers = {{"Upgrade", "websocket"},
  24931. {"Connection", "Upgrade"},
  24932. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24933. {"Sec-WebSocket-Version", "13"}};
  24934. auto res = cli.Get("/ws", headers);
  24935. ASSERT_TRUE(res);
  24936. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24937. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24938. EXPECT_EQ("Unauthorized", res->body);
  24939. }
  24940. // With Authorization header - should succeed
  24941. Headers headers = {{"Authorization", "Bearer token123"}};
  24942. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24943. headers);
  24944. ASSERT_TRUE(client2.connect());
  24945. ASSERT_TRUE(client2.send("hello"));
  24946. std::string msg;
  24947. ASSERT_TRUE(client2.read(msg));
  24948. EXPECT_EQ("hello", msg);
  24949. client2.close();
  24950. svr.stop();
  24951. t.join();
  24952. }
  24953. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24954. Server svr;
  24955. std::atomic<int> pre_routing_calls{0};
  24956. std::atomic<int> pre_request_calls{0};
  24957. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24958. pre_routing_calls++;
  24959. if (req.path == "/handled") {
  24960. res.set_content("handled", "text/plain");
  24961. return Server::HandlerResponse::Handled;
  24962. }
  24963. return Server::HandlerResponse::Unhandled;
  24964. });
  24965. svr.set_pre_request_handler([&](const Request &, Response &) {
  24966. pre_request_calls++;
  24967. return Server::HandlerResponse::Unhandled;
  24968. });
  24969. svr.Get("/http", [](const Request &, Response &res) {
  24970. res.set_content("http", "text/plain");
  24971. });
  24972. svr.WebSocket("/ws",
  24973. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24974. auto port = svr.bind_to_any_port("localhost");
  24975. std::thread t([&]() { svr.listen_after_bind(); });
  24976. auto se = detail::scope_exit([&] {
  24977. svr.stop();
  24978. t.join();
  24979. });
  24980. svr.wait_until_ready();
  24981. Headers upgrade = {{"Upgrade", "websocket"},
  24982. {"Connection", "Upgrade"},
  24983. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24984. {"Sec-WebSocket-Version", "13"}};
  24985. auto get = [&](const char *path) {
  24986. pre_routing_calls = 0;
  24987. return Client("localhost", port).Get(path, upgrade);
  24988. };
  24989. // No WebSocket route, but an HTTP one
  24990. auto res = get("/http");
  24991. ASSERT_TRUE(res);
  24992. EXPECT_EQ(StatusCode::OK_200, res->status);
  24993. EXPECT_EQ("http", res->body);
  24994. EXPECT_EQ(1, pre_routing_calls);
  24995. EXPECT_EQ(1, pre_request_calls);
  24996. // No route at all
  24997. res = get("/none");
  24998. ASSERT_TRUE(res);
  24999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25000. EXPECT_EQ(1, pre_routing_calls);
  25001. // Answered by the pre-routing handler
  25002. res = get("/handled");
  25003. ASSERT_TRUE(res);
  25004. EXPECT_EQ(StatusCode::OK_200, res->status);
  25005. EXPECT_EQ("handled", res->body);
  25006. EXPECT_EQ(1, pre_routing_calls);
  25007. // A WebSocket route
  25008. pre_routing_calls = 0;
  25009. pre_request_calls = 0;
  25010. {
  25011. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25012. "/ws");
  25013. ASSERT_TRUE(client.connect());
  25014. std::string msg;
  25015. ASSERT_TRUE(client.read(msg));
  25016. EXPECT_EQ("ws", msg);
  25017. client.close();
  25018. }
  25019. EXPECT_EQ(1, pre_routing_calls);
  25020. EXPECT_EQ(1, pre_request_calls);
  25021. }
  25022. // An upgrade request answered by a hook leaves its body unread, so that body
  25023. // must not be served as the next request on the connection.
  25024. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25025. Server svr;
  25026. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25027. if (req.path == "/pre-routing") {
  25028. res.set_content("pre-routing", "text/plain");
  25029. return Server::HandlerResponse::Handled;
  25030. }
  25031. return Server::HandlerResponse::Unhandled;
  25032. });
  25033. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25034. if (req.matched_route == "/pre-request") {
  25035. res.set_content("pre-request", "text/plain");
  25036. return Server::HandlerResponse::Handled;
  25037. }
  25038. return Server::HandlerResponse::Unhandled;
  25039. });
  25040. svr.Get("/smuggled", [](const Request &, Response &res) {
  25041. res.set_content("smuggled", "text/plain");
  25042. });
  25043. svr.WebSocket("/pre-request",
  25044. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25045. auto port = svr.bind_to_any_port(HOST);
  25046. std::thread t([&]() { svr.listen_after_bind(); });
  25047. auto se = detail::scope_exit([&] {
  25048. svr.stop();
  25049. t.join();
  25050. });
  25051. svr.wait_until_ready();
  25052. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25053. for (auto path : {"/pre-routing", "/pre-request"}) {
  25054. std::string req = std::string("GET ") + path +
  25055. " HTTP/1.1\r\n"
  25056. "Host: localhost\r\n"
  25057. "Upgrade: websocket\r\n"
  25058. "Connection: Upgrade\r\n"
  25059. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25060. "Sec-WebSocket-Version: 13\r\n"
  25061. "Content-Length: " +
  25062. std::to_string(body.size()) + "\r\n\r\n" + body;
  25063. std::string res;
  25064. ASSERT_TRUE(send_request(5, req, &res, port));
  25065. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25066. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25067. // Only one response, and the body was not served as a request
  25068. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25069. }
  25070. }
  25071. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25072. Server svr;
  25073. std::atomic<int> pre_request_calls{0};
  25074. std::atomic<bool> route_matched{false};
  25075. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25076. pre_request_calls++;
  25077. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25078. if (req.get_header_value("Authorization") != "Bearer token123") {
  25079. res.status = StatusCode::Unauthorized_401;
  25080. res.set_content("Unauthorized", "text/plain");
  25081. return Server::HandlerResponse::Handled;
  25082. }
  25083. return Server::HandlerResponse::Unhandled;
  25084. });
  25085. std::atomic<bool> handler_called{false};
  25086. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25087. handler_called = true;
  25088. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25089. });
  25090. auto port = svr.bind_to_any_port("localhost");
  25091. std::thread t([&]() { svr.listen_after_bind(); });
  25092. svr.wait_until_ready();
  25093. // Without Authorization header - should be rejected before upgrade
  25094. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25095. "/ws/1");
  25096. EXPECT_FALSE(client1.connect());
  25097. EXPECT_FALSE(handler_called);
  25098. EXPECT_EQ(1, pre_request_calls);
  25099. EXPECT_TRUE(route_matched);
  25100. // The rejection is an ordinary HTTP response, not a protocol switch
  25101. {
  25102. Client cli("localhost", port);
  25103. Headers headers = {{"Upgrade", "websocket"},
  25104. {"Connection", "Upgrade"},
  25105. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25106. {"Sec-WebSocket-Version", "13"}};
  25107. auto res = cli.Get("/ws/1", headers);
  25108. ASSERT_TRUE(res);
  25109. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25110. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25111. EXPECT_EQ("Unauthorized", res->body);
  25112. }
  25113. EXPECT_FALSE(handler_called);
  25114. // With Authorization header - should succeed
  25115. Headers headers = {{"Authorization", "Bearer token123"}};
  25116. ws::WebSocketClient client2(
  25117. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25118. ASSERT_TRUE(client2.connect());
  25119. std::string msg;
  25120. ASSERT_TRUE(client2.read(msg));
  25121. EXPECT_EQ("/ws/:id 2", msg);
  25122. EXPECT_TRUE(handler_called);
  25123. client2.close();
  25124. svr.stop();
  25125. t.join();
  25126. }
  25127. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25128. static Headers websocket_upgrade_headers() {
  25129. return {{"Upgrade", "websocket"},
  25130. {"Connection", "Upgrade"},
  25131. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25132. {"Sec-WebSocket-Version", "13"},
  25133. {"Sec-WebSocket-Protocol", "chat"}};
  25134. }
  25135. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25136. Server svr;
  25137. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25138. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25139. return Server::HandlerResponse::Unhandled;
  25140. });
  25141. svr.set_pre_request_handler([](const Request &req, Response &) {
  25142. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25143. return Server::HandlerResponse::Unhandled;
  25144. });
  25145. svr.set_exception_handler(
  25146. [](const Request &, Response &res, std::exception_ptr ep) {
  25147. try {
  25148. std::rethrow_exception(ep);
  25149. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25150. });
  25151. auto handler = [](const Request &, ws::WebSocket &) {};
  25152. svr.WebSocket("/pre-routing", handler);
  25153. svr.WebSocket("/pre-request", handler);
  25154. svr.WebSocket("/sub-protocol", handler,
  25155. [](const std::vector<std::string> &) -> std::string {
  25156. throw std::runtime_error("/sub-protocol");
  25157. });
  25158. auto port = svr.bind_to_any_port(HOST);
  25159. ASSERT_GT(port, 0);
  25160. thread t = thread([&] { svr.listen_after_bind(); });
  25161. auto se = detail::scope_exit([&] {
  25162. svr.stop();
  25163. t.join();
  25164. ASSERT_FALSE(svr.is_running());
  25165. });
  25166. svr.wait_until_ready();
  25167. Client cli(HOST, port);
  25168. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25169. auto res = cli.Get(path, websocket_upgrade_headers());
  25170. if (!res) {
  25171. ADD_FAILURE() << path << ": " << to_string(res.error());
  25172. continue;
  25173. }
  25174. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25175. EXPECT_EQ(path, res->body);
  25176. }
  25177. }
  25178. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25179. Server svr;
  25180. svr.set_pre_routing_handler(
  25181. [](const Request &, Response &) -> Server::HandlerResponse {
  25182. throw std::runtime_error("pre-routing");
  25183. });
  25184. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25185. auto port = svr.bind_to_any_port(HOST);
  25186. ASSERT_GT(port, 0);
  25187. thread t = thread([&] { svr.listen_after_bind(); });
  25188. auto se = detail::scope_exit([&] {
  25189. svr.stop();
  25190. t.join();
  25191. ASSERT_FALSE(svr.is_running());
  25192. });
  25193. svr.wait_until_ready();
  25194. Client cli(HOST, port);
  25195. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25196. ASSERT_TRUE(res) << to_string(res.error());
  25197. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25198. }
  25199. #endif
  25200. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25201. Server svr;
  25202. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25203. // A read timeout is how a handler gets control back. Without it, a handler
  25204. // parked in read() can never write on the connection it is reading.
  25205. ws.set_read_timeout(std::chrono::milliseconds(100));
  25206. std::string msg;
  25207. while (ws.is_open()) {
  25208. auto r = ws.read(msg);
  25209. if (r == httplib::ws::Timeout) {
  25210. ws.send("tick");
  25211. continue;
  25212. }
  25213. if (r == httplib::ws::Fail) { break; }
  25214. ws.send(msg);
  25215. }
  25216. });
  25217. auto port = svr.bind_to_any_port("localhost");
  25218. std::thread t([&]() { svr.listen_after_bind(); });
  25219. svr.wait_until_ready();
  25220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25221. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25222. ASSERT_TRUE(client.connect());
  25223. // The client sends nothing, so anything it receives came out of the
  25224. // handler's timeout path.
  25225. std::string msg;
  25226. ASSERT_EQ(client.read(msg), ws::Text);
  25227. EXPECT_EQ("tick", msg);
  25228. client.close();
  25229. svr.stop();
  25230. t.join();
  25231. }
  25232. // Stream::read may return fewer bytes than asked for. This is that contract at
  25233. // its worst -- one byte per call -- which is what a frame header straddling a
  25234. // read buffer's boundary looks like to the frame parser.
  25235. class WsByteAtATimeStream : public Stream {
  25236. public:
  25237. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25238. bool is_readable() const override { return true; }
  25239. bool wait_readable() const override { return true; }
  25240. bool wait_writable() const override { return true; }
  25241. ssize_t read(char *ptr, size_t size) override {
  25242. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25243. *ptr = data_[pos_++];
  25244. return 1;
  25245. }
  25246. ssize_t write(const char *, size_t size) override {
  25247. return static_cast<ssize_t>(size);
  25248. }
  25249. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25250. ip = "127.0.0.1";
  25251. port = 0;
  25252. }
  25253. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25254. ip = "127.0.0.1";
  25255. port = 0;
  25256. }
  25257. socket_t socket() const override { return INVALID_SOCKET; }
  25258. time_t duration() const override { return 0; }
  25259. private:
  25260. std::string data_;
  25261. size_t pos_ = 0;
  25262. };
  25263. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25264. // The payload uses the 16-bit extended length, so the header, the length
  25265. // and the mask key are all multi-byte fields here. Each used to be read
  25266. // with a single read() call, which fails as soon as one is split. The
  25267. // payload is also a little over one read chunk, so it is read in two.
  25268. std::string body;
  25269. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25270. body += static_cast<char>(i % 251);
  25271. }
  25272. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25273. std::string frame;
  25274. frame += static_cast<char>(0x81); // FIN + Text
  25275. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25276. frame += static_cast<char>(body.size() >> 8);
  25277. frame += static_cast<char>(body.size() & 0xff);
  25278. for (size_t i = 0; i < 4; i++) {
  25279. frame += static_cast<char>(mask[i]);
  25280. }
  25281. for (size_t i = 0; i < body.size(); i++) {
  25282. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25283. }
  25284. WsByteAtATimeStream strm(frame);
  25285. ws::Opcode opcode;
  25286. std::string payload;
  25287. bool fin = false;
  25288. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25289. /*expect_masked=*/true, body.size()),
  25290. ws::impl::FrameRead::Ok);
  25291. EXPECT_TRUE(fin);
  25292. EXPECT_EQ(opcode, ws::Opcode::Text);
  25293. EXPECT_EQ(payload, body);
  25294. }
  25295. // Keeps what is written, counting the writes, and reads it back.
  25296. class WsWriteCountingStream : public Stream {
  25297. public:
  25298. bool is_readable() const override { return true; }
  25299. bool wait_readable() const override { return true; }
  25300. bool wait_writable() const override { return true; }
  25301. ssize_t read(char *ptr, size_t size) override {
  25302. auto n = (std::min)(size, data_.size() - pos_);
  25303. if (n == 0) { return 0; }
  25304. memcpy(ptr, data_.data() + pos_, n);
  25305. pos_ += n;
  25306. return static_cast<ssize_t>(n);
  25307. }
  25308. ssize_t write(const char *ptr, size_t size) override {
  25309. writes++;
  25310. data_.append(ptr, size);
  25311. return static_cast<ssize_t>(size);
  25312. }
  25313. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25314. ip = "127.0.0.1";
  25315. port = 0;
  25316. }
  25317. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25318. ip = "127.0.0.1";
  25319. port = 0;
  25320. }
  25321. socket_t socket() const override { return INVALID_SOCKET; }
  25322. time_t duration() const override { return 0; }
  25323. int writes = 0;
  25324. private:
  25325. std::string data_;
  25326. size_t pos_ = 0;
  25327. };
  25328. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25329. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25330. // masked and not, reads back as written; a payload over one chunk follows
  25331. // its first in more writes.
  25332. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25333. for (auto mask : {false, true}) {
  25334. std::string body(len, '\0');
  25335. for (size_t i = 0; i < len; i++) {
  25336. body[i] = static_cast<char>(i % 251);
  25337. }
  25338. WsWriteCountingStream strm;
  25339. ASSERT_TRUE(detail::write_websocket_frame(
  25340. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25341. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25342. ws::Opcode opcode;
  25343. std::string payload;
  25344. bool fin = false;
  25345. ASSERT_EQ(
  25346. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25347. ws::impl::FrameRead::Ok)
  25348. << len << " " << mask;
  25349. EXPECT_TRUE(fin);
  25350. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25351. EXPECT_EQ(body, payload) << len << " " << mask;
  25352. }
  25353. }
  25354. }
  25355. // Hands out its pieces one read at a time, timing out between each two.
  25356. class WsTimeoutBetweenPiecesStream : public Stream {
  25357. public:
  25358. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25359. : pieces_(std::move(pieces)) {}
  25360. bool is_readable() const override { return true; }
  25361. bool wait_readable() const override { return true; }
  25362. bool wait_writable() const override { return true; }
  25363. ssize_t read(char *ptr, size_t size) override {
  25364. if (time_out_) {
  25365. time_out_ = false;
  25366. error_ = Error::Timeout;
  25367. return -1;
  25368. }
  25369. if (i_ >= pieces_.size()) {
  25370. error_ = Error::ConnectionClosed;
  25371. return 0;
  25372. }
  25373. auto &piece = pieces_[i_];
  25374. auto n = (std::min)(size, piece.size() - at_);
  25375. memcpy(ptr, piece.data() + at_, n);
  25376. at_ += n;
  25377. if (at_ == piece.size()) {
  25378. i_++;
  25379. at_ = 0;
  25380. time_out_ = true;
  25381. }
  25382. return static_cast<ssize_t>(n);
  25383. }
  25384. ssize_t write(const char *, size_t size) override {
  25385. return static_cast<ssize_t>(size);
  25386. }
  25387. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25388. ip = "127.0.0.1";
  25389. port = 0;
  25390. }
  25391. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25392. ip = "127.0.0.1";
  25393. port = 0;
  25394. }
  25395. socket_t socket() const override { return INVALID_SOCKET; }
  25396. time_t duration() const override { return 0; }
  25397. private:
  25398. std::vector<std::string> pieces_;
  25399. size_t i_ = 0;
  25400. size_t at_ = 0;
  25401. bool time_out_ = false;
  25402. };
  25403. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25404. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25405. std::string frame = "\x81\x85";
  25406. frame.append(4, '\0');
  25407. frame += "Hello";
  25408. // The header's first byte, then its second with half the mask key, then
  25409. // the rest
  25410. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25411. frame.substr(4)};
  25412. WsTimeoutBetweenPiecesStream strm(pieces);
  25413. ws::impl::FrameReader reader;
  25414. ws::Opcode opcode;
  25415. std::string payload;
  25416. bool fin = false;
  25417. for (int i = 0; i < 2; i++) {
  25418. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25419. reader.read(strm, opcode, payload, fin, true, 0));
  25420. EXPECT_TRUE(reader.begun());
  25421. }
  25422. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25423. reader.read(strm, opcode, payload, fin, true, 0));
  25424. EXPECT_FALSE(reader.begun());
  25425. EXPECT_TRUE(fin);
  25426. EXPECT_EQ(ws::Opcode::Text, opcode);
  25427. EXPECT_EQ("Hello", payload);
  25428. // Read in one go, the frame cannot be gone on with after a timeout
  25429. WsTimeoutBetweenPiecesStream again(pieces);
  25430. EXPECT_EQ(
  25431. ws::impl::FrameRead::Fail,
  25432. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25433. }
  25434. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25435. std::string body(2000, 'x');
  25436. std::string frame;
  25437. frame += static_cast<char>(0x82); // FIN + Binary
  25438. frame += static_cast<char>(126); // 16-bit length follows
  25439. frame += static_cast<char>(body.size() >> 8);
  25440. frame += static_cast<char>(body.size() & 0xff);
  25441. frame += body;
  25442. detail::BufferStream strm;
  25443. strm.write(frame.data(), frame.size());
  25444. ws::Opcode opcode;
  25445. std::string payload;
  25446. bool fin;
  25447. EXPECT_EQ(
  25448. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25449. ws::impl::FrameRead::Ok);
  25450. EXPECT_EQ(body, payload);
  25451. }
  25452. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25453. // The header announces the largest payload allowed, and only 3 bytes of it
  25454. // ever arrive.
  25455. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25456. std::string frame;
  25457. frame += static_cast<char>(0x82); // FIN + Binary
  25458. frame += static_cast<char>(127); // 64-bit length follows
  25459. for (int shift = 56; shift >= 0; shift -= 8) {
  25460. frame += static_cast<char>((len >> shift) & 0xff);
  25461. }
  25462. frame += "abc";
  25463. detail::BufferStream strm;
  25464. strm.write(frame.data(), frame.size());
  25465. ws::Opcode opcode;
  25466. std::string payload;
  25467. bool fin;
  25468. EXPECT_EQ(
  25469. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25470. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25471. ws::impl::FrameRead::Fail);
  25472. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25473. }
  25474. TEST(WebSocketTest, QueryStringInHandshake) {
  25475. Server svr;
  25476. std::mutex mtx;
  25477. std::string received_target;
  25478. std::string received_token;
  25479. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25480. {
  25481. std::lock_guard<std::mutex> lock(mtx);
  25482. received_target = req.target;
  25483. if (req.has_param("token")) {
  25484. received_token = req.get_param_value("token");
  25485. }
  25486. }
  25487. std::string msg;
  25488. while (ws.read(msg)) {
  25489. ws.send(msg);
  25490. }
  25491. });
  25492. auto port = svr.bind_to_any_port("localhost");
  25493. std::thread t([&]() { svr.listen_after_bind(); });
  25494. svr.wait_until_ready();
  25495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25496. "/ws?token=ABC&session=123");
  25497. ASSERT_TRUE(client.connect());
  25498. // Round-trip ensures the handler has run and captured the request.
  25499. ASSERT_TRUE(client.send("hello"));
  25500. std::string msg;
  25501. ASSERT_TRUE(client.read(msg));
  25502. EXPECT_EQ("hello", msg);
  25503. client.close();
  25504. {
  25505. std::lock_guard<std::mutex> lock(mtx);
  25506. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25507. EXPECT_EQ("ABC", received_token);
  25508. }
  25509. svr.stop();
  25510. t.join();
  25511. }
  25512. // Run a handshake against a throwaway server and hand the request the server
  25513. // received back to the caller, so tests can assert on the headers the client
  25514. // actually put on the wire.
  25515. static void capture_websocket_handshake_request(
  25516. const Headers &client_headers,
  25517. std::function<void(const Request &, int port)> verify) {
  25518. Server svr;
  25519. std::mutex mtx;
  25520. Request received;
  25521. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25522. {
  25523. std::lock_guard<std::mutex> lock(mtx);
  25524. received = req;
  25525. }
  25526. std::string msg;
  25527. while (ws.read(msg)) {
  25528. ws.send(msg);
  25529. }
  25530. });
  25531. auto port = svr.bind_to_any_port("localhost");
  25532. std::thread t([&]() { svr.listen_after_bind(); });
  25533. auto se = detail::scope_exit([&] {
  25534. svr.stop();
  25535. t.join();
  25536. });
  25537. svr.wait_until_ready();
  25538. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25539. client_headers);
  25540. ASSERT_TRUE(client.connect());
  25541. ASSERT_TRUE(client.send("hello"));
  25542. std::string msg;
  25543. ASSERT_TRUE(client.read(msg));
  25544. client.close();
  25545. {
  25546. std::lock_guard<std::mutex> lock(mtx);
  25547. verify(received, port);
  25548. }
  25549. }
  25550. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25551. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25552. // Non-default port must be present in the Host header. Default ports
  25553. // (80/443) are omitted; that logic is covered by
  25554. // MakeHostAndPortStringTest.
  25555. EXPECT_EQ("localhost:" + std::to_string(port),
  25556. req.get_header_value("Host"));
  25557. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25558. req.get_header_value("User-Agent"));
  25559. EXPECT_FALSE(req.has_header("Accept"));
  25560. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25561. EXPECT_FALSE(req.has_header("Content-Length"));
  25562. });
  25563. }
  25564. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25565. capture_websocket_handshake_request(
  25566. {{"Host", "example.com"},
  25567. {"User-Agent", "custom-agent"},
  25568. {"X-Custom", "value"}},
  25569. [](const Request &req, int) {
  25570. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25571. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25572. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25573. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25574. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25575. });
  25576. }
  25577. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25578. capture_websocket_handshake_request(
  25579. {{"Upgrade", "bogus"},
  25580. {"Connection", "close"},
  25581. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25582. {"Sec-WebSocket-Version", "8"}},
  25583. [](const Request &req, int) {
  25584. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25585. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25586. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25587. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25588. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25589. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25590. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25591. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25592. req.get_header_value("Sec-WebSocket-Key"));
  25593. });
  25594. }
  25595. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25596. // A header the client refuses to send must abort the handshake before any
  25597. // part of it reaches the wire; a lone request line would otherwise sit in
  25598. // the peer's buffer as a truncated request.
  25599. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25600. ASSERT_NE(INVALID_SOCKET, srv);
  25601. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25602. sockaddr_in addr{};
  25603. addr.sin_family = AF_INET;
  25604. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25606. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25607. ASSERT_EQ(0, ::listen(srv, 1));
  25608. sockaddr_in bound{};
  25609. socklen_t bound_len = sizeof(bound);
  25610. ASSERT_EQ(
  25611. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25612. auto port = ntohs(bound.sin_port);
  25613. ssize_t received = -1;
  25614. std::thread t([&] {
  25615. // Bound every blocking call so a regression fails the test with a bad
  25616. // value instead of hanging the suite.
  25617. fd_set rfds;
  25618. FD_ZERO(&rfds);
  25619. FD_SET(srv, &rfds);
  25620. timeval tv{5, 0};
  25621. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25622. 0) {
  25623. return;
  25624. }
  25625. sockaddr_in cli_addr{};
  25626. socklen_t cli_len = sizeof(cli_addr);
  25627. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25628. if (cli == INVALID_SOCKET) { return; }
  25629. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25630. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25631. char buf[4096];
  25632. received = ::recv(cli, buf, sizeof(buf), 0);
  25633. });
  25634. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25635. // connect() has already shut the socket down by the time it returns false,
  25636. // so the peer sees EOF without waiting for the client to be destroyed.
  25637. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25638. {{"X-Bad", "a\r\nInjected: 1"}});
  25639. EXPECT_FALSE(client.connect());
  25640. t.join();
  25641. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25642. EXPECT_EQ(0, received);
  25643. }
  25644. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25645. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25646. // contains "upgrade" as a substring is a different token and must not
  25647. // start a WebSocket handshake.
  25648. auto make_request = [](const std::vector<std::string> &connection_values) {
  25649. Request req;
  25650. req.method = "GET";
  25651. req.headers.emplace("Upgrade", "websocket");
  25652. for (const auto &value : connection_values) {
  25653. req.headers.emplace("Connection", value);
  25654. }
  25655. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25656. req.headers.emplace("Sec-WebSocket-Version", "13");
  25657. return req;
  25658. };
  25659. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25660. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25661. EXPECT_TRUE(
  25662. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25663. EXPECT_TRUE(
  25664. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25665. EXPECT_TRUE(
  25666. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25667. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25668. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25669. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25670. EXPECT_FALSE(
  25671. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25672. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25673. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25674. }
  25675. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25676. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25677. // asks recipients to match each protocol-name case-insensitively, and RFC
  25678. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25679. // client naming websocket alongside another protocol, or on a second field
  25680. // line, is offering websocket; a value that merely contains "websocket" as a
  25681. // substring is a different protocol name and is not.
  25682. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25683. Request req;
  25684. req.method = "GET";
  25685. for (const auto &value : upgrade_values) {
  25686. req.headers.emplace("Upgrade", value);
  25687. }
  25688. req.headers.emplace("Connection", "Upgrade");
  25689. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25690. req.headers.emplace("Sec-WebSocket-Version", "13");
  25691. return req;
  25692. };
  25693. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25694. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25695. EXPECT_TRUE(
  25696. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25697. EXPECT_TRUE(
  25698. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25699. EXPECT_TRUE(
  25700. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25701. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25702. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25703. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25704. EXPECT_FALSE(
  25705. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25706. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25707. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25708. }
  25709. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25710. Server svr;
  25711. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25712. auto port = svr.bind_to_any_port("localhost");
  25713. std::thread t([&]() { svr.listen_after_bind(); });
  25714. auto se = detail::scope_exit([&] {
  25715. svr.stop();
  25716. t.join();
  25717. });
  25718. svr.wait_until_ready();
  25719. Headers headers = {{"Upgrade", "websocket"},
  25720. {"Connection", "notupgrade"},
  25721. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25722. {"Sec-WebSocket-Version", "13"}};
  25723. Client cli("localhost", port);
  25724. auto res = cli.Get("/ws", headers);
  25725. // The route exists only as a WebSocket route, so a request that fails the
  25726. // handshake check falls through to ordinary routing.
  25727. ASSERT_TRUE(res);
  25728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25729. }
  25730. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25731. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25732. // Connection value is the only thing left for the client to reject.
  25733. Server svr;
  25734. svr.Get("/ws", [](const Request &req, Response &res) {
  25735. res.status = StatusCode::SwitchingProtocol_101;
  25736. res.set_header("Upgrade", "websocket");
  25737. res.set_header("Connection", "notupgrade");
  25738. res.set_header("Sec-WebSocket-Accept",
  25739. detail::websocket_accept_key(
  25740. req.get_header_value("Sec-WebSocket-Key")));
  25741. });
  25742. auto port = svr.bind_to_any_port("localhost");
  25743. std::thread t([&]() { svr.listen_after_bind(); });
  25744. auto se = detail::scope_exit([&] {
  25745. svr.stop();
  25746. t.join();
  25747. });
  25748. svr.wait_until_ready();
  25749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25750. auto res = client.connect();
  25751. EXPECT_FALSE(res);
  25752. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25753. EXPECT_FALSE(client.is_open());
  25754. }
  25755. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25756. Server svr;
  25757. svr.Get("/ws", [](const Request &req, Response &res) {
  25758. res.status = StatusCode::SwitchingProtocol_101;
  25759. res.set_header("Upgrade", "websocket");
  25760. res.set_header("Connection", "Upgrade");
  25761. res.set_header("Sec-WebSocket-Accept",
  25762. detail::websocket_accept_key(
  25763. req.get_header_value("Sec-WebSocket-Key")));
  25764. res.set_header("Sec-WebSocket-Protocol", "admin");
  25765. });
  25766. auto port = svr.bind_to_any_port("localhost");
  25767. std::thread t([&]() { svr.listen_after_bind(); });
  25768. auto se = detail::scope_exit([&] {
  25769. svr.stop();
  25770. t.join();
  25771. });
  25772. svr.wait_until_ready();
  25773. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25774. // Server selects a subprotocol the client never offered
  25775. {
  25776. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25777. ws::WebSocketClient client(url, headers);
  25778. auto res = client.connect();
  25779. EXPECT_FALSE(res);
  25780. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25781. EXPECT_FALSE(client.is_open());
  25782. EXPECT_TRUE(client.subprotocol().empty());
  25783. }
  25784. // Client offered none but the server named one anyway
  25785. {
  25786. ws::WebSocketClient client(url);
  25787. auto res = client.connect();
  25788. EXPECT_FALSE(res);
  25789. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25790. EXPECT_FALSE(client.is_open());
  25791. EXPECT_TRUE(client.subprotocol().empty());
  25792. }
  25793. }
  25794. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25795. // The socket path doubles as the URL host, so it must not contain '/'.
  25796. const char *shard = getenv("GTEST_SHARD_INDEX");
  25797. const std::string sock_path =
  25798. shard ? std::string("httplib-ws-") + shard + ".sock"
  25799. : std::string("httplib-ws.sock");
  25800. std::remove(sock_path.c_str());
  25801. Server svr;
  25802. std::mutex mtx;
  25803. std::string received_host;
  25804. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25805. {
  25806. std::lock_guard<std::mutex> lock(mtx);
  25807. received_host = req.get_header_value("Host");
  25808. }
  25809. std::string msg;
  25810. while (ws.read(msg)) {
  25811. ws.send(msg);
  25812. }
  25813. });
  25814. svr.set_address_family(AF_UNIX);
  25815. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25816. auto se = detail::scope_exit([&] {
  25817. svr.stop();
  25818. t.join();
  25819. std::remove(sock_path.c_str());
  25820. });
  25821. svr.wait_until_ready();
  25822. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25823. client.set_address_family(AF_UNIX);
  25824. ASSERT_TRUE(client.connect());
  25825. ASSERT_TRUE(client.send("hello"));
  25826. std::string msg;
  25827. ASSERT_TRUE(client.read(msg));
  25828. client.close();
  25829. {
  25830. std::lock_guard<std::mutex> lock(mtx);
  25831. // There is no host:port for a Unix socket, so the same "localhost"
  25832. // placeholder the HTTP client uses is expected.
  25833. EXPECT_EQ("localhost", received_host);
  25834. }
  25835. }
  25836. // Two threads must never parse WebSocket frames from the same stream.
  25837. // close() used to read the peer's Close reply with its own frame read, so it
  25838. // raced a reader thread that was in the middle of a payload: the payload loop
  25839. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25840. // so bytes taken by close() were replaced with bytes from further along the
  25841. // stream. The message kept its length and silently changed content.
  25842. //
  25843. // The raw peer below sends a frame header plus part of the payload, waits for
  25844. // the handler to call close(), and only then sends the rest. Whichever thread
  25845. // would win the race for those bytes, the message must arrive intact, because
  25846. // close() must not touch the stream while read() owns it.
  25847. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25848. #ifndef _WIN32
  25849. signal(SIGPIPE, SIG_IGN);
  25850. #endif
  25851. const size_t payload_len = 120; // fits the 7-bit length field
  25852. const size_t prefix_len = 8;
  25853. const int attempts = 8;
  25854. std::string expected(payload_len, '\0');
  25855. for (size_t i = 0; i < payload_len; i++) {
  25856. expected[i] = static_cast<char>('a' + i % 26);
  25857. }
  25858. std::atomic<bool> peer_stalled{false};
  25859. std::atomic<bool> handler_done{false};
  25860. std::mutex received_mutex;
  25861. std::vector<std::string> received;
  25862. // Bound every wait, so a regression fails the test instead of hanging the
  25863. // suite.
  25864. auto wait_for = [](const std::atomic<bool> &flag) {
  25865. for (int i = 0; i < 500 && !flag; i++) {
  25866. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25867. }
  25868. };
  25869. Server svr;
  25870. svr.set_websocket_ping_interval(0);
  25871. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25872. std::thread reader([&]() {
  25873. std::string msg;
  25874. while (ws.read(msg)) {
  25875. std::lock_guard<std::mutex> guard(received_mutex);
  25876. received.push_back(msg);
  25877. }
  25878. });
  25879. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25880. // inside a frame when close() runs.
  25881. wait_for(peer_stalled);
  25882. ws.close();
  25883. reader.join();
  25884. handler_done = true;
  25885. });
  25886. auto port = svr.bind_to_any_port("127.0.0.1");
  25887. std::thread t([&]() { svr.listen_after_bind(); });
  25888. auto se = detail::scope_exit([&] {
  25889. svr.stop();
  25890. t.join();
  25891. });
  25892. svr.wait_until_ready();
  25893. auto send_bytes = [](socket_t s, const std::string &data) {
  25894. #ifdef _WIN32
  25895. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25896. #else
  25897. auto n = ::send(s, data.data(), data.size(), 0);
  25898. #endif
  25899. return n == static_cast<decltype(n)>(data.size());
  25900. };
  25901. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25902. // Every length used here fits the 7-bit length field.
  25903. auto masked_header = [](uint8_t first_byte, size_t len) {
  25904. std::string h;
  25905. h += static_cast<char>(first_byte);
  25906. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25907. h.append(4, '\0'); // mask key
  25908. return h;
  25909. };
  25910. for (int attempt = 0; attempt < attempts; attempt++) {
  25911. peer_stalled = false;
  25912. handler_done = false;
  25913. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25914. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25915. auto se_sock = detail::scope_exit([&] {
  25916. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25917. });
  25918. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25919. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25920. sockaddr_in addr{};
  25921. addr.sin_family = AF_INET;
  25922. addr.sin_port = htons(static_cast<uint16_t>(port));
  25923. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25924. ASSERT_EQ(
  25925. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25926. << "attempt " << attempt;
  25927. ASSERT_TRUE(send_bytes(sock,
  25928. "GET /ws HTTP/1.1\r\n"
  25929. "Host: 127.0.0.1\r\n"
  25930. "Upgrade: websocket\r\n"
  25931. "Connection: Upgrade\r\n"
  25932. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25933. "Sec-WebSocket-Version: 13\r\n"
  25934. "\r\n"))
  25935. << "attempt " << attempt;
  25936. std::string response;
  25937. while (response.find("\r\n\r\n") == std::string::npos) {
  25938. char buf[512];
  25939. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25940. if (n <= 0) { break; }
  25941. response.append(buf, static_cast<size_t>(n));
  25942. }
  25943. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25944. << "attempt " << attempt;
  25945. // Send the header of a Binary message but only the first prefix_len bytes
  25946. // of its payload, leaving the reader thread stalled inside the payload.
  25947. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25948. expected.substr(0, prefix_len)))
  25949. << "attempt " << attempt;
  25950. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25951. peer_stalled = true;
  25952. // Let close() send its Close frame and park in its own read before the
  25953. // rest of the payload arrives, so both threads are waiting for it.
  25954. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25955. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25956. close_frame += static_cast<char>(0x03); // status 1000
  25957. close_frame += static_cast<char>(0xE8);
  25958. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25959. << "attempt " << attempt;
  25960. // Closing the peer releases the reader thread even on the buggy path,
  25961. // where it waits for bytes another thread already consumed.
  25962. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25963. detail::close_socket(sock);
  25964. sock = INVALID_SOCKET;
  25965. wait_for(handler_done);
  25966. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25967. }
  25968. std::lock_guard<std::mutex> guard(received_mutex);
  25969. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25970. << "a message in flight when close() ran was dropped";
  25971. for (size_t i = 0; i < received.size(); i++) {
  25972. EXPECT_EQ(expected, received[i]) << "message " << i;
  25973. }
  25974. }
  25975. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25976. // returning the socket, or INVALID_SOCKET.
  25977. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25978. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25979. if (sock == INVALID_SOCKET) { return sock; }
  25980. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25981. sockaddr_in addr{};
  25982. addr.sin_family = AF_INET;
  25983. addr.sin_port = htons(static_cast<uint16_t>(port));
  25984. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25985. std::string req = "GET " + path +
  25986. " HTTP/1.1\r\n"
  25987. "Host: 127.0.0.1\r\n"
  25988. "Upgrade: websocket\r\n"
  25989. "Connection: Upgrade\r\n"
  25990. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25991. "Sec-WebSocket-Version: 13\r\n"
  25992. "\r\n";
  25993. std::string res;
  25994. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25995. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25996. static_cast<ssize_t>(req.size())) {
  25997. char c;
  25998. while (res.find("\r\n\r\n") == std::string::npos &&
  25999. ::recv(sock, &c, 1, 0) == 1) {
  26000. res += c;
  26001. }
  26002. }
  26003. if (res.find(" 101 ") == std::string::npos) {
  26004. detail::close_socket(sock);
  26005. return INVALID_SOCKET;
  26006. }
  26007. return sock;
  26008. }
  26009. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26010. // The payload must fit the 7-bit length field.
  26011. static std::string masked_frame(uint8_t first_byte,
  26012. const std::string &payload) {
  26013. std::string f;
  26014. f += static_cast<char>(first_byte);
  26015. f += static_cast<char>(0x80 | payload.size());
  26016. f.append(4, '\0');
  26017. return f + payload;
  26018. }
  26019. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26020. std::atomic<bool> done{false};
  26021. std::string received;
  26022. Server svr;
  26023. svr.set_websocket_ping_interval(0);
  26024. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26025. std::string msg;
  26026. if (ws.read(msg) == ws::Binary) { received = msg; }
  26027. done = true;
  26028. });
  26029. auto port = svr.bind_to_any_port("127.0.0.1");
  26030. std::thread t([&]() { svr.listen_after_bind(); });
  26031. auto se = detail::scope_exit([&] {
  26032. svr.stop();
  26033. t.join();
  26034. });
  26035. svr.wait_until_ready();
  26036. auto sock = connect_raw_websocket(port, "/ws");
  26037. ASSERT_NE(INVALID_SOCKET, sock);
  26038. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26039. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26040. masked_frame(0x89, "p") + // FIN + Ping
  26041. masked_frame(0x80, "lo"); // FIN + Continuation
  26042. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26043. for (int i = 0; i < 500 && !done; i++) {
  26044. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26045. }
  26046. ASSERT_TRUE(done);
  26047. EXPECT_EQ("Hello", received);
  26048. // The Ping between the fragments is answered with a Pong.
  26049. char pong[3];
  26050. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26051. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26052. }
  26053. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26054. #ifndef _WIN32
  26055. signal(SIGPIPE, SIG_IGN);
  26056. #endif
  26057. std::atomic<bool> read_ended{false};
  26058. std::atomic<bool> sending{true};
  26059. Server svr;
  26060. svr.set_websocket_ping_interval(0);
  26061. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26062. std::thread reader([&]() {
  26063. std::string msg;
  26064. while (ws.read(msg)) {}
  26065. read_ended = true;
  26066. });
  26067. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26068. ws.close();
  26069. reader.join();
  26070. });
  26071. auto port = svr.bind_to_any_port("127.0.0.1");
  26072. std::thread t([&]() { svr.listen_after_bind(); });
  26073. auto se = detail::scope_exit([&] {
  26074. svr.stop();
  26075. t.join();
  26076. });
  26077. svr.wait_until_ready();
  26078. auto sock = connect_raw_websocket(port, "/ws");
  26079. ASSERT_NE(INVALID_SOCKET, sock);
  26080. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26081. // A Text message whose empty continuation frames never end
  26082. std::thread sender([&]() {
  26083. auto data = masked_frame(0x01, "");
  26084. while (sending) {
  26085. data += masked_frame(0x00, "");
  26086. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26087. return;
  26088. }
  26089. data.clear();
  26090. }
  26091. });
  26092. for (int i = 0; i < 300 && !read_ended; i++) {
  26093. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26094. }
  26095. sending = false;
  26096. sender.join();
  26097. EXPECT_TRUE(read_ended);
  26098. }
  26099. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26100. Server svr;
  26101. svr.set_websocket_ping_interval(-1);
  26102. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26103. std::string msg;
  26104. while (ws.read(msg)) {}
  26105. });
  26106. auto port = svr.bind_to_any_port("127.0.0.1");
  26107. std::thread t([&]() { svr.listen_after_bind(); });
  26108. auto se = detail::scope_exit([&] {
  26109. svr.stop();
  26110. t.join();
  26111. });
  26112. svr.wait_until_ready();
  26113. auto sock = connect_raw_websocket(port, "/ws");
  26114. ASSERT_NE(INVALID_SOCKET, sock);
  26115. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26116. // Nothing comes while the client stays quiet.
  26117. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26118. char c;
  26119. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26120. }
  26121. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26122. // and that has to end a read() already waiting on the peer, on every platform.
  26123. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26124. // The peer sends no pings, and its handler never calls read(), which is
  26125. // where pongs are written.
  26126. std::mutex mutex;
  26127. std::condition_variable cv;
  26128. auto release = false;
  26129. svr.set_websocket_ping_interval(0);
  26130. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26131. std::unique_lock<std::mutex> lock(mutex);
  26132. cv.wait(lock, [&] { return release; });
  26133. });
  26134. auto port = svr.bind_to_any_port(HOST);
  26135. std::thread t([&]() { svr.listen_after_bind(); });
  26136. auto se = detail::scope_exit([&] {
  26137. {
  26138. std::lock_guard<std::mutex> lock(mutex);
  26139. release = true;
  26140. }
  26141. cv.notify_all();
  26142. svr.stop();
  26143. t.join();
  26144. });
  26145. svr.wait_until_ready();
  26146. ws::WebSocketClient client(std::string(scheme) +
  26147. "://localhost:" + std::to_string(port) + "/ws");
  26148. #ifdef CPPHTTPLIB_SSL_ENABLED
  26149. client.enable_server_certificate_verification(false);
  26150. #endif
  26151. // A ping a second, given up on after two go unanswered: about 3s
  26152. client.set_websocket_ping_interval(1);
  26153. client.set_websocket_max_missed_pongs(2);
  26154. // Well past that, so that a read the timeout ends instead stands out
  26155. client.set_read_timeout(10);
  26156. ASSERT_TRUE(client.connect());
  26157. auto start = std::chrono::steady_clock::now();
  26158. std::string msg;
  26159. EXPECT_EQ(ws::Fail, client.read(msg));
  26160. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26161. std::chrono::steady_clock::now() - start)
  26162. .count(),
  26163. 6000);
  26164. EXPECT_FALSE(client.is_open());
  26165. }
  26166. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26167. Server svr;
  26168. check_pong_timeout_ends_read(svr, "ws");
  26169. }
  26170. #ifdef CPPHTTPLIB_SSL_ENABLED
  26171. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26173. ASSERT_TRUE(svr.is_valid());
  26174. check_pong_timeout_ends_read(svr, "wss");
  26175. }
  26176. #endif
  26177. // listen() returns only after every handler has, so Server::stop() has to end
  26178. // a WebSocket handler's read() waiting on a client that stays connected and
  26179. // quiet, whether or not the handler bounded its reads, and the client's
  26180. // connection ends with it.
  26181. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26182. bool bounded) {
  26183. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26184. if (bounded) { ws.set_read_timeout(0, 50000); }
  26185. std::string msg;
  26186. while (ws.read(msg) != ws::Fail) {}
  26187. });
  26188. auto port = svr.bind_to_any_port(HOST);
  26189. std::thread t([&]() { svr.listen_after_bind(); });
  26190. auto se = detail::scope_exit([&] {
  26191. if (t.joinable()) {
  26192. svr.stop();
  26193. t.join();
  26194. }
  26195. });
  26196. svr.wait_until_ready();
  26197. ws::WebSocketClient client(std::string(scheme) +
  26198. "://localhost:" + std::to_string(port) + "/ws");
  26199. #ifdef CPPHTTPLIB_SSL_ENABLED
  26200. client.enable_server_certificate_verification(false);
  26201. #endif
  26202. client.set_read_timeout(2);
  26203. ASSERT_TRUE(client.connect());
  26204. auto stopped = std::async(std::launch::async, [&] {
  26205. svr.stop();
  26206. t.join();
  26207. });
  26208. std::string msg;
  26209. EXPECT_EQ(ws::Fail, client.read(msg));
  26210. EXPECT_FALSE(client.is_open());
  26211. auto in_time =
  26212. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26213. // A handler the stop did not reach ends when the client leaves
  26214. if (!in_time) { client.close(); }
  26215. stopped.wait();
  26216. EXPECT_TRUE(in_time);
  26217. }
  26218. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26219. Server svr;
  26220. check_stop_ends_websocket_read(svr, "ws", false);
  26221. }
  26222. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26223. Server svr;
  26224. check_stop_ends_websocket_read(svr, "ws", true);
  26225. }
  26226. #ifdef CPPHTTPLIB_SSL_ENABLED
  26227. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26229. ASSERT_TRUE(svr.is_valid());
  26230. check_stop_ends_websocket_read(svr, "wss", false);
  26231. }
  26232. #endif
  26233. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26234. // dropped connection, whether the handler waits for a message or for the rest
  26235. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26236. // time out inside the message as well, and the stop ends them too.
  26237. static void check_stop_closes_with_going_away(const std::string &sent,
  26238. bool bounded = false) {
  26239. Server svr;
  26240. svr.set_websocket_ping_interval(0);
  26241. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26242. if (bounded) { ws.set_read_timeout(0, 10000); }
  26243. std::string msg;
  26244. while (ws.read(msg) != ws::Fail) {}
  26245. });
  26246. auto port = svr.bind_to_any_port("127.0.0.1");
  26247. std::thread t([&]() { svr.listen_after_bind(); });
  26248. auto se = detail::scope_exit([&] {
  26249. svr.stop();
  26250. t.join();
  26251. });
  26252. svr.wait_until_ready();
  26253. // Closed before the join above, which a handler the stop did not reach
  26254. // would otherwise hold up.
  26255. auto sock = connect_raw_websocket(port, "/ws");
  26256. ASSERT_NE(INVALID_SOCKET, sock);
  26257. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26258. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26259. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26260. // Let the handler take what was sent and wait for more
  26261. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26262. svr.stop();
  26263. // FIN + Close, its length, then the code: unmasked, from a server
  26264. std::string head;
  26265. char c;
  26266. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26267. head += c;
  26268. }
  26269. const std::string reason = "server stopping";
  26270. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26271. "\x03\xe9",
  26272. head);
  26273. }
  26274. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26275. check_stop_closes_with_going_away("");
  26276. }
  26277. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26278. // A Text frame without FIN: the first fragment of a message
  26279. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26280. }
  26281. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26282. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26283. /*bounded=*/true);
  26284. }
  26285. // A handler that bounds its reads gets control back within its timeout even
  26286. // while a message arrives in pieces, and the message whole once the last has
  26287. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26288. // sent a while after the one before, much longer than the handler's timeout.
  26289. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26290. const std::string &expected) {
  26291. std::atomic<bool> done{false};
  26292. std::string received;
  26293. std::chrono::steady_clock::duration longest{};
  26294. Server svr;
  26295. svr.set_websocket_ping_interval(0);
  26296. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26297. ws.set_read_timeout(0, 10000);
  26298. std::string msg;
  26299. ws::ReadResult r;
  26300. do {
  26301. auto began = std::chrono::steady_clock::now();
  26302. r = ws.read(msg);
  26303. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26304. } while (r == ws::Timeout);
  26305. if (r == ws::Text) { received = msg; }
  26306. done = true;
  26307. });
  26308. auto port = svr.bind_to_any_port("127.0.0.1");
  26309. std::thread t([&]() { svr.listen_after_bind(); });
  26310. auto se = detail::scope_exit([&] {
  26311. svr.stop();
  26312. t.join();
  26313. });
  26314. svr.wait_until_ready();
  26315. auto sock = connect_raw_websocket(port, "/ws");
  26316. ASSERT_NE(INVALID_SOCKET, sock);
  26317. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26318. for (const auto &piece : pieces) {
  26319. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26320. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26321. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26322. }
  26323. for (int i = 0; i < 500 && !done; i++) {
  26324. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26325. }
  26326. ASSERT_TRUE(done);
  26327. EXPECT_EQ(expected, received);
  26328. // Far under the 200 ms between the pieces, however loaded the machine
  26329. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26330. }
  26331. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26332. // The header's first byte, then its second with half the mask key, then
  26333. // the rest: what a frame written in several writes may look like when
  26334. // Nagle's algorithm holds the later ones back for an ACK.
  26335. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26336. check_bounded_read_resumes(
  26337. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26338. }
  26339. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26340. check_bounded_read_resumes(
  26341. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26342. }
  26343. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26344. Server svr;
  26345. svr.set_websocket_ping_interval(0);
  26346. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26347. std::string msg;
  26348. while (ws.read(msg)) {}
  26349. });
  26350. auto port = svr.bind_to_any_port("127.0.0.1");
  26351. std::thread t([&]() { svr.listen_after_bind(); });
  26352. auto se = detail::scope_exit([&] {
  26353. svr.stop();
  26354. t.join();
  26355. });
  26356. svr.wait_until_ready();
  26357. // Each Close payload and the reply it should get: an echo when valid, 1002
  26358. // otherwise.
  26359. std::vector<std::pair<std::string, std::string>> cases = {
  26360. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26361. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26362. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26363. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26364. };
  26365. // Also between the fragments of a message.
  26366. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26367. for (const auto &c : cases) {
  26368. auto sock = connect_raw_websocket(port, "/ws");
  26369. ASSERT_NE(INVALID_SOCKET, sock);
  26370. auto frames = prefix + masked_frame(0x88, c.first);
  26371. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26372. std::string reply;
  26373. char buf[256];
  26374. while (reply.size() < 2 + c.second.size()) {
  26375. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26376. if (n <= 0) { break; }
  26377. reply.append(buf, static_cast<size_t>(n));
  26378. }
  26379. detail::close_socket(sock);
  26380. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26381. c.second,
  26382. reply);
  26383. }
  26384. }
  26385. }
  26386. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26387. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26388. protected:
  26389. void SetUp() override {
  26390. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26391. SERVER_PRIVATE_KEY_FILE);
  26392. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26393. std::string msg;
  26394. ws::ReadResult ret;
  26395. while ((ret = ws.read(msg))) {
  26396. if (ret == ws::Binary) {
  26397. ws.send(msg.data(), msg.size());
  26398. } else {
  26399. ws.send(msg);
  26400. }
  26401. }
  26402. });
  26403. port_ = server_->bind_to_any_port(HOST);
  26404. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26405. server_->wait_until_ready();
  26406. }
  26407. void TearDown() override {
  26408. server_->stop();
  26409. if (server_thread_.joinable()) { server_thread_.join(); }
  26410. }
  26411. std::unique_ptr<SSLServer> server_;
  26412. std::thread server_thread_;
  26413. int port_ = 0;
  26414. };
  26415. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26416. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26417. {
  26418. ws::WebSocketClient client(url);
  26419. client.enable_server_certificate_verification(false);
  26420. auto calls = 0;
  26421. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26422. calls++;
  26423. return false;
  26424. });
  26425. EXPECT_FALSE(client.connect());
  26426. EXPECT_GT(calls, 0);
  26427. }
  26428. {
  26429. ws::WebSocketClient client(url);
  26430. client.enable_server_certificate_verification(false);
  26431. client.set_session_verifier([](tls::session_t) {
  26432. return SSLVerifierResponse::CertificateRejected;
  26433. });
  26434. EXPECT_FALSE(client.connect());
  26435. }
  26436. {
  26437. ws::WebSocketClient client(url);
  26438. client.enable_server_certificate_verification(false);
  26439. client.set_session_verifier([](tls::session_t) {
  26440. return SSLVerifierResponse::CertificateAccepted;
  26441. });
  26442. EXPECT_TRUE(client.connect());
  26443. }
  26444. }
  26445. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26446. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26447. "/ws-echo");
  26448. client.enable_server_certificate_verification(false);
  26449. ASSERT_TRUE(client.connect());
  26450. ASSERT_TRUE(client.is_open());
  26451. ASSERT_TRUE(client.send("Hello WSS"));
  26452. std::string msg;
  26453. EXPECT_EQ(ws::Text, client.read(msg));
  26454. EXPECT_EQ("Hello WSS", msg);
  26455. client.close();
  26456. }
  26457. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26458. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26459. "/ws-echo");
  26460. client.enable_server_certificate_verification(false);
  26461. EXPECT_TRUE(client.connect());
  26462. }
  26463. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26464. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26465. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26466. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26467. // client (without calling close() first) is the only path that runs
  26468. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26469. // bug exactly.
  26470. //
  26471. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26472. // when linked against an instrumented libssl; run under Valgrind to catch it
  26473. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26474. // suite (the freed session otherwise stalls on the close handshake) — this test
  26475. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26476. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26477. {
  26478. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26479. "/ws-echo");
  26480. client.enable_server_certificate_verification(false);
  26481. client.set_read_timeout(2, 0);
  26482. client.set_write_timeout(2, 0);
  26483. ASSERT_TRUE(client.connect());
  26484. ASSERT_TRUE(client.is_open());
  26485. ASSERT_TRUE(client.send("still open"));
  26486. // Intentionally do NOT call client.close(): leaving scope runs
  26487. // shutdown_and_close() with the WebSocket still open, which must send the
  26488. // close frame while the TLS session is still alive.
  26489. }
  26490. }
  26491. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26492. // shutdown_and_close() at the start of connect(), reproducing the same
  26493. // use-after-free within the test body rather than at scope exit. The second
  26494. // connect must succeed and echo, proving the close handshake ran over a live
  26495. // session. See the note above about memory-tool requirements.
  26496. TEST_F(WebSocketSSLIntegrationTest,
  26497. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26498. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26499. "/ws-echo");
  26500. client.enable_server_certificate_verification(false);
  26501. client.set_read_timeout(2, 0);
  26502. client.set_write_timeout(2, 0);
  26503. ASSERT_TRUE(client.connect());
  26504. ASSERT_TRUE(client.is_open());
  26505. ASSERT_TRUE(client.send("still open"));
  26506. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26507. // the still-open connection, which must not touch a freed TLS session.
  26508. ASSERT_TRUE(client.connect());
  26509. ASSERT_TRUE(client.is_open());
  26510. ASSERT_TRUE(client.send("after reconnect"));
  26511. std::string msg;
  26512. EXPECT_EQ(ws::Text, client.read(msg));
  26513. EXPECT_EQ("after reconnect", msg);
  26514. client.close();
  26515. }
  26516. #endif
  26517. #ifdef CPPHTTPLIB_SSL_ENABLED
  26518. class WebSocketSSLCATest : public ::testing::Test {
  26519. protected:
  26520. void SetUp() override {
  26521. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26522. SERVER_PRIVATE_KEY_FILE);
  26523. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26524. std::string msg;
  26525. while (ws.read(msg)) {
  26526. ws.send(msg);
  26527. }
  26528. });
  26529. port_ = server_->bind_to_any_port("127.0.0.1");
  26530. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26531. server_->wait_until_ready();
  26532. }
  26533. void TearDown() override {
  26534. server_->stop();
  26535. if (server_thread_.joinable()) { server_thread_.join(); }
  26536. }
  26537. std::string url() const {
  26538. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26539. }
  26540. std::unique_ptr<SSLServer> server_;
  26541. std::thread server_thread_;
  26542. int port_ = 0;
  26543. };
  26544. // A custom CA loaded as PEM verifies the server with full certificate
  26545. // verification enabled
  26546. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26547. ws::WebSocketClient client(url());
  26548. std::string cert;
  26549. read_file(SERVER_CERT2_FILE, cert);
  26550. client.load_ca_cert_store(cert.c_str(), cert.size());
  26551. ASSERT_TRUE(client.connect());
  26552. ASSERT_TRUE(client.send("hello"));
  26553. std::string msg;
  26554. EXPECT_EQ(ws::Text, client.read(msg));
  26555. EXPECT_EQ("hello", msg);
  26556. client.close();
  26557. }
  26558. // A custom CA that does not cover the server must fail verification (the
  26559. // custom CA is exclusive; system certs are not loaded alongside it)
  26560. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26561. ws::WebSocketClient client(url());
  26562. std::string cert;
  26563. read_file(CLIENT_CA_CERT_FILE, cert);
  26564. client.load_ca_cert_store(cert.c_str(), cert.size());
  26565. auto res = client.connect();
  26566. ASSERT_FALSE(res);
  26567. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26568. EXPECT_EQ(-1, res.status());
  26569. EXPECT_NE(0u, res.ssl_backend_error());
  26570. }
  26571. // The same CA as a file path rather than PEM in memory
  26572. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26573. ws::WebSocketClient client(url());
  26574. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26575. ASSERT_TRUE(client.connect());
  26576. ASSERT_TRUE(client.send("hello"));
  26577. std::string msg;
  26578. EXPECT_EQ(ws::Text, client.read(msg));
  26579. EXPECT_EQ("hello", msg);
  26580. client.close();
  26581. }
  26582. // ...and a CA file that does not cover the server still fails, so it is the
  26583. // path above that decides the outcome
  26584. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26585. ws::WebSocketClient client(url());
  26586. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26587. ASSERT_FALSE(client.connect());
  26588. }
  26589. // Regression test: reconnecting with a native custom CA store used to reuse
  26590. // a store handle the previous TLS context had already freed (use-after-free
  26591. // under the OpenSSL backend). The context now lives as long as the client.
  26592. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26593. ws::WebSocketClient client(url());
  26594. std::string cert;
  26595. read_file(SERVER_CERT2_FILE, cert);
  26596. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26597. ASSERT_TRUE(client.connect());
  26598. client.close();
  26599. ASSERT_TRUE(client.connect());
  26600. ASSERT_TRUE(client.send("again"));
  26601. std::string msg;
  26602. EXPECT_EQ(ws::Text, client.read(msg));
  26603. EXPECT_EQ("again", msg);
  26604. client.close();
  26605. }
  26606. // Regression test: a certificate with a trusted chain but no identity match
  26607. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26608. // verification entirely for IP hosts, so this connection succeeded there.
  26609. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26610. // chain verification while the identity check must still fail.
  26611. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26613. ASSERT_TRUE(svr.is_valid());
  26614. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26615. std::string msg;
  26616. while (ws.read(msg)) {
  26617. ws.send(msg);
  26618. }
  26619. });
  26620. auto port = svr.bind_to_any_port("127.0.0.1");
  26621. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26622. auto se = detail::scope_exit([&] {
  26623. svr.stop();
  26624. t.join();
  26625. });
  26626. svr.wait_until_ready();
  26627. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26628. "/echo");
  26629. std::string cert;
  26630. read_file(SERVER_CERT_FILE, cert);
  26631. client.load_ca_cert_store(cert.c_str(), cert.size());
  26632. ASSERT_FALSE(client.connect());
  26633. }
  26634. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26635. // SNI, so nothing binds the host name to the TLS session. These bind the
  26636. // server to "localhost" instead, the only shape that exercises the SNI and
  26637. // hostname-verification path with certificate verification left enabled.
  26638. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26639. protected:
  26640. void Start(const char *cert_file) {
  26641. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26642. SERVER_PRIVATE_KEY_FILE);
  26643. ASSERT_TRUE(server_->is_valid());
  26644. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26645. std::string msg;
  26646. while (ws.read(msg)) {
  26647. ws.send(msg);
  26648. }
  26649. });
  26650. port_ = server_->bind_to_any_port("localhost");
  26651. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26652. server_->wait_until_ready();
  26653. }
  26654. void TearDown() override {
  26655. if (server_) { server_->stop(); }
  26656. if (server_thread_.joinable()) { server_thread_.join(); }
  26657. }
  26658. std::string url() const {
  26659. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26660. }
  26661. std::unique_ptr<SSLServer> server_;
  26662. std::thread server_thread_;
  26663. int port_ = 0;
  26664. };
  26665. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26666. // out and the connection is usable
  26667. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26668. Start(SERVER_CERT2_FILE);
  26669. ws::WebSocketClient client(url());
  26670. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26671. ASSERT_TRUE(client.connect());
  26672. ASSERT_TRUE(client.send("hello"));
  26673. std::string msg;
  26674. EXPECT_EQ(ws::Text, client.read(msg));
  26675. EXPECT_EQ("hello", msg);
  26676. client.close();
  26677. }
  26678. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26679. // while the identity check must still reject "localhost"
  26680. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26681. Start(SERVER_CERT_FILE);
  26682. ws::WebSocketClient client(url());
  26683. client.set_ca_cert_path(SERVER_CERT_FILE);
  26684. auto res = client.connect();
  26685. ASSERT_FALSE(res);
  26686. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26687. EXPECT_EQ(-1, res.status());
  26688. }
  26689. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26690. // disabled: the chain is still checked, only the identity check is skipped
  26691. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26692. Start(SERVER_CERT_FILE);
  26693. ws::WebSocketClient client(url());
  26694. client.set_ca_cert_path(SERVER_CERT_FILE);
  26695. client.enable_server_hostname_verification(false);
  26696. ASSERT_TRUE(client.connect());
  26697. ASSERT_TRUE(client.send("hello"));
  26698. std::string msg;
  26699. EXPECT_EQ(ws::Text, client.read(msg));
  26700. EXPECT_EQ("hello", msg);
  26701. client.close();
  26702. }
  26703. // A CA that did not sign the server certificate fails the chain, even though
  26704. // the name would match
  26705. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26706. Start(SERVER_CERT2_FILE);
  26707. ws::WebSocketClient client(url());
  26708. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26709. ASSERT_FALSE(client.connect());
  26710. }
  26711. // With verification disabled, neither the chain nor the name is checked
  26712. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26713. Start(SERVER_CERT_FILE);
  26714. ws::WebSocketClient client(url());
  26715. client.enable_server_certificate_verification(false);
  26716. ASSERT_TRUE(client.connect());
  26717. ASSERT_TRUE(client.send("hello"));
  26718. std::string msg;
  26719. EXPECT_EQ(ws::Text, client.read(msg));
  26720. EXPECT_EQ("hello", msg);
  26721. client.close();
  26722. }
  26723. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26724. protected:
  26725. void SetUp() override {
  26726. server_ = httplib::detail::make_unique<SSLServer>(
  26727. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26728. ASSERT_TRUE(server_->is_valid());
  26729. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26730. std::string msg;
  26731. while (ws.read(msg)) {
  26732. ws.send(msg);
  26733. }
  26734. });
  26735. port_ = server_->bind_to_any_port("localhost");
  26736. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26737. server_->wait_until_ready();
  26738. }
  26739. void TearDown() override {
  26740. server_->stop();
  26741. if (server_thread_.joinable()) { server_thread_.join(); }
  26742. }
  26743. std::string url() const {
  26744. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26745. }
  26746. void ConnectWithClientCert(const std::string &client_cert_file,
  26747. const std::string &client_private_key_file,
  26748. const char *private_key_password) {
  26749. std::string cert_pem, key_pem;
  26750. read_file(client_cert_file, cert_pem);
  26751. read_file(client_private_key_file, key_pem);
  26752. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26753. key_pem.c_str(), key_pem.size(),
  26754. private_key_password};
  26755. ConnectWithPem(pem);
  26756. }
  26757. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26758. ws::WebSocketClient client(url(), pem);
  26759. ASSERT_TRUE(client.is_valid());
  26760. client.enable_server_certificate_verification(false);
  26761. ASSERT_TRUE(client.connect());
  26762. ASSERT_TRUE(client.send("hello"));
  26763. std::string msg;
  26764. EXPECT_EQ(ws::Text, client.read(msg));
  26765. EXPECT_EQ("hello", msg);
  26766. client.close();
  26767. }
  26768. std::unique_ptr<SSLServer> server_;
  26769. std::thread server_thread_;
  26770. int port_ = 0;
  26771. };
  26772. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26773. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26774. }
  26775. // Control for the tests above: the fixture's server really does require a
  26776. // client certificate, so it is the PEM the constructor installed that decides
  26777. // the outcome.
  26778. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26779. ws::WebSocketClient client(url());
  26780. ASSERT_TRUE(client.is_valid());
  26781. client.enable_server_certificate_verification(false);
  26782. EXPECT_FALSE(client.connect());
  26783. }
  26784. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26785. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26786. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26787. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26788. }
  26789. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26790. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26791. std::string cert_pem, key_pem;
  26792. read_file(CLIENT_CERT_FILE, cert_pem);
  26793. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26794. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26795. std::vector<char> key(key_pem.begin(), key_pem.end());
  26796. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26797. key.size(), nullptr};
  26798. ConnectWithPem(pem);
  26799. }
  26800. #endif
  26801. #if !defined(_WIN32)
  26802. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26803. auto secret_dir = std::string("./symlink_test_secret");
  26804. auto served_dir = std::string("./symlink_test_served");
  26805. auto secret_file = secret_dir + "/secret.txt";
  26806. auto symlink_path = served_dir + "/escape";
  26807. // Setup: create directories and files
  26808. mkdir(secret_dir.c_str(), 0755);
  26809. mkdir(served_dir.c_str(), 0755);
  26810. {
  26811. std::ofstream ofs(secret_file);
  26812. ofs << "SECRET_DATA";
  26813. }
  26814. // Create symlink using absolute path so it resolves correctly
  26815. #ifdef PATH_MAX
  26816. char abs_secret[PATH_MAX];
  26817. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26818. #else
  26819. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26820. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26821. ASSERT_NE(nullptr, abs_secret);
  26822. #endif
  26823. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26824. auto se = detail::scope_exit([&] {
  26825. unlink(symlink_path.c_str());
  26826. unlink(secret_file.c_str());
  26827. rmdir(served_dir.c_str());
  26828. rmdir(secret_dir.c_str());
  26829. });
  26830. Server svr;
  26831. svr.set_mount_point("/", served_dir);
  26832. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26833. auto se2 = detail::scope_exit([&] {
  26834. svr.stop();
  26835. listen_thread.join();
  26836. });
  26837. svr.wait_until_ready();
  26838. Client cli("localhost", PORT);
  26839. // Symlink pointing outside base dir should be blocked
  26840. auto res = cli.Get("/escape/secret.txt");
  26841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26842. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26843. }
  26844. #else
  26845. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26846. auto secret_dir = std::string("junction_test_secret");
  26847. auto served_dir = std::string("junction_test_served");
  26848. auto secret_file = secret_dir + "\\secret.txt";
  26849. auto junction_path = served_dir + "\\escape";
  26850. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26851. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26852. {
  26853. std::ofstream ofs(secret_file);
  26854. ofs << "SECRET_DATA";
  26855. }
  26856. // A junction needs no privilege to create, unlike a symlink
  26857. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26858. ASSERT_EQ(0, std::system(cmd.c_str()));
  26859. auto se = detail::scope_exit([&] {
  26860. ::RemoveDirectoryA(junction_path.c_str());
  26861. std::remove(secret_file.c_str());
  26862. ::RemoveDirectoryA(served_dir.c_str());
  26863. ::RemoveDirectoryA(secret_dir.c_str());
  26864. });
  26865. Server svr;
  26866. svr.set_mount_point("/", served_dir);
  26867. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26868. auto se2 = detail::scope_exit([&] {
  26869. svr.stop();
  26870. listen_thread.join();
  26871. });
  26872. svr.wait_until_ready();
  26873. Client cli("localhost", PORT);
  26874. // Junction pointing outside base dir should be blocked
  26875. auto res = cli.Get("/escape/secret.txt");
  26876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26877. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26878. }
  26879. #endif
  26880. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26881. // "GET /smuggled" request), reads the first response, and only then sends the
  26882. // embedded request as the body. Returns how many times /smuggled ran.
  26883. //
  26884. // The body is sent AFTER receiving the first response (as in the original
  26885. // PoC) so that the stream_line_reader cannot buffer it together with the
  26886. // headers of the first request.
  26887. static int count_smuggled_requests(const std::string &outer_head,
  26888. std::string &first_response) {
  26889. Server svr;
  26890. svr.set_mount_point("/", "./www");
  26891. std::atomic<int> smuggled_count(0);
  26892. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26893. smuggled_count++;
  26894. res.set_content("oops", "text/plain");
  26895. });
  26896. svr.Post("/post", [&](const Request &req, Response &res) {
  26897. res.set_content(req.body, "text/plain");
  26898. });
  26899. auto port = svr.bind_to_any_port("localhost");
  26900. thread t = thread([&] { svr.listen_after_bind(); });
  26901. auto se = detail::scope_exit([&] {
  26902. svr.stop();
  26903. t.join();
  26904. });
  26905. svr.wait_until_ready();
  26906. auto error = Error::Success;
  26907. auto sock = detail::create_client_socket(
  26908. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26909. /*connection_timeout_sec=*/2, 0,
  26910. /*read_timeout_sec=*/2, 0,
  26911. /*write_timeout_sec=*/2, 0, std::string(), error);
  26912. EXPECT_NE(INVALID_SOCKET, sock);
  26913. if (sock == INVALID_SOCKET) { return -1; }
  26914. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26915. // The "smuggled" request will be sent as the body of the outer request
  26916. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26917. "Host: localhost\r\n"
  26918. "Connection: close\r\n"
  26919. "\r\n";
  26920. auto head = outer_head;
  26921. auto len = std::to_string(smuggled.size());
  26922. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26923. pos = head.find("{len}", pos + len.size())) {
  26924. head.replace(pos, 5, len);
  26925. }
  26926. // Step 1: Send only the outer request headers (no body yet)
  26927. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26928. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26929. // Step 2: Read the first response
  26930. char buf[4096];
  26931. for (;;) {
  26932. auto n = recv(sock, buf, sizeof(buf), 0);
  26933. if (n <= 0) break;
  26934. first_response.append(buf, static_cast<size_t>(n));
  26935. // Stop once we have a complete response (headers + body)
  26936. auto hdr_end = first_response.find("\r\n\r\n");
  26937. if (hdr_end != std::string::npos) {
  26938. // Check for Content-Length to know when the body is complete
  26939. auto cl_pos = first_response.find("Content-Length:");
  26940. if (cl_pos != std::string::npos) {
  26941. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26942. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26943. auto cl = std::stoul(
  26944. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26945. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26946. } else {
  26947. break; // No Content-Length, assume headers-only response
  26948. }
  26949. }
  26950. }
  26951. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26952. // vulnerable server the keep-alive loop reads this as a second request. The
  26953. // server may already have closed the connection, so the result is ignored.
  26954. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26955. // Half-close so that a server which drained the body sees EOF and closes,
  26956. // instead of the read below waiting for the read timeout.
  26957. #ifdef _WIN32
  26958. ::shutdown(sock, SD_SEND);
  26959. #else
  26960. ::shutdown(sock, SHUT_WR);
  26961. #endif
  26962. // Step 4: Read until the server closes the connection
  26963. for (;;) {
  26964. auto n = recv(sock, buf, sizeof(buf), 0);
  26965. if (n <= 0) break;
  26966. }
  26967. return smuggled_count.load();
  26968. }
  26969. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26970. // A GET request with Content-Length to a static file handler must have its
  26971. // body drained before the keep-alive connection is reused. Otherwise the
  26972. // unread body bytes are interpreted as the next HTTP request.
  26973. std::string first_response;
  26974. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26975. "Host: localhost\r\n"
  26976. "Content-Length: {len}\r\n"
  26977. "\r\n",
  26978. first_response));
  26979. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26980. }
  26981. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26982. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26983. // be answered with 400 and the connection closed. Treating it as "no body"
  26984. // leaves the body to be parsed as the next request.
  26985. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26986. const char *targets[] = {
  26987. "GET /file", // handler that never reads the body
  26988. "GET /not-found", // no handler matches (404)
  26989. "POST /post", // handler that reads the body
  26990. };
  26991. for (auto target : targets) {
  26992. for (auto value : values) {
  26993. std::string first_response;
  26994. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26995. " HTTP/1.1\r\n"
  26996. "Host: localhost\r\n"
  26997. "Content-Length: " +
  26998. value + "\r\n\r\n",
  26999. first_response))
  27000. << target << " with Content-Length: " << value;
  27001. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27002. << target << " with Content-Length: " << value;
  27003. }
  27004. }
  27005. }
  27006. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27007. // A 400 for an unparseable request line leaves the rest of the message
  27008. // unread, so the connection must be closed rather than reused.
  27009. std::string first_response;
  27010. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27011. "Host: localhost\r\n"
  27012. "Content-Length: {len}\r\n"
  27013. "\r\n",
  27014. first_response));
  27015. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27016. }
  27017. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27018. // Same as above for a header block that fails to parse.
  27019. std::string first_response;
  27020. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27021. "Host: localhost\r\n"
  27022. "Bad Header\r\n"
  27023. "Content-Length: {len}\r\n"
  27024. "\r\n",
  27025. first_response));
  27026. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27027. }
  27028. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27029. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27030. // server must not read another request on that connection, even when the
  27031. // request had no body to drain.
  27032. std::string first_response;
  27033. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27034. "Host: localhost\r\n"
  27035. "\r\n",
  27036. first_response));
  27037. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27038. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27039. }
  27040. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27041. // A content reader that stops early leaves the stream inside the body.
  27042. // Draining the whole Content-Length from there, or reading the body again,
  27043. // reads into the next request, and whatever follows is parsed as a request
  27044. // of its own.
  27045. Server svr;
  27046. std::atomic<int> smuggled_count(0);
  27047. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27048. svr.Post("/upload", [](const Request &req, Response &res,
  27049. const ContentReader &content_reader) {
  27050. // Stop at the last chunk, so the whole body has been read however it
  27051. // arrives.
  27052. auto length = req.get_header_value_u64("Content-Length");
  27053. size_t total = 0;
  27054. auto consumed = content_reader([&](const char *, size_t n) {
  27055. total += n;
  27056. return total < length;
  27057. });
  27058. EXPECT_FALSE(consumed);
  27059. if (req.has_param("retry")) {
  27060. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27061. }
  27062. // Replace the 400 the aborted read set, which would close the connection.
  27063. res.set_redirect("/done");
  27064. });
  27065. auto port = svr.bind_to_any_port(HOST);
  27066. thread t = thread([&] { svr.listen_after_bind(); });
  27067. auto se = detail::scope_exit([&] {
  27068. svr.stop();
  27069. t.join();
  27070. });
  27071. svr.wait_until_ready();
  27072. // A front end sees the second request as a POST whose body is the GET. The
  27073. // first body is as long as the POST's headers, so draining it again reads
  27074. // exactly those and leaves the GET to be parsed next.
  27075. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27076. "Host: localhost\r\n"
  27077. "\r\n";
  27078. std::string second_head = "POST /post HTTP/1.1\r\n"
  27079. "Host: localhost\r\n"
  27080. "Content-Length: " +
  27081. std::to_string(inner.size()) +
  27082. "\r\n"
  27083. "\r\n";
  27084. for (auto target : {"/upload", "/upload?retry"}) {
  27085. smuggled_count = 0;
  27086. std::string request = "POST " + std::string(target) +
  27087. " HTTP/1.1\r\n"
  27088. "Host: localhost\r\n"
  27089. "Content-Length: " +
  27090. std::to_string(second_head.size()) +
  27091. "\r\n"
  27092. "\r\n" +
  27093. std::string(second_head.size(), 'A') + second_head +
  27094. inner;
  27095. std::string response;
  27096. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27097. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27098. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27099. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27100. EXPECT_EQ(0, smuggled_count.load()) << target;
  27101. }
  27102. }
  27103. // An error response closes the connection anyway, so the body is left unread
  27104. // with a redirect, such as one to a login page.
  27105. static void serve_redirects(Server &svr,
  27106. const std::function<void(int)> &client) {
  27107. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27108. res.set_redirect("/login");
  27109. return Server::HandlerResponse::Handled;
  27110. });
  27111. auto port = svr.bind_to_any_port(HOST);
  27112. ASSERT_GT(port, 0);
  27113. thread t = thread([&] { svr.listen_after_bind(); });
  27114. auto se = detail::scope_exit([&] {
  27115. svr.stop();
  27116. t.join();
  27117. ASSERT_FALSE(svr.is_running());
  27118. });
  27119. svr.wait_until_ready();
  27120. client(port);
  27121. }
  27122. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27123. Server svr;
  27124. serve_redirects(svr, [](int port) {
  27125. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27126. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27127. std::to_string(body.size()) + "\r\n\r\n" + body +
  27128. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27129. std::string resp;
  27130. ASSERT_TRUE(send_request(1, req, &resp, port));
  27131. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27132. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27133. });
  27134. }
  27135. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27136. Server svr;
  27137. svr.set_read_timeout(0, 200000);
  27138. serve_redirects(svr, [](int port) {
  27139. // A byte every 100 ms keeps each read within the read timeout, but not the
  27140. // body as a whole, so the server closes and the bytes sent after that fail.
  27141. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27142. "Content-Length: 10\r\n\r\n"};
  27143. parts.resize(11, "x");
  27144. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27145. });
  27146. }
  27147. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27148. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27149. // must be rejected with 400 Bad Request.
  27150. Server svr;
  27151. svr.Post("/test", [&](const Request &, Response &res) {
  27152. res.set_content("ok", "text/plain");
  27153. });
  27154. thread t = thread([&] { svr.listen(HOST, PORT); });
  27155. auto se = detail::scope_exit([&] {
  27156. svr.stop();
  27157. t.join();
  27158. ASSERT_FALSE(svr.is_running());
  27159. });
  27160. svr.wait_until_ready();
  27161. // Exact "chunked"
  27162. {
  27163. auto req = "POST /test HTTP/1.1\r\n"
  27164. "Host: localhost\r\n"
  27165. "Content-Length: 5\r\n"
  27166. "Transfer-Encoding: chunked\r\n"
  27167. "Connection: close\r\n"
  27168. "\r\n"
  27169. "hello";
  27170. std::string response;
  27171. ASSERT_TRUE(send_request(1, req, &response));
  27172. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27173. response.substr(0, response.find("\r\n")));
  27174. }
  27175. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27176. {
  27177. auto req = "POST /test HTTP/1.1\r\n"
  27178. "Host: localhost\r\n"
  27179. "Content-Length: 5\r\n"
  27180. "Transfer-Encoding: gzip, chunked\r\n"
  27181. "Connection: close\r\n"
  27182. "\r\n"
  27183. "hello";
  27184. std::string response;
  27185. ASSERT_TRUE(send_request(1, req, &response));
  27186. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27187. response.substr(0, response.find("\r\n")));
  27188. }
  27189. }
  27190. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27191. Server svr;
  27192. svr.Post("/test", [&](const Request &, Response &res) {
  27193. res.set_content("ok", "text/plain");
  27194. });
  27195. thread t = thread([&] { svr.listen(HOST, PORT); });
  27196. auto se = detail::scope_exit([&] {
  27197. svr.stop();
  27198. t.join();
  27199. ASSERT_FALSE(svr.is_running());
  27200. });
  27201. svr.wait_until_ready();
  27202. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27203. // length cannot be determined, so the server must answer 400 and close
  27204. // rather than treat the request as bodyless and leave the body in the
  27205. // socket for the next request to pick up.
  27206. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27207. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27208. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27209. std::string response;
  27210. ASSERT_TRUE(send_request(1, req, &response));
  27211. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27212. response.substr(0, response.find("\r\n")))
  27213. << transfer_encoding;
  27214. }
  27215. // RFC 9110 5.3: the codings may also be split across several
  27216. // Transfer-Encoding lines, which combine in the order they were received.
  27217. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27218. // just like the single-line "chunked, gzip" above.
  27219. {
  27220. auto req = "POST /test HTTP/1.1\r\n"
  27221. "Host: localhost\r\n"
  27222. "Transfer-Encoding: chunked\r\n"
  27223. "Transfer-Encoding: gzip\r\n"
  27224. "\r\n"
  27225. "0\r\n\r\n";
  27226. std::string response;
  27227. ASSERT_TRUE(send_request(1, req, &response));
  27228. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27229. response.substr(0, response.find("\r\n")));
  27230. }
  27231. }
  27232. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27233. Server svr;
  27234. svr.Post("/test", [&](const Request &, Response &res) {
  27235. res.set_content("ok", "text/plain");
  27236. });
  27237. auto port = svr.bind_to_any_port(HOST);
  27238. ASSERT_GT(port, 0);
  27239. thread t = thread([&] { svr.listen_after_bind(); });
  27240. auto se = detail::scope_exit([&] {
  27241. svr.stop();
  27242. t.join();
  27243. ASSERT_FALSE(svr.is_running());
  27244. });
  27245. svr.wait_until_ready();
  27246. for (auto transfer_encoding :
  27247. {"Transfer-Encoding: gzip, chunked\r\n",
  27248. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27249. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27250. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27251. transfer_encoding + "\r\n0\r\n\r\n";
  27252. std::string response;
  27253. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27254. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27255. response.substr(0, response.find("\r\n")))
  27256. << transfer_encoding;
  27257. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27258. << transfer_encoding;
  27259. }
  27260. }
  27261. // Regression for issue #2450: a DELETE without Content-Length on a
  27262. // keep-alive connection must not let the post-response drain consume the
  27263. // next request's bytes.
  27264. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27265. Server svr;
  27266. std::atomic<int> delete_count(0);
  27267. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27268. delete_count++;
  27269. res.status = StatusCode::NoContent_204;
  27270. });
  27271. auto port = svr.bind_to_any_port(HOST);
  27272. thread t = thread([&] { svr.listen_after_bind(); });
  27273. auto se = detail::scope_exit([&] {
  27274. svr.stop();
  27275. t.join();
  27276. });
  27277. svr.wait_until_ready();
  27278. auto error = Error::Success;
  27279. auto sock = detail::create_client_socket(
  27280. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27281. /*connection_timeout_sec=*/2, 0,
  27282. /*read_timeout_sec=*/2, 0,
  27283. /*write_timeout_sec=*/2, 0, std::string(), error);
  27284. ASSERT_NE(INVALID_SOCKET, sock);
  27285. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27286. auto send_request_and_read_response = [&](const std::string &req,
  27287. std::string &out) -> bool {
  27288. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27289. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27290. char buf[4096];
  27291. for (;;) {
  27292. auto n = recv(sock, buf, sizeof(buf), 0);
  27293. if (n <= 0) { return !out.empty(); }
  27294. out.append(buf, static_cast<size_t>(n));
  27295. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27296. }
  27297. };
  27298. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27299. "Host: localhost\r\n"
  27300. "\r\n";
  27301. std::string resp1;
  27302. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27303. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27304. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27305. "Host: localhost\r\n"
  27306. "Connection: close\r\n"
  27307. "\r\n";
  27308. std::string resp2;
  27309. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27310. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27311. EXPECT_EQ(2, delete_count.load());
  27312. }
  27313. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27314. Server svr;
  27315. svr.Post("/ingest", [&](const Request &, Response &res,
  27316. const ContentReader &content_reader) {
  27317. auto consumed = content_reader([](const char *, size_t) { return false; });
  27318. EXPECT_FALSE(consumed);
  27319. res.status = StatusCode::Conflict_409;
  27320. res.set_header("Connection", "close");
  27321. });
  27322. auto port = svr.bind_to_any_port(HOST);
  27323. thread t = thread([&] { svr.listen_after_bind(); });
  27324. auto se = detail::scope_exit([&] {
  27325. svr.stop();
  27326. t.join();
  27327. });
  27328. svr.wait_until_ready();
  27329. auto error = Error::Success;
  27330. auto sock = detail::create_client_socket(
  27331. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27332. /*connection_timeout_sec=*/2, 0,
  27333. /*read_timeout_sec=*/1, 0,
  27334. /*write_timeout_sec=*/2, 0, std::string(), error);
  27335. ASSERT_NE(INVALID_SOCKET, sock);
  27336. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27337. std::string request = "POST /ingest HTTP/1.1\r\n"
  27338. "Host: localhost\r\n"
  27339. "Transfer-Encoding: chunked\r\n"
  27340. "\r\n"
  27341. "4\r\n"
  27342. "data\r\n";
  27343. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27344. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27345. std::string response;
  27346. ssize_t received = 0;
  27347. do {
  27348. char buf[4096];
  27349. received = recv(sock, buf, sizeof(buf), 0);
  27350. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27351. } while (received > 0);
  27352. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27353. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27354. EXPECT_EQ(0, received);
  27355. }
  27356. namespace no_proxy_test {
  27357. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27358. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27359. // calling listen().
  27360. class ScopedServer {
  27361. public:
  27362. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27363. ~ScopedServer() {
  27364. svr_.stop();
  27365. if (th_.joinable()) { th_.join(); }
  27366. }
  27367. Server &svr() { return svr_; }
  27368. int port() const { return port_; }
  27369. void listen() {
  27370. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27371. svr_.wait_until_ready();
  27372. }
  27373. private:
  27374. Server svr_;
  27375. std::thread th_;
  27376. int port_ = 0;
  27377. };
  27378. class ProxyAndTargetServers {
  27379. public:
  27380. ProxyAndTargetServers() {
  27381. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27382. proxy_hits_++;
  27383. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27384. res.set_content("via-proxy", "text/plain");
  27385. });
  27386. target_.Get(".*", [this](const Request &req, Response &res) {
  27387. target_hits_++;
  27388. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27389. res.set_content("direct", "text/plain");
  27390. });
  27391. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27392. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27393. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27394. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27395. proxy_mock_.wait_until_ready();
  27396. target_.wait_until_ready();
  27397. }
  27398. ~ProxyAndTargetServers() {
  27399. proxy_mock_.stop();
  27400. target_.stop();
  27401. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27402. if (target_thread_.joinable()) { target_thread_.join(); }
  27403. }
  27404. Server &proxy_mock() { return proxy_mock_; }
  27405. Server &target() { return target_; }
  27406. int proxy_port() const { return proxy_port_; }
  27407. int target_port() const { return target_port_; }
  27408. int proxy_hits() const { return proxy_hits_.load(); }
  27409. int target_hits() const { return target_hits_.load(); }
  27410. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27411. void reset_counters() {
  27412. proxy_hits_ = 0;
  27413. target_hits_ = 0;
  27414. last_had_proxy_authz_ = false;
  27415. }
  27416. private:
  27417. Server proxy_mock_;
  27418. Server target_;
  27419. std::thread proxy_thread_;
  27420. std::thread target_thread_;
  27421. int proxy_port_ = 0;
  27422. int target_port_ = 0;
  27423. std::atomic<int> proxy_hits_{0};
  27424. std::atomic<int> target_hits_{0};
  27425. std::atomic<bool> last_had_proxy_authz_{false};
  27426. };
  27427. inline std::unique_ptr<Client> make_client(const std::string &host,
  27428. ProxyAndTargetServers &s) {
  27429. auto cli = detail::make_unique<Client>(host, s.target_port());
  27430. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27431. cli->set_proxy("127.0.0.1", s.proxy_port());
  27432. return cli;
  27433. }
  27434. } // namespace no_proxy_test
  27435. using no_proxy_test::make_client;
  27436. using no_proxy_test::ProxyAndTargetServers;
  27437. // A stream request carries the credentials a buffered request does
  27438. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27439. no_proxy_test::ScopedServer origin;
  27440. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27441. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27442. });
  27443. origin.listen();
  27444. Client cli("127.0.0.1", origin.port());
  27445. cli.set_basic_auth("user", "pass");
  27446. auto handle = cli.open_stream("GET", "/x");
  27447. ASSERT_TRUE(handle.is_valid());
  27448. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27449. Client bearer("127.0.0.1", origin.port());
  27450. bearer.set_bearer_token_auth("tok");
  27451. auto handle2 = bearer.open_stream("GET", "/x");
  27452. ASSERT_TRUE(handle2.is_valid());
  27453. EXPECT_EQ("Bearer tok", read_all(handle2));
  27454. }
  27455. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27456. // takes its own credentials, as for a buffered request
  27457. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27458. std::string target, authz, proxy_authz;
  27459. no_proxy_test::ScopedServer proxy;
  27460. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27461. target = req.target;
  27462. authz = req.get_header_value("Authorization");
  27463. proxy_authz = req.get_header_value("Proxy-Authorization");
  27464. res.set_content("ok", "text/plain");
  27465. });
  27466. proxy.listen();
  27467. Client cli("origin.example", 8080);
  27468. cli.set_proxy("127.0.0.1", proxy.port());
  27469. cli.set_proxy_basic_auth("puser", "ppass");
  27470. cli.set_basic_auth("user", "pass");
  27471. auto handle = cli.open_stream("GET", "/x");
  27472. ASSERT_TRUE(handle.is_valid());
  27473. EXPECT_EQ("ok", read_all(handle));
  27474. EXPECT_EQ("http://origin.example:8080/x", target);
  27475. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27476. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27477. }
  27478. // In absolute-form the path follows the authority, so a path that does not
  27479. // begin with '/' would make the proxy connect to another host
  27480. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27481. std::vector<std::string> targets;
  27482. no_proxy_test::ScopedServer proxy;
  27483. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27484. targets.push_back(req.target);
  27485. res.set_content("ok", "text/plain");
  27486. });
  27487. proxy.listen();
  27488. Client cli("origin.example", 8080);
  27489. cli.set_proxy("127.0.0.1", proxy.port());
  27490. cli.set_basic_auth("user", "pass");
  27491. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27492. auto res = cli.Get(path);
  27493. EXPECT_FALSE(res) << path;
  27494. auto handle = cli.open_stream("GET", path);
  27495. EXPECT_FALSE(handle.is_valid()) << path;
  27496. }
  27497. EXPECT_TRUE(targets.empty());
  27498. auto res = cli.Get("/x");
  27499. ASSERT_TRUE(res);
  27500. ASSERT_EQ(1u, targets.size());
  27501. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27502. }
  27503. TEST(NoProxyTest, ExactHostnameBypasses) {
  27504. ProxyAndTargetServers s;
  27505. auto cli = make_client("example.com", s);
  27506. cli->set_no_proxy({"example.com"});
  27507. auto res = cli->Get("/");
  27508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27509. EXPECT_EQ(0, s.proxy_hits());
  27510. EXPECT_EQ(1, s.target_hits());
  27511. }
  27512. TEST(NoProxyTest, SubdomainBypasses) {
  27513. ProxyAndTargetServers s;
  27514. auto cli = make_client("foo.example.com", s);
  27515. cli->set_no_proxy({"example.com"});
  27516. auto res = cli->Get("/");
  27517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27518. EXPECT_EQ(0, s.proxy_hits());
  27519. EXPECT_EQ(1, s.target_hits());
  27520. }
  27521. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27522. // Regression guard: "evilexample.com" must not be considered a subdomain
  27523. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27524. // check would let traffic bypass the proxy and leak credentials direct
  27525. // to the attacker host.
  27526. ProxyAndTargetServers s;
  27527. auto cli = make_client("evilexample.com", s);
  27528. cli->set_no_proxy({"example.com"});
  27529. auto res = cli->Get("/");
  27530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27531. EXPECT_GE(s.proxy_hits(), 1);
  27532. EXPECT_EQ(0, s.target_hits());
  27533. }
  27534. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27535. ProxyAndTargetServers s;
  27536. auto cli = make_client("example.com.evil.com", s);
  27537. cli->set_no_proxy({"example.com"});
  27538. auto res = cli->Get("/");
  27539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27540. EXPECT_GE(s.proxy_hits(), 1);
  27541. EXPECT_EQ(0, s.target_hits());
  27542. }
  27543. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27544. ProxyAndTargetServers s;
  27545. auto cli = make_client("example.com", s);
  27546. cli->set_no_proxy({".example.com"});
  27547. auto res = cli->Get("/");
  27548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27549. EXPECT_EQ(0, s.proxy_hits());
  27550. EXPECT_EQ(1, s.target_hits());
  27551. }
  27552. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27553. ProxyAndTargetServers s;
  27554. auto cli = make_client("Example.COM", s);
  27555. cli->set_no_proxy({"EXAMPLE.com"});
  27556. auto res = cli->Get("/");
  27557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27558. EXPECT_EQ(0, s.proxy_hits());
  27559. EXPECT_EQ(1, s.target_hits());
  27560. }
  27561. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27562. ProxyAndTargetServers s;
  27563. auto cli = make_client("example.com.", s);
  27564. cli->set_no_proxy({"example.com"});
  27565. auto res = cli->Get("/");
  27566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27567. EXPECT_EQ(0, s.proxy_hits());
  27568. EXPECT_EQ(1, s.target_hits());
  27569. }
  27570. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27571. // Trailing dots must be normalized on BOTH sides — host and entry.
  27572. // An implementation that only strips the host-side trailing dot would
  27573. // fail to match host "example.com" against entry "example.com." because
  27574. // a literal substring search would compare 11 chars against 12.
  27575. ProxyAndTargetServers s;
  27576. auto cli = make_client("example.com", s);
  27577. cli->set_no_proxy({"example.com."});
  27578. auto res = cli->Get("/");
  27579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27580. EXPECT_EQ(0, s.proxy_hits());
  27581. EXPECT_EQ(1, s.target_hits());
  27582. }
  27583. TEST(NoProxyTest, WildcardBypassesEverything) {
  27584. ProxyAndTargetServers s;
  27585. auto cli = make_client("anything.invalid.test", s);
  27586. cli->set_no_proxy({"*"});
  27587. auto res = cli->Get("/");
  27588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27589. EXPECT_EQ(0, s.proxy_hits());
  27590. EXPECT_EQ(1, s.target_hits());
  27591. }
  27592. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27593. ProxyAndTargetServers s;
  27594. Client cli("127.0.0.1", s.target_port());
  27595. cli.set_proxy("127.0.0.1", s.proxy_port());
  27596. cli.set_no_proxy({"127.0.0.1"});
  27597. auto res = cli.Get("/");
  27598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27599. EXPECT_EQ(0, s.proxy_hits());
  27600. EXPECT_EQ(1, s.target_hits());
  27601. }
  27602. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27603. ProxyAndTargetServers s;
  27604. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27605. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27606. cli.set_proxy("127.0.0.1", s.proxy_port());
  27607. cli.set_no_proxy({"::1"});
  27608. auto res = cli.Get("/");
  27609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27610. EXPECT_EQ(0, s.proxy_hits());
  27611. EXPECT_EQ(1, s.target_hits());
  27612. }
  27613. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27614. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27615. // must still be recognized as IPv6 for CIDR matching. Implementations
  27616. // that detect IPv6 only when the host begins with '[' would parse the
  27617. // host as a hostname and miss the match.
  27618. ProxyAndTargetServers s;
  27619. Client cli("fe80::1", s.target_port());
  27620. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27621. cli.set_proxy("127.0.0.1", s.proxy_port());
  27622. cli.set_no_proxy({"fe80::/10"});
  27623. auto res = cli.Get("/");
  27624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27625. EXPECT_EQ(0, s.proxy_hits());
  27626. EXPECT_EQ(1, s.target_hits());
  27627. }
  27628. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27629. ProxyAndTargetServers s;
  27630. Client cli("::1", s.target_port());
  27631. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27632. cli.set_proxy("127.0.0.1", s.proxy_port());
  27633. cli.set_no_proxy({"[::1]"});
  27634. auto res = cli.Get("/");
  27635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27636. EXPECT_EQ(0, s.proxy_hits());
  27637. EXPECT_EQ(1, s.target_hits());
  27638. }
  27639. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27640. ProxyAndTargetServers s;
  27641. Client cli("fe80::1", s.target_port());
  27642. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27643. cli.set_proxy("127.0.0.1", s.proxy_port());
  27644. cli.set_no_proxy({"[fe80::]/10"});
  27645. auto res = cli.Get("/");
  27646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27647. EXPECT_EQ(0, s.proxy_hits());
  27648. EXPECT_EQ(1, s.target_hits());
  27649. }
  27650. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27651. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27652. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27653. // tricks via address-family conversion.
  27654. ProxyAndTargetServers s;
  27655. Client cli("::ffff:127.0.0.1", s.target_port());
  27656. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27657. cli.set_proxy("127.0.0.1", s.proxy_port());
  27658. cli.set_no_proxy({"127.0.0.1"});
  27659. auto res = cli.Get("/");
  27660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27661. EXPECT_GE(s.proxy_hits(), 1);
  27662. EXPECT_EQ(0, s.target_hits());
  27663. }
  27664. TEST(NoProxyTest, IPv4CidrMatch) {
  27665. ProxyAndTargetServers s;
  27666. Client cli("127.0.0.1", s.target_port());
  27667. cli.set_proxy("127.0.0.1", s.proxy_port());
  27668. cli.set_no_proxy({"127.0.0.0/8"});
  27669. auto res = cli.Get("/");
  27670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27671. EXPECT_EQ(0, s.proxy_hits());
  27672. EXPECT_EQ(1, s.target_hits());
  27673. }
  27674. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27675. ProxyAndTargetServers s;
  27676. Client cli("127.0.0.1", s.target_port());
  27677. cli.set_proxy("127.0.0.1", s.proxy_port());
  27678. cli.set_no_proxy({"10.0.0.0/8"});
  27679. auto res = cli.Get("/");
  27680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27681. EXPECT_GE(s.proxy_hits(), 1);
  27682. EXPECT_EQ(0, s.target_hits());
  27683. }
  27684. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27685. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27686. // IPv4 target matches.
  27687. ProxyAndTargetServers s;
  27688. Client cli("127.0.0.1", s.target_port());
  27689. cli.set_proxy("127.0.0.1", s.proxy_port());
  27690. cli.set_no_proxy({"0.0.0.0/0"});
  27691. auto res = cli.Get("/");
  27692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27693. EXPECT_EQ(0, s.proxy_hits());
  27694. EXPECT_EQ(1, s.target_hits());
  27695. }
  27696. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27697. ProxyAndTargetServers s;
  27698. Client cli("127.0.0.1", s.target_port());
  27699. cli.set_proxy("127.0.0.1", s.proxy_port());
  27700. cli.set_no_proxy({"127.0.0.1"});
  27701. auto res = cli.Get("/");
  27702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27703. EXPECT_EQ(0, s.proxy_hits());
  27704. EXPECT_EQ(1, s.target_hits());
  27705. }
  27706. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27707. ProxyAndTargetServers s;
  27708. Client cli("127.0.0.1", s.target_port());
  27709. cli.set_proxy("127.0.0.1", s.proxy_port());
  27710. cli.set_no_proxy({"127.0.0.0/33"});
  27711. auto res = cli.Get("/");
  27712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27713. EXPECT_GE(s.proxy_hits(), 1);
  27714. EXPECT_EQ(0, s.target_hits());
  27715. }
  27716. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27717. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27718. ProxyAndTargetServers s;
  27719. Client cli("127.0.0.1", s.target_port());
  27720. cli.set_proxy("127.0.0.1", s.proxy_port());
  27721. cli.set_no_proxy({"127.0.0.1/"});
  27722. auto res = cli.Get("/");
  27723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27724. EXPECT_GE(s.proxy_hits(), 1);
  27725. EXPECT_EQ(0, s.target_hits());
  27726. }
  27727. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27728. ProxyAndTargetServers s;
  27729. auto cli = make_client("internal.corp", s);
  27730. cli->set_proxy_basic_auth("u", "p");
  27731. cli->set_no_proxy({"internal.corp"});
  27732. auto res = cli->Get("/");
  27733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27734. EXPECT_EQ(1, s.target_hits());
  27735. EXPECT_EQ(0, s.proxy_hits());
  27736. EXPECT_FALSE(s.last_had_proxy_authz())
  27737. << "Proxy-Authorization must not be sent direct to the target";
  27738. }
  27739. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27740. ProxyAndTargetServers s;
  27741. auto cli = make_client("public.example", s);
  27742. cli->set_proxy_basic_auth("u", "p");
  27743. cli->set_no_proxy({"internal.corp"}); // does not match
  27744. auto res = cli->Get("/");
  27745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27746. EXPECT_GE(s.proxy_hits(), 1);
  27747. EXPECT_TRUE(s.last_had_proxy_authz());
  27748. }
  27749. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27750. std::atomic<int> hits{0};
  27751. std::atomic<int> hits_with_authz{0};
  27752. no_proxy_test::ScopedServer proxy_mock;
  27753. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27754. hits++;
  27755. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27756. if (req.target.find("/redir") != std::string::npos) {
  27757. res.set_redirect("http://other.example/landed");
  27758. } else {
  27759. res.set_content("via-proxy", "text/plain");
  27760. }
  27761. });
  27762. proxy_mock.listen();
  27763. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27764. hits = 0;
  27765. hits_with_authz = 0;
  27766. Client cli("public.example", 80);
  27767. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27768. cli.set_proxy_basic_auth(c.first, c.second);
  27769. cli.set_follow_location(true);
  27770. // The redirect to another host goes through the proxy as well
  27771. auto res = cli.Get("/redir");
  27772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27773. EXPECT_EQ(2, hits.load());
  27774. EXPECT_EQ(2, hits_with_authz.load());
  27775. }
  27776. }
  27777. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27778. ProxyAndTargetServers s;
  27779. auto cli = make_client("anything.test", s);
  27780. auto res = cli->Get("/");
  27781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27782. EXPECT_GE(s.proxy_hits(), 1);
  27783. EXPECT_EQ(0, s.target_hits());
  27784. }
  27785. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27786. ProxyAndTargetServers s;
  27787. auto cli = make_client("example.com", s);
  27788. cli->set_no_proxy({"example.com:8080"});
  27789. auto res = cli->Get("/");
  27790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27791. EXPECT_GE(s.proxy_hits(), 1);
  27792. EXPECT_EQ(0, s.target_hits());
  27793. }
  27794. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27795. ProxyAndTargetServers s;
  27796. auto cli = make_client("anything.test", s);
  27797. cli->set_no_proxy({"", " ", "\t"});
  27798. auto res = cli->Get("/");
  27799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27800. EXPECT_GE(s.proxy_hits(), 1);
  27801. EXPECT_EQ(0, s.target_hits());
  27802. }
  27803. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27804. // An entry with leading/trailing whitespace must still match — env-style
  27805. // values are commonly pasted with stray spaces and an implementation
  27806. // that feeds the raw token directly to inet_pton would fail to match
  27807. // valid CIDRs because of the spaces.
  27808. ProxyAndTargetServers s;
  27809. Client cli("127.0.0.1", s.target_port());
  27810. cli.set_proxy("127.0.0.1", s.proxy_port());
  27811. cli.set_no_proxy({" 127.0.0.0/8 "});
  27812. auto res = cli.Get("/");
  27813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27814. EXPECT_EQ(0, s.proxy_hits());
  27815. EXPECT_EQ(1, s.target_hits());
  27816. }
  27817. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27818. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27819. // go direct and must NOT carry Proxy-Authorization.
  27820. std::atomic<int> proxy_hits{0};
  27821. std::atomic<int> target_hits{0};
  27822. std::atomic<bool> target_saw_authz{false};
  27823. no_proxy_test::ScopedServer proxy_mock, target;
  27824. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27825. proxy_hits++;
  27826. res.status = 302;
  27827. res.set_header("Location", "http://127.0.0.1:" +
  27828. std::to_string(target.port()) + "/landed");
  27829. });
  27830. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27831. target_hits++;
  27832. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27833. res.set_content("direct", "text/plain");
  27834. });
  27835. proxy_mock.listen();
  27836. target.listen();
  27837. Client cli("public.example", target.port());
  27838. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27839. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27840. cli.set_proxy_basic_auth("u", "p");
  27841. cli.set_no_proxy({"127.0.0.1"});
  27842. cli.set_follow_location(true);
  27843. auto res = cli.Get("/redir");
  27844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27845. EXPECT_GE(proxy_hits.load(), 1);
  27846. EXPECT_GE(target_hits.load(), 1);
  27847. EXPECT_FALSE(target_saw_authz.load());
  27848. }
  27849. #ifdef CPPHTTPLIB_SSL_ENABLED
  27850. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27851. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27852. // proxy creds would be sent to the (possibly hostile) origin.
  27853. std::atomic<int> target_hits{0};
  27854. std::atomic<bool> target_saw_proxy_authz{false};
  27855. no_proxy_test::ScopedServer target;
  27856. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27857. target_hits++;
  27858. if (req.has_header("Proxy-Authorization")) {
  27859. target_saw_proxy_authz = true;
  27860. }
  27861. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27862. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27863. "nonce=\"abc\", algorithm=MD5");
  27864. });
  27865. target.listen();
  27866. // The proxy address is set to the target's port: the bypass MUST kick in;
  27867. // if it doesn't, the test still routes "via proxy" to the same server and
  27868. // the Proxy-Authorization assertion below catches the leak.
  27869. Client cli("evil.example", target.port());
  27870. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27871. cli.set_proxy("127.0.0.1", target.port());
  27872. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27873. cli.set_no_proxy({"evil.example"});
  27874. auto res = cli.Get("/x");
  27875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27876. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27877. EXPECT_EQ(1, target_hits.load());
  27878. EXPECT_FALSE(target_saw_proxy_authz.load());
  27879. }
  27880. #endif
  27881. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27882. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27883. std::atomic<int> proxy_hits{0};
  27884. std::atomic<int> bypass_hits{0};
  27885. std::atomic<bool> proxy_saw_c_url{false};
  27886. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27887. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27888. proxy_hits++;
  27889. if (req.path.find("/start") != std::string::npos) {
  27890. res.status = 302;
  27891. res.set_header("Location", "http://127.0.0.1:" +
  27892. std::to_string(bypass_server.port()) +
  27893. "/middle");
  27894. return;
  27895. }
  27896. if (req.path.find("/end") != std::string::npos) {
  27897. proxy_saw_c_url = true;
  27898. res.set_content("c-via-proxy", "text/plain");
  27899. return;
  27900. }
  27901. res.set_content("unexpected", "text/plain");
  27902. });
  27903. // public.example's "advertised" port is arbitrary (the request never lands
  27904. // there — it goes through the proxy), but use a dynamic value to stay
  27905. // friendly with sharded parallel runs.
  27906. int public_port = bypass_server.port();
  27907. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27908. bypass_hits++;
  27909. res.status = 302;
  27910. res.set_header("Location", "http://public.example:" +
  27911. std::to_string(public_port) + "/end");
  27912. });
  27913. proxy_mock.listen();
  27914. bypass_server.listen();
  27915. Client cli("public.example", public_port);
  27916. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27917. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27918. cli.set_no_proxy({"127.0.0.1"});
  27919. cli.set_follow_location(true);
  27920. auto res = cli.Get("/start");
  27921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27922. EXPECT_EQ(StatusCode::OK_200, res->status);
  27923. EXPECT_EQ("c-via-proxy", res->body);
  27924. EXPECT_GE(proxy_hits.load(), 2);
  27925. EXPECT_GE(bypass_hits.load(), 1);
  27926. EXPECT_TRUE(proxy_saw_c_url.load());
  27927. }
  27928. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27929. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27930. // request reconnects to the correct endpoint.
  27931. std::atomic<int> proxy_hits{0};
  27932. std::atomic<int> target_hits{0};
  27933. no_proxy_test::ScopedServer proxy_mock, target;
  27934. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27935. proxy_hits++;
  27936. res.set_content("via-proxy", "text/plain");
  27937. });
  27938. target.svr().Get(".*", [&](const Request &, Response &res) {
  27939. target_hits++;
  27940. res.set_content("direct", "text/plain");
  27941. });
  27942. proxy_mock.listen();
  27943. target.listen();
  27944. Client cli("public.example", target.port());
  27945. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27946. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27947. cli.set_keep_alive(true);
  27948. auto res1 = cli.Get("/a");
  27949. ASSERT_TRUE(res1);
  27950. EXPECT_EQ("via-proxy", res1->body);
  27951. EXPECT_EQ(1, proxy_hits.load());
  27952. EXPECT_EQ(0, target_hits.load());
  27953. cli.set_no_proxy({"public.example"});
  27954. auto res2 = cli.Get("/b");
  27955. ASSERT_TRUE(res2);
  27956. EXPECT_EQ("direct", res2->body);
  27957. EXPECT_EQ(1, proxy_hits.load());
  27958. EXPECT_EQ(1, target_hits.load());
  27959. }
  27960. // Forward declarations (see the base64_encode note).
  27961. namespace httplib {
  27962. namespace detail {
  27963. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27964. int shutdown_socket(socket_t sock) noexcept;
  27965. } // namespace detail
  27966. } // namespace httplib
  27967. namespace proxy_tunnel_test {
  27968. const char *const kTunnelEstablished =
  27969. "HTTP/1.1 200 Connection established\r\n\r\n";
  27970. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27971. using ConnectReply = std::function<std::string(const std::string &head)>;
  27972. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27973. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27974. class ScopedConnectProxy {
  27975. public:
  27976. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27977. : forward_port_(forward_port), reply_(std::move(reply)) {
  27978. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27979. if (listen_sock_ == INVALID_SOCKET) { return; }
  27980. auto a = loopback(0);
  27981. auto addr = reinterpret_cast<sockaddr *>(&a);
  27982. socklen_t alen = sizeof(a);
  27983. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27984. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27985. ::listen(listen_sock_, 4) != 0) {
  27986. return;
  27987. }
  27988. port_ = ntohs(a.sin_port);
  27989. th_ = std::thread([this] { run(); });
  27990. }
  27991. ~ScopedConnectProxy() {
  27992. if (th_.joinable()) {
  27993. stop_ = true;
  27994. auto wake = connect_to(port_);
  27995. th_.join();
  27996. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27997. }
  27998. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27999. }
  28000. int port() const { return port_; }
  28001. int connect_hits() const { return connect_hits_.load(); }
  28002. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28003. std::string connect_request() const {
  28004. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28005. return connect_request_;
  28006. }
  28007. private:
  28008. static sockaddr_in loopback(int port) {
  28009. sockaddr_in a{};
  28010. a.sin_family = AF_INET;
  28011. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28012. a.sin_port = htons(static_cast<unsigned short>(port));
  28013. return a;
  28014. }
  28015. static socket_t connect_to(int port) {
  28016. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28017. if (sock == INVALID_SOCKET) { return sock; }
  28018. auto a = loopback(port);
  28019. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28020. detail::close_socket(sock);
  28021. return INVALID_SOCKET;
  28022. }
  28023. return sock;
  28024. }
  28025. static bool send_all(socket_t sock, const char *data, size_t size) {
  28026. while (size > 0) {
  28027. auto n = detail::send_socket(sock, data, size, 0);
  28028. if (n <= 0) { return false; }
  28029. data += n;
  28030. size -= static_cast<size_t>(n);
  28031. }
  28032. return true;
  28033. }
  28034. void run() {
  28035. for (;;) {
  28036. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28037. if (stop_) {
  28038. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28039. return;
  28040. }
  28041. if (client == INVALID_SOCKET) { continue; }
  28042. serve(client);
  28043. detail::close_socket(client);
  28044. }
  28045. }
  28046. void serve(socket_t client) {
  28047. std::string head;
  28048. char buf[2048];
  28049. while (head.find("\r\n\r\n") == std::string::npos) {
  28050. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28051. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28052. if (n <= 0) { return; }
  28053. head.append(buf, static_cast<size_t>(n));
  28054. }
  28055. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28056. connect_hits_++;
  28057. {
  28058. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28059. connect_request_ = head;
  28060. }
  28061. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28062. if (!send_all(client, res.data(), res.size()) ||
  28063. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28064. return;
  28065. }
  28066. auto origin = connect_to(forward_port_);
  28067. if (origin == INVALID_SOCKET) { return; }
  28068. // When either side stops, shut both down so the other pump returns too.
  28069. auto pump = [&](socket_t from, socket_t to) {
  28070. char b[8192];
  28071. for (;;) {
  28072. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28073. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28074. }
  28075. detail::shutdown_socket(client);
  28076. detail::shutdown_socket(origin);
  28077. };
  28078. std::thread up([&] { pump(client, origin); });
  28079. pump(origin, client);
  28080. up.join();
  28081. detail::close_socket(origin);
  28082. }
  28083. int forward_port_;
  28084. ConnectReply reply_;
  28085. socket_t listen_sock_ = INVALID_SOCKET;
  28086. int port_ = 0;
  28087. std::thread th_;
  28088. std::atomic<bool> stop_{false};
  28089. std::atomic<int> connect_hits_{0};
  28090. mutable std::mutex connect_request_mutex_;
  28091. std::string connect_request_;
  28092. };
  28093. } // namespace proxy_tunnel_test
  28094. #ifdef CPPHTTPLIB_SSL_ENABLED
  28095. namespace proxy_tunnel_test {
  28096. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28097. class ScopedSSLServer {
  28098. public:
  28099. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28100. port_ = svr_.bind_to_any_port("127.0.0.1");
  28101. }
  28102. ~ScopedSSLServer() {
  28103. svr_.stop();
  28104. if (th_.joinable()) { th_.join(); }
  28105. }
  28106. SSLServer &svr() { return svr_; }
  28107. int port() const { return port_; }
  28108. void listen() {
  28109. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28110. svr_.wait_until_ready();
  28111. }
  28112. private:
  28113. SSLServer svr_;
  28114. std::thread th_;
  28115. int port_ = 0;
  28116. };
  28117. // Sends one request through the CONNECT proxy to the TLS origin with a
  28118. // credential configured for each hop, and checks that each credential reaches
  28119. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28120. // origin's (every header in origin_headers) on the tunnelled request.
  28121. void CredentialsStayWithTheirHop(
  28122. const std::function<void(SSLClient &)> &set_credentials,
  28123. const std::string &scheme,
  28124. const std::vector<std::string> &origin_headers = {"Authorization"},
  28125. bool stream = false) {
  28126. std::atomic<int> origin_hits{0};
  28127. std::atomic<bool> origin_saw_proxy_authz{false};
  28128. std::atomic<bool> origin_saw_headers{false};
  28129. ScopedSSLServer origin;
  28130. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28131. origin_hits++;
  28132. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28133. origin_saw_headers =
  28134. std::all_of(origin_headers.begin(), origin_headers.end(),
  28135. [&](const std::string &h) { return req.has_header(h); });
  28136. res.set_content("ok", "text/plain");
  28137. });
  28138. origin.listen();
  28139. ScopedConnectProxy proxy(origin.port());
  28140. ASSERT_NE(0, proxy.port());
  28141. // Pinned to 127.0.0.1 for the same reason as the test below.
  28142. SSLClient cli("127.0.0.1", origin.port());
  28143. cli.enable_server_certificate_verification(false);
  28144. cli.set_proxy("127.0.0.1", proxy.port());
  28145. set_credentials(cli);
  28146. if (stream) {
  28147. auto handle = cli.open_stream("GET", "/x");
  28148. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28149. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28150. } else {
  28151. auto res = cli.Get("/x");
  28152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28153. EXPECT_EQ(StatusCode::OK_200, res->status);
  28154. }
  28155. EXPECT_EQ(1, origin_hits.load());
  28156. EXPECT_EQ(1, proxy.connect_hits());
  28157. EXPECT_TRUE(origin_saw_headers.load());
  28158. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28159. << "Proxy-Authorization must not be sent inside the tunnel";
  28160. auto connect_req = proxy.connect_request();
  28161. EXPECT_NE(std::string::npos,
  28162. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28163. for (const auto &h : origin_headers) {
  28164. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28165. << h << " must not be sent to the proxy on CONNECT";
  28166. }
  28167. }
  28168. } // namespace proxy_tunnel_test
  28169. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28170. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28171. [](SSLClient &cli) {
  28172. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28173. cli.set_basic_auth("origin-user", "origin-pass");
  28174. },
  28175. "Basic");
  28176. }
  28177. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28178. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28179. [](SSLClient &cli) {
  28180. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28181. cli.set_basic_auth("origin-user", "origin-pass");
  28182. },
  28183. "Basic", {"Authorization"}, true);
  28184. }
  28185. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28186. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28187. [](SSLClient &cli) {
  28188. cli.set_proxy_bearer_token_auth("proxy-token");
  28189. cli.set_bearer_token_auth("origin-token");
  28190. },
  28191. "Bearer");
  28192. }
  28193. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28194. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28195. [](SSLClient &cli) {
  28196. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28197. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28198. {"Cookie", "sid=origin-session"},
  28199. {"X-Api-Key", "origin-key"}});
  28200. },
  28201. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28202. }
  28203. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28204. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28205. // retry; otherwise proxy creds would be sent to the origin.
  28206. std::atomic<int> origin_hits{0};
  28207. std::atomic<bool> origin_saw_proxy_authz{false};
  28208. proxy_tunnel_test::ScopedSSLServer origin;
  28209. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28210. origin_hits++;
  28211. if (req.has_header("Proxy-Authorization")) {
  28212. origin_saw_proxy_authz = true;
  28213. }
  28214. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28215. res.set_header("Proxy-Authenticate",
  28216. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28217. "algorithm=MD5");
  28218. });
  28219. origin.listen();
  28220. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28221. ASSERT_NE(0, proxy.port());
  28222. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28223. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28224. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28225. // and answer with its own status, making this test flaky.
  28226. SSLClient cli("127.0.0.1", origin.port());
  28227. cli.enable_server_certificate_verification(false);
  28228. cli.set_proxy("127.0.0.1", proxy.port());
  28229. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28230. auto res = cli.Get("/x");
  28231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28232. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28233. EXPECT_EQ(1, origin_hits.load());
  28234. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28235. EXPECT_EQ(1, proxy.connect_hits());
  28236. }
  28237. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28238. std::string origin_sni;
  28239. std::string origin_host;
  28240. proxy_tunnel_test::ScopedSSLServer origin;
  28241. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28242. origin_sni = req.sni();
  28243. origin_host = req.get_header_value("Host");
  28244. res.set_content("ok", "text/plain");
  28245. });
  28246. origin.listen();
  28247. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28248. ASSERT_NE(0, proxy.port());
  28249. SSLClient cli("origin.example", origin.port());
  28250. cli.enable_server_certificate_verification(false);
  28251. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28252. cli.set_proxy("127.0.0.1", proxy.port());
  28253. auto res = cli.Get("/x");
  28254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28255. EXPECT_EQ(StatusCode::OK_200, res->status);
  28256. auto port = std::to_string(origin.port());
  28257. auto target = "127.0.0.1:" + port;
  28258. auto connect_req = proxy.connect_request();
  28259. EXPECT_EQ(1, proxy.connect_hits());
  28260. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28261. EXPECT_NE(std::string::npos,
  28262. connect_req.find("\r\nHost: " + target + "\r\n"));
  28263. EXPECT_EQ("origin.example", origin_sni);
  28264. EXPECT_EQ("origin.example:" + port, origin_host);
  28265. }
  28266. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28267. proxy_tunnel_test::ScopedSSLServer origin;
  28268. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28269. res.set_content("ok", "text/plain");
  28270. });
  28271. origin.listen();
  28272. proxy_tunnel_test::ScopedConnectProxy proxy(
  28273. origin.port(), [](const std::string &head) -> std::string {
  28274. if (head.find(
  28275. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28276. std::string::npos) {
  28277. return proxy_tunnel_test::kTunnelEstablished;
  28278. }
  28279. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28280. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28281. "nonce=\"abc\", algorithm=MD5\r\n"
  28282. "Content-Length: 0\r\n\r\n";
  28283. });
  28284. ASSERT_NE(0, proxy.port());
  28285. SSLClient cli("origin.example", origin.port());
  28286. cli.enable_server_certificate_verification(false);
  28287. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28288. cli.set_proxy("127.0.0.1", proxy.port());
  28289. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28290. auto res = cli.Get("/x");
  28291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28292. EXPECT_EQ(StatusCode::OK_200, res->status);
  28293. // The retried CONNECT is the one the proxy saw last.
  28294. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28295. auto connect_req = proxy.connect_request();
  28296. EXPECT_EQ(2, proxy.connect_hits());
  28297. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28298. EXPECT_NE(std::string::npos,
  28299. connect_req.find("\r\nHost: " + target + "\r\n"));
  28300. }
  28301. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28302. proxy_tunnel_test::ScopedSSLServer origin;
  28303. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28304. res.set_content("ok", "text/plain");
  28305. });
  28306. origin.listen();
  28307. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28308. ASSERT_NE(0, proxy.port());
  28309. SSLClient cli("origin.example", origin.port());
  28310. cli.enable_server_certificate_verification(false);
  28311. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28312. cli.set_proxy("127.0.0.1", proxy.port());
  28313. auto res = cli.Get("/x");
  28314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28315. EXPECT_EQ(StatusCode::OK_200, res->status);
  28316. auto target = "origin.example:" + std::to_string(origin.port());
  28317. auto connect_req = proxy.connect_request();
  28318. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28319. EXPECT_NE(std::string::npos,
  28320. connect_req.find("\r\nHost: " + target + "\r\n"));
  28321. }
  28322. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28323. proxy_tunnel_test::ScopedSSLServer origin;
  28324. auto port = std::to_string(origin.port());
  28325. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28326. res.set_redirect("https://next.example:" + port + "/y");
  28327. });
  28328. origin.svr().Get("/y", [](const Request &, Response &res) {
  28329. res.set_content("ok", "text/plain");
  28330. });
  28331. origin.listen();
  28332. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28333. ASSERT_NE(0, proxy.port());
  28334. SSLClient cli("origin.example", origin.port());
  28335. cli.enable_server_certificate_verification(false);
  28336. cli.set_tunnel_hostname_addr_map(
  28337. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28338. cli.set_proxy("127.0.0.1", proxy.port());
  28339. cli.set_follow_location(true);
  28340. auto res = cli.Get("/x");
  28341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28342. EXPECT_EQ("ok", res->body);
  28343. // The last CONNECT is the redirect client's.
  28344. ASSERT_EQ(2, proxy.connect_hits());
  28345. auto target = "127.0.0.1:" + port;
  28346. auto connect_req = proxy.connect_request();
  28347. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28348. EXPECT_NE(std::string::npos,
  28349. connect_req.find("\r\nHost: " + target + "\r\n"));
  28350. }
  28351. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28352. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28353. std::atomic<int> origin_hits{0};
  28354. proxy_tunnel_test::ScopedSSLServer origin;
  28355. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28356. origin_hits++;
  28357. res.set_content("ok", "text/plain");
  28358. });
  28359. origin.listen();
  28360. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28361. ASSERT_NE(0, proxy.port());
  28362. SSLClient cli("127.0.0.1", origin.port());
  28363. cli.enable_server_certificate_verification(false);
  28364. cli.set_proxy("127.0.0.1", proxy.port());
  28365. cli.set_keep_alive(true);
  28366. cli.set_session_verifier(
  28367. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28368. auto res = cli.Get("/x");
  28369. EXPECT_FALSE(res);
  28370. ASSERT_FALSE(cli.is_socket_open());
  28371. res = cli.Get("/x");
  28372. EXPECT_FALSE(res);
  28373. EXPECT_EQ(2, proxy.connect_hits());
  28374. auto handle = cli.open_stream("GET", "/x");
  28375. EXPECT_FALSE(handle.is_valid());
  28376. EXPECT_EQ(3, proxy.connect_hits());
  28377. EXPECT_EQ(0, origin_hits.load());
  28378. }
  28379. #endif
  28380. namespace proxy_tunnel_test {
  28381. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28382. // anything else gets a 407 with `challenge`.
  28383. ConnectReply require_proxy_auth(const std::string &expected,
  28384. const std::string &challenge) {
  28385. return [=](const std::string &head) -> std::string {
  28386. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28387. std::string::npos) {
  28388. return kTunnelEstablished;
  28389. }
  28390. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28391. "Proxy-Authenticate: " +
  28392. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28393. };
  28394. }
  28395. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28396. // request, then echoes.
  28397. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28398. ws.send(
  28399. "authorization:" + req.get_header_value("Authorization") +
  28400. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28401. std::string msg;
  28402. while (ws.read(msg)) {
  28403. ws.send(msg);
  28404. }
  28405. }
  28406. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28407. class ScopedWebSocketOrigin {
  28408. public:
  28409. ScopedWebSocketOrigin() {
  28410. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28411. server_.listen();
  28412. }
  28413. int port() const { return server_.port(); }
  28414. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28415. std::string url() const {
  28416. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28417. }
  28418. private:
  28419. no_proxy_test::ScopedServer server_;
  28420. };
  28421. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28422. // passed as a constructor header, and checks that each reaches only its hop.
  28423. void WebSocketCredentialsStayWithTheirHop(
  28424. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28425. const std::string &proxy_authz, const std::string &origin_authz) {
  28426. ScopedWebSocketOrigin origin;
  28427. ScopedConnectProxy proxy(
  28428. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28429. ASSERT_NE(0, proxy.port());
  28430. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28431. client.set_proxy("127.0.0.1", proxy.port());
  28432. set_proxy_credentials(client);
  28433. auto res = client.connect();
  28434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28435. std::string msg;
  28436. ASSERT_TRUE(client.read(msg));
  28437. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28438. client.close();
  28439. EXPECT_EQ(1, proxy.connect_hits());
  28440. EXPECT_EQ(std::string::npos,
  28441. proxy.connect_request().find("\r\nAuthorization: "))
  28442. << "origin credentials must not be sent to the proxy";
  28443. }
  28444. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28445. void WebSocketSetterCredentialsStayWithTheirHop(
  28446. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28447. const std::string &proxy_authz, const std::string &origin_authz) {
  28448. ScopedWebSocketOrigin origin;
  28449. ScopedConnectProxy proxy(
  28450. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28451. ASSERT_NE(0, proxy.port());
  28452. ws::WebSocketClient client(origin.url());
  28453. client.set_proxy("127.0.0.1", proxy.port());
  28454. set_credentials(client);
  28455. auto res = client.connect();
  28456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28457. std::string msg;
  28458. ASSERT_TRUE(client.read(msg));
  28459. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28460. client.close();
  28461. EXPECT_EQ(1, proxy.connect_hits());
  28462. EXPECT_EQ(std::string::npos,
  28463. proxy.connect_request().find("\r\nAuthorization: "))
  28464. << "origin credentials must not be sent to the proxy";
  28465. }
  28466. } // namespace proxy_tunnel_test
  28467. namespace {
  28468. // Connects `client` and returns the Authorization header its upgrade
  28469. // request carried, or "<failed>" when the connection could not be opened.
  28470. std::string websocket_authorization(ws::WebSocketClient &client) {
  28471. if (!client.connect()) { return "<failed>"; }
  28472. std::string msg;
  28473. if (!client.read(msg)) { return "<failed>"; }
  28474. client.close();
  28475. auto prefix = std::string("authorization:");
  28476. auto end = msg.find("|proxy-authorization:");
  28477. return msg.substr(prefix.size(), end - prefix.size());
  28478. }
  28479. } // namespace
  28480. TEST(WebSocketClientAuthTest, BasicAuth) {
  28481. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28482. ws::WebSocketClient client(origin.url());
  28483. client.set_basic_auth("user", "pass");
  28484. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28485. websocket_authorization(client));
  28486. }
  28487. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28488. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28489. ws::WebSocketClient client(origin.url());
  28490. client.set_basic_auth("user", "");
  28491. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28492. websocket_authorization(client));
  28493. }
  28494. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28495. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28496. ws::WebSocketClient client(origin.url());
  28497. client.set_bearer_token_auth("token123");
  28498. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28499. }
  28500. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28501. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28502. ws::WebSocketClient client(origin.url());
  28503. client.set_bearer_token_auth("token123");
  28504. client.set_basic_auth("user", "pass");
  28505. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28506. websocket_authorization(client));
  28507. }
  28508. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28509. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28510. ws::WebSocketClient client(origin.url(),
  28511. {{"Authorization", "Bearer from-header"}});
  28512. client.set_bearer_token_auth("from-setter");
  28513. client.set_basic_auth("user", "pass");
  28514. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28515. }
  28516. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28517. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28518. ws::WebSocketClient client(origin.url());
  28519. EXPECT_EQ("", websocket_authorization(client));
  28520. client.set_bearer_token_auth("first");
  28521. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28522. client.set_bearer_token_auth("second");
  28523. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28524. client.set_bearer_token_auth("");
  28525. EXPECT_EQ("", websocket_authorization(client));
  28526. }
  28527. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28528. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28529. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28530. ASSERT_NE(0, proxy.port());
  28531. ws::WebSocketClient client(origin.url());
  28532. client.set_proxy("127.0.0.1", proxy.port());
  28533. auto res = client.connect();
  28534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28535. std::string msg;
  28536. ASSERT_TRUE(client.read(msg));
  28537. ASSERT_TRUE(client.send("hello"));
  28538. ASSERT_TRUE(client.read(msg));
  28539. EXPECT_EQ("hello", msg);
  28540. client.close();
  28541. EXPECT_EQ(1, proxy.connect_hits());
  28542. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28543. auto connect_req = proxy.connect_request();
  28544. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28545. EXPECT_NE(std::string::npos,
  28546. connect_req.find("\r\nHost: " + target + "\r\n"));
  28547. }
  28548. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28549. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28550. [](ws::WebSocketClient &cli) {
  28551. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28552. },
  28553. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28554. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28555. }
  28556. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28557. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28558. [](ws::WebSocketClient &cli) {
  28559. cli.set_proxy_bearer_token_auth("proxy-token");
  28560. },
  28561. "Bearer proxy-token", "Bearer origin-token");
  28562. }
  28563. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28564. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28565. [](ws::WebSocketClient &cli) {
  28566. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28567. cli.set_basic_auth("origin-user", "origin-pass");
  28568. },
  28569. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28570. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28571. }
  28572. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28573. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28574. [](ws::WebSocketClient &cli) {
  28575. cli.set_proxy_bearer_token_auth("proxy-token");
  28576. cli.set_bearer_token_auth("origin-token");
  28577. },
  28578. "Bearer proxy-token", "Bearer origin-token");
  28579. }
  28580. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28581. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28582. proxy_tunnel_test::ScopedConnectProxy proxy(
  28583. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28584. "Basic " + detail::base64_encode("proxy-user:"),
  28585. "Basic realm=\"proxy\""));
  28586. ASSERT_NE(0, proxy.port());
  28587. ws::WebSocketClient client(origin.url());
  28588. client.set_proxy("127.0.0.1", proxy.port());
  28589. client.set_proxy_basic_auth("proxy-user", "");
  28590. auto res = client.connect();
  28591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28592. client.close();
  28593. EXPECT_EQ(1, proxy.connect_hits());
  28594. }
  28595. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28596. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28597. proxy_tunnel_test::ScopedConnectProxy proxy(
  28598. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28599. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28600. ASSERT_NE(0, proxy.port());
  28601. ws::WebSocketClient client(origin.url());
  28602. client.set_proxy("127.0.0.1", proxy.port());
  28603. auto res = client.connect();
  28604. EXPECT_FALSE(res);
  28605. EXPECT_EQ(Error::ProxyConnection, res.error());
  28606. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28607. EXPECT_EQ("Basic realm=\"proxy\"",
  28608. res.get_header_value("Proxy-Authenticate"));
  28609. EXPECT_FALSE(client.is_open());
  28610. }
  28611. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28612. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28613. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28614. ASSERT_NE(0, proxy.port());
  28615. ws::WebSocketClient client(origin.url());
  28616. client.set_proxy("127.0.0.1", proxy.port());
  28617. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28618. client.set_no_proxy({"127.0.0.1"});
  28619. auto res = client.connect();
  28620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28621. std::string msg;
  28622. ASSERT_TRUE(client.read(msg));
  28623. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28624. << "proxy credentials must not reach a bypassed origin";
  28625. client.close();
  28626. EXPECT_EQ(0, proxy.connect_hits());
  28627. }
  28628. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28629. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28630. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28631. ASSERT_NE(0, proxy.port());
  28632. ws::WebSocketClient client(origin.url());
  28633. client.set_proxy("127.0.0.1", proxy.port());
  28634. ASSERT_TRUE(client.connect());
  28635. ASSERT_TRUE(client.connect());
  28636. client.close();
  28637. EXPECT_EQ(2, proxy.connect_hits());
  28638. }
  28639. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28640. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28641. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28642. ASSERT_NE(0, proxy.port());
  28643. auto port = std::to_string(origin.port());
  28644. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28645. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28646. client.set_proxy("127.0.0.1", proxy.port());
  28647. auto res = client.connect();
  28648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28649. std::string msg;
  28650. ASSERT_TRUE(client.read(msg));
  28651. client.close();
  28652. EXPECT_EQ(1, proxy.connect_hits());
  28653. auto target = "127.0.0.1:" + port;
  28654. auto connect_req = proxy.connect_request();
  28655. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28656. EXPECT_NE(std::string::npos,
  28657. connect_req.find("\r\nHost: " + target + "\r\n"));
  28658. }
  28659. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28660. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28661. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28662. ASSERT_NE(0, proxy.port());
  28663. auto port = std::to_string(origin.port());
  28664. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28665. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28666. client.set_proxy("127.0.0.1", proxy.port());
  28667. auto res = client.connect();
  28668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28669. client.close();
  28670. auto target = "origin.example:" + port;
  28671. auto connect_req = proxy.connect_request();
  28672. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28673. EXPECT_NE(std::string::npos,
  28674. connect_req.find("\r\nHost: " + target + "\r\n"));
  28675. }
  28676. #ifdef CPPHTTPLIB_SSL_ENABLED
  28677. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28678. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28679. proxy_tunnel_test::ScopedConnectProxy proxy(
  28680. origin.port(), [](const std::string &head) -> std::string {
  28681. if (head.find(
  28682. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28683. std::string::npos) {
  28684. return proxy_tunnel_test::kTunnelEstablished;
  28685. }
  28686. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28687. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28688. "nonce=\"abc\", algorithm=MD5\r\n"
  28689. "Content-Length: 0\r\n\r\n";
  28690. });
  28691. ASSERT_NE(0, proxy.port());
  28692. ws::WebSocketClient client(origin.url());
  28693. client.set_proxy("127.0.0.1", proxy.port());
  28694. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28695. auto res = client.connect();
  28696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28697. std::string msg;
  28698. ASSERT_TRUE(client.read(msg));
  28699. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28700. client.close();
  28701. EXPECT_EQ(2, proxy.connect_hits());
  28702. }
  28703. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28704. proxy_tunnel_test::ScopedSSLServer origin;
  28705. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28706. origin.listen();
  28707. proxy_tunnel_test::ScopedConnectProxy proxy(
  28708. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28709. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28710. ASSERT_NE(0, proxy.port());
  28711. ws::WebSocketClient client(
  28712. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28713. client.enable_server_certificate_verification(false);
  28714. client.set_proxy("127.0.0.1", proxy.port());
  28715. client.set_proxy_bearer_token_auth("proxy-token");
  28716. auto res = client.connect();
  28717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28718. std::string msg;
  28719. ASSERT_TRUE(client.read(msg));
  28720. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28721. << "Proxy-Authorization must not be sent inside the tunnel";
  28722. client.close();
  28723. EXPECT_EQ(1, proxy.connect_hits());
  28724. }
  28725. #endif
  28726. // ---------------------------------------------------------------------------
  28727. // Poller
  28728. // ---------------------------------------------------------------------------
  28729. namespace poller_test {
  28730. struct PollerBackend {
  28731. const char *name;
  28732. std::unique_ptr<detail::Poller> (*create)();
  28733. };
  28734. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28735. *os << backend.name;
  28736. }
  28737. // Every backend runs the same contract tests. A new one is added here only.
  28738. std::vector<PollerBackend> poller_backends() {
  28739. return {
  28740. {"poll", &detail::PollPoller::create},
  28741. #ifdef __linux__
  28742. {"epoll", &detail::EpollPoller::create},
  28743. #endif
  28744. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28745. {"kqueue", &detail::KqueuePoller::create},
  28746. #endif
  28747. };
  28748. }
  28749. // A descriptor whose readability the test controls.
  28750. struct TestSocketPair {
  28751. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28752. TestSocketPair() { detail::create_socket_pair(fd); }
  28753. ~TestSocketPair() {
  28754. for (auto s : fd) {
  28755. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28756. }
  28757. }
  28758. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28759. socket_t reader() const { return fd[0]; }
  28760. void make_readable() {
  28761. const char c = 1;
  28762. detail::send_socket(fd[1], &c, 1, 0);
  28763. }
  28764. void close_writer() {
  28765. detail::close_socket(fd[1]);
  28766. fd[1] = INVALID_SOCKET;
  28767. }
  28768. };
  28769. using Tokens = std::vector<detail::Poller::Token>;
  28770. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28771. protected:
  28772. void SetUp() override {
  28773. poller_ = GetParam().create();
  28774. ASSERT_TRUE(poller_ != nullptr);
  28775. }
  28776. Tokens wait_for(int timeout_ms) {
  28777. Tokens ready;
  28778. poller_->wait(timeout_ms, ready);
  28779. std::sort(ready.begin(), ready.end());
  28780. return ready;
  28781. }
  28782. std::unique_ptr<detail::Poller> poller_;
  28783. };
  28784. } // namespace poller_test
  28785. using poller_test::PollerTest;
  28786. using poller_test::TestSocketPair;
  28787. using poller_test::Tokens;
  28788. INSTANTIATE_TEST_SUITE_P(
  28789. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28790. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28791. return std::string(p.param.name);
  28792. });
  28793. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28794. TestSocketPair sp;
  28795. ASSERT_TRUE(sp.ok());
  28796. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28797. EXPECT_EQ(Tokens{}, wait_for(0));
  28798. sp.make_readable();
  28799. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28800. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28801. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28802. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28803. }
  28804. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28805. TestSocketPair sp;
  28806. ASSERT_TRUE(sp.ok());
  28807. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28808. poller_->disarm(sp.reader());
  28809. poller_->disarm(sp.reader()); // disarming twice is harmless
  28810. sp.make_readable();
  28811. EXPECT_EQ(Tokens{}, wait_for(0));
  28812. }
  28813. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28814. TestSocketPair sp;
  28815. ASSERT_TRUE(sp.ok());
  28816. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28817. auto start = std::chrono::steady_clock::now();
  28818. EXPECT_EQ(Tokens{}, wait_for(30));
  28819. auto elapsed = std::chrono::steady_clock::now() - start;
  28820. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28821. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28822. }
  28823. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28824. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28825. for (detail::Poller::Token i = 0; i < 8; i++) {
  28826. sps.emplace_back(new TestSocketPair());
  28827. ASSERT_TRUE(sps.back()->ok());
  28828. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28829. }
  28830. sps[0]->make_readable();
  28831. sps[3]->make_readable();
  28832. sps[7]->make_readable();
  28833. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28834. // The others are still armed, the delivered ones are not.
  28835. sps[1]->make_readable();
  28836. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28837. EXPECT_EQ(Tokens{}, wait_for(0));
  28838. }
  28839. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28840. TestSocketPair s0, s1, s2;
  28841. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28842. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28843. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28844. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28845. // A delivery may move another entry inside the poller.
  28846. s0.make_readable();
  28847. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28848. // The entries left must still be found by descriptor.
  28849. poller_->disarm(s2.reader());
  28850. s1.make_readable();
  28851. s2.make_readable();
  28852. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28853. }
  28854. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  28855. TestSocketPair sp;
  28856. ASSERT_TRUE(sp.ok());
  28857. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  28858. sp.close_writer();
  28859. EXPECT_EQ(Tokens{5}, wait_for(1000));
  28860. char c;
  28861. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  28862. }
  28863. TEST_P(PollerTest, WakeEndsABlockedWait) {
  28864. std::thread waker([&] {
  28865. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  28866. poller_->wake();
  28867. });
  28868. Tokens ready;
  28869. auto start = std::chrono::steady_clock::now();
  28870. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  28871. waker.join();
  28872. EXPECT_TRUE(ready.empty());
  28873. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  28874. }
  28875. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  28876. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  28877. Tokens ready;
  28878. EXPECT_TRUE(poller_->wait(1000, ready));
  28879. }
  28880. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  28881. for (int i = 0; i < 1000; i++) {
  28882. poller_->wake();
  28883. }
  28884. Tokens ready;
  28885. EXPECT_TRUE(poller_->wait(0, ready));
  28886. EXPECT_FALSE(poller_->wait(0, ready));
  28887. poller_->wake();
  28888. EXPECT_TRUE(poller_->wait(0, ready));
  28889. }
  28890. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  28891. // Two threads publish changes and wake() after each, as a reactor's workers
  28892. // do. Every change must be seen without a wait() timing out. A lost wake()
  28893. // needs an unlucky interleaving, hence the rounds.
  28894. for (int round = 0; round < 5; round++) {
  28895. SCOPED_TRACE(round);
  28896. const int per_thread = 20000;
  28897. std::atomic<int> posted{0};
  28898. auto post = [&] {
  28899. for (int i = 0; i < per_thread; i++) {
  28900. posted++;
  28901. poller_->wake();
  28902. }
  28903. };
  28904. std::thread t1(post), t2(post);
  28905. auto lost = false;
  28906. Tokens ready;
  28907. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  28908. if (!poller_->wait(1000, ready)) {
  28909. lost = true;
  28910. break;
  28911. }
  28912. }
  28913. t1.join();
  28914. t2.join();
  28915. ASSERT_FALSE(lost);
  28916. }
  28917. }
  28918. TEST(PollerFactoryTest, MakePollerWorks) {
  28919. auto poller = detail::make_poller();
  28920. ASSERT_TRUE(poller != nullptr);
  28921. poller->wake();
  28922. std::vector<detail::Poller::Token> ready;
  28923. EXPECT_TRUE(poller->wait(1000, ready));
  28924. }
  28925. // ---------------------------------------------------------------------------
  28926. // Keep-alive parking
  28927. // ---------------------------------------------------------------------------
  28928. namespace parking_test {
  28929. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  28930. // runs once the port is bound and listening, before the server accepts.
  28931. struct RunningServer {
  28932. explicit RunningServer(
  28933. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  28934. : svr_(svr) {
  28935. port = svr_.bind_to_any_port("127.0.0.1");
  28936. if (before_listen) { before_listen(port); }
  28937. thread = std::thread([this] { svr_.listen_after_bind(); });
  28938. svr_.wait_until_ready();
  28939. }
  28940. ~RunningServer() {
  28941. svr_.stop();
  28942. if (thread.joinable()) { thread.join(); }
  28943. }
  28944. Server &svr_;
  28945. int port = 0;
  28946. std::thread thread;
  28947. };
  28948. struct Sockets {
  28949. std::vector<socket_t> socks;
  28950. ~Sockets() {
  28951. for (auto s : socks) {
  28952. detail::close_socket(s);
  28953. }
  28954. }
  28955. socket_t connect(int port) {
  28956. auto error = Error::Success;
  28957. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  28958. false, false, nullptr, 2, 0, 2, 0, 2,
  28959. 0, std::string(), error);
  28960. if (s != INVALID_SOCKET) { socks.push_back(s); }
  28961. return s;
  28962. }
  28963. };
  28964. std::chrono::steady_clock::time_point in_ms(int ms) {
  28965. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  28966. }
  28967. bool readable_by(socket_t sock,
  28968. std::chrono::steady_clock::time_point deadline) {
  28969. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  28970. deadline - std::chrono::steady_clock::now())
  28971. .count();
  28972. return left > 0 && detail::select_read(sock, 0, left) > 0;
  28973. }
  28974. bool send_get(socket_t sock, const std::string &path = "/") {
  28975. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  28976. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  28977. static_cast<ssize_t>(req.size());
  28978. }
  28979. // Reads one response whose body is "ok".
  28980. bool receives_ok(socket_t sock, int timeout_ms) {
  28981. auto deadline = in_ms(timeout_ms);
  28982. std::string buf;
  28983. while (readable_by(sock, deadline)) {
  28984. char tmp[1024];
  28985. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  28986. if (n <= 0) { return false; }
  28987. buf.append(tmp, static_cast<size_t>(n));
  28988. auto end = buf.find("\r\n\r\n");
  28989. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  28990. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  28991. buf.compare(end + 4, 2, "ok") == 0;
  28992. }
  28993. }
  28994. return false;
  28995. }
  28996. bool get_ok(socket_t sock, int timeout_ms) {
  28997. return send_get(sock) && receives_ok(sock, timeout_ms);
  28998. }
  28999. // Whether the server closes `sock` by `deadline`.
  29000. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29001. char c;
  29002. return readable_by(sock, deadline) &&
  29003. detail::read_socket(sock, &c, 1, 0) <= 0;
  29004. }
  29005. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29006. auto deadline = in_ms(timeout_ms);
  29007. while (!cond()) {
  29008. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29009. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29010. }
  29011. return true;
  29012. }
  29013. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29014. svr.new_task_queue = std::move(new_task_queue);
  29015. svr.set_keep_alive_parking(true);
  29016. svr.Get("/", [](const Request &, Response &res) {
  29017. res.set_content("ok", "text/plain");
  29018. });
  29019. }
  29020. std::function<TaskQueue *(void)> threads(size_t n) {
  29021. return [n] { return new ThreadPool(n); };
  29022. }
  29023. // Counts what the event loop managed to queue, so that a test can wait for it.
  29024. class CountingTaskQueue final : public TaskQueue {
  29025. public:
  29026. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29027. std::atomic<int> &full)
  29028. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29029. bool enqueue(std::function<void()> fn) override {
  29030. auto queued = pool_.enqueue([this, fn]() {
  29031. fn();
  29032. // Holds the worker back from taking the next job.
  29033. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29034. });
  29035. (queued ? ok_ : full_)++;
  29036. return queued;
  29037. }
  29038. void shutdown() override { pool_.shutdown(); }
  29039. std::atomic<int> pause_after_ms{0};
  29040. private:
  29041. ThreadPool pool_;
  29042. std::atomic<int> &ok_;
  29043. std::atomic<int> &full_;
  29044. };
  29045. // Holds handlers until it opens, or for 3 seconds at most.
  29046. class Gate {
  29047. public:
  29048. void wait() {
  29049. std::unique_lock<std::mutex> lock(m_);
  29050. entered_++;
  29051. cv_.notify_all();
  29052. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29053. }
  29054. void open() {
  29055. std::lock_guard<std::mutex> guard(m_);
  29056. open_ = true;
  29057. cv_.notify_all();
  29058. }
  29059. int entered() {
  29060. std::lock_guard<std::mutex> guard(m_);
  29061. return entered_;
  29062. }
  29063. private:
  29064. std::mutex m_;
  29065. std::condition_variable cv_;
  29066. bool open_ = false;
  29067. int entered_ = 0;
  29068. };
  29069. } // namespace parking_test
  29070. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29071. using namespace parking_test;
  29072. Server svr;
  29073. serve_ok(svr, threads(1));
  29074. RunningServer running(svr);
  29075. Sockets socks;
  29076. // One kept-alive connection that has been served, and many that have not
  29077. // sent anything yet. None of them may keep the only worker.
  29078. auto served = socks.connect(running.port);
  29079. ASSERT_TRUE(get_ok(served, 2000));
  29080. for (int i = 0; i < 49; i++) {
  29081. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29082. }
  29083. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29084. EXPECT_TRUE(get_ok(served, 1000));
  29085. }
  29086. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29087. using namespace parking_test;
  29088. Server svr;
  29089. serve_ok(svr, threads(1));
  29090. svr.set_keep_alive_timeout(1);
  29091. RunningServer running(svr);
  29092. Sockets socks;
  29093. for (int i = 0; i < 3; i++) {
  29094. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29095. }
  29096. // One worker waiting on each in turn would take about 3 seconds.
  29097. auto deadline = in_ms(2000);
  29098. for (auto s : socks.socks) {
  29099. EXPECT_TRUE(sees_eof(s, deadline));
  29100. }
  29101. }
  29102. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29103. using namespace parking_test;
  29104. std::atomic<int> queued{0}, full{0};
  29105. Server svr;
  29106. // One worker and room for one queued task.
  29107. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29108. Gate gate;
  29109. svr.Get("/block", [&](const Request &, Response &res) {
  29110. gate.wait();
  29111. res.set_content("ok", "text/plain");
  29112. });
  29113. RunningServer running(svr);
  29114. // Before the server stops, so that a failed run does not wait for the
  29115. // handler's timeout.
  29116. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29117. Sockets socks;
  29118. auto a = socks.connect(running.port);
  29119. ASSERT_TRUE(get_ok(a, 2000));
  29120. // B keeps the only worker busy.
  29121. auto b = socks.connect(running.port);
  29122. ASSERT_TRUE(send_get(b, "/block"));
  29123. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29124. // A new connection C fills the queue.
  29125. auto c = socks.connect(running.port);
  29126. ASSERT_TRUE(send_get(c));
  29127. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29128. // A's next request finds the queue full, but A has been served before, so it
  29129. // waits instead of being cut off.
  29130. ASSERT_TRUE(send_get(a));
  29131. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29132. gate.open();
  29133. EXPECT_TRUE(receives_ok(b, 2000));
  29134. EXPECT_TRUE(receives_ok(c, 2000));
  29135. EXPECT_TRUE(receives_ok(a, 2000));
  29136. }
  29137. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29138. using namespace parking_test;
  29139. std::atomic<int> queued{0}, full{0};
  29140. CountingTaskQueue *queue = nullptr;
  29141. Server svr;
  29142. // Two workers and room for one queued task.
  29143. serve_ok(svr,
  29144. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29145. Gate first, second;
  29146. svr.Get("/first", [&](const Request &, Response &res) {
  29147. first.wait();
  29148. res.set_content("ok", "text/plain");
  29149. });
  29150. svr.Get("/second", [&](const Request &, Response &res) {
  29151. second.wait();
  29152. res.set_content("ok", "text/plain");
  29153. });
  29154. RunningServer running(svr);
  29155. auto open_gates = detail::scope_exit([&] {
  29156. first.open();
  29157. second.open();
  29158. });
  29159. Sockets socks;
  29160. auto a = socks.connect(running.port);
  29161. ASSERT_TRUE(get_ok(a, 2000));
  29162. // B and D take both workers, and C fills the queue. One at a time: the
  29163. // queue has room for one job only until a worker takes it.
  29164. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29165. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29166. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29167. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29168. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29169. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29170. // A's next request waits in the backlog.
  29171. ASSERT_TRUE(send_get(a));
  29172. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29173. // B's worker finishes, then takes C off the queue only later, which makes
  29174. // room for A.
  29175. queue->pause_after_ms = 200;
  29176. first.open();
  29177. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29178. queue->pause_after_ms = 0;
  29179. second.open();
  29180. EXPECT_TRUE(receives_ok(a, 2000));
  29181. }
  29182. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29183. using namespace parking_test;
  29184. Server svr;
  29185. serve_ok(svr, threads(1));
  29186. svr.set_keep_alive_timeout(0);
  29187. // The request is on the socket before the server accepts the connection,
  29188. // so it does not race the 10 ms floor. Without the floor the connection is
  29189. // closed unread.
  29190. Sockets socks;
  29191. auto sock = INVALID_SOCKET;
  29192. RunningServer running(svr, [&](int port) {
  29193. sock = socks.connect(port);
  29194. send_get(sock);
  29195. });
  29196. EXPECT_TRUE(receives_ok(sock, 1000));
  29197. }
  29198. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29199. using namespace parking_test;
  29200. for (int round = 0; round < 5; round++) {
  29201. SCOPED_TRACE(round);
  29202. Server svr;
  29203. serve_ok(svr, threads(2));
  29204. RunningServer running(svr);
  29205. Sockets socks;
  29206. for (int i = 0; i < 20; i++) {
  29207. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29208. }
  29209. auto start = std::chrono::steady_clock::now();
  29210. svr.stop();
  29211. running.thread.join();
  29212. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29213. std::chrono::milliseconds(500));
  29214. auto deadline = in_ms(1000);
  29215. for (auto s : socks.socks) {
  29216. EXPECT_TRUE(sees_eof(s, deadline));
  29217. }
  29218. }
  29219. }
  29220. #ifdef CPPHTTPLIB_SSL_ENABLED
  29221. namespace parking_test {
  29222. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29223. // that has opened a connection ahead of time. Freeing the session sends no
  29224. // close_notify, so the connection stays quiet.
  29225. bool handshake_only(socket_t sock) {
  29226. auto ctx = tls::create_client_context();
  29227. tls::set_verify_client(ctx, false);
  29228. auto session = tls::create_session(ctx, sock);
  29229. auto se = detail::scope_exit([&] {
  29230. tls::free_session(session);
  29231. tls::free_context(ctx);
  29232. });
  29233. tls::TlsError err;
  29234. return session &&
  29235. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29236. }
  29237. Client tls_client(int port) {
  29238. Client cli("https://127.0.0.1:" + std::to_string(port));
  29239. cli.enable_server_certificate_verification(false);
  29240. cli.set_keep_alive(true);
  29241. cli.set_connection_timeout(1);
  29242. cli.set_read_timeout(1);
  29243. return cli;
  29244. }
  29245. bool tls_get_ok(Client &cli) {
  29246. auto res = cli.Get("/");
  29247. return res && res->body == "ok";
  29248. }
  29249. } // namespace parking_test
  29250. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29251. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29252. struct {
  29253. unsigned long version;
  29254. bool safe;
  29255. } cases[] = {
  29256. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29257. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29258. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29259. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29260. };
  29261. for (const auto &c : cases) {
  29262. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29263. << std::hex << c.version;
  29264. }
  29265. }
  29266. #endif
  29267. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29268. using namespace parking_test;
  29269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29270. ASSERT_TRUE(svr.is_valid());
  29271. serve_ok(svr, threads(1));
  29272. svr.set_read_timeout(1); // so that a failing run does not take long
  29273. RunningServer running(svr);
  29274. Sockets socks;
  29275. // One served connection, some that have not started their handshake, and
  29276. // one that has finished it and gone quiet. None may keep the only worker.
  29277. auto served = tls_client(running.port);
  29278. ASSERT_TRUE(tls_get_ok(served));
  29279. for (int i = 0; i < 10; i++) {
  29280. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29281. }
  29282. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29283. auto other = tls_client(running.port);
  29284. EXPECT_TRUE(tls_get_ok(other));
  29285. EXPECT_TRUE(tls_get_ok(served));
  29286. }
  29287. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29288. using namespace parking_test;
  29289. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29290. ASSERT_TRUE(svr.is_valid());
  29291. serve_ok(svr, threads(1));
  29292. RunningServer running(svr);
  29293. Sockets socks;
  29294. auto plain = socks.connect(running.port);
  29295. ASSERT_TRUE(send_get(plain));
  29296. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29297. EXPECT_NE(0, svr.ssl_last_error());
  29298. }
  29299. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29300. using namespace parking_test;
  29301. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29302. ASSERT_TRUE(svr.is_valid());
  29303. serve_ok(svr, threads(2));
  29304. RunningServer running(svr);
  29305. std::vector<Client> clients;
  29306. for (int i = 0; i < 5; i++) {
  29307. clients.push_back(tls_client(running.port));
  29308. ASSERT_TRUE(tls_get_ok(clients.back()));
  29309. }
  29310. auto start = std::chrono::steady_clock::now();
  29311. svr.stop();
  29312. running.thread.join();
  29313. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29314. std::chrono::milliseconds(500));
  29315. }
  29316. #endif