test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621
  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. // Keep-alive parking would wait for the ClientHello without a handshake.
  4933. svr.set_keep_alive_parking(false);
  4934. svr.Get("/test", [](const Request &, Response &res) {
  4935. res.set_content("ok", "text/plain");
  4936. });
  4937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4938. auto se = detail::scope_exit([&] {
  4939. svr.stop();
  4940. t.join();
  4941. ASSERT_FALSE(svr.is_running());
  4942. });
  4943. svr.wait_until_ready();
  4944. // A connection that sends no ClientHello keeps its handshake in progress,
  4945. // once the server has had a moment to start it.
  4946. auto error = Error::Success;
  4947. auto sock = detail::create_client_socket(
  4948. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4949. /*connection_timeout_sec=*/5, 0,
  4950. /*read_timeout_sec=*/5, 0,
  4951. /*write_timeout_sec=*/5, 0, std::string(), error);
  4952. ASSERT_NE(INVALID_SOCKET, sock);
  4953. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4954. std::string cert_pem, key_pem;
  4955. read_file(SERVER_CERT_FILE, cert_pem);
  4956. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4957. auto update = std::async(std::launch::async, [&]() {
  4958. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4959. });
  4960. EXPECT_EQ(std::future_status::timeout,
  4961. update.wait_for(std::chrono::milliseconds(200)));
  4962. detail::close_socket(sock);
  4963. EXPECT_TRUE(update.get());
  4964. SSLClient cli(HOST, PORT);
  4965. cli.enable_server_certificate_verification(false);
  4966. auto res = cli.Get("/test");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. }
  4970. #endif
  4971. TEST(ErrorHandlerTest, ContentLength) {
  4972. Server svr;
  4973. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4974. res.status = StatusCode::OK_200;
  4975. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4976. "text/html"); // <= Content-Length still 13
  4977. });
  4978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4979. res.set_content("Hello World!\n", "text/plain");
  4980. res.status = 524;
  4981. });
  4982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4983. auto se = detail::scope_exit([&] {
  4984. svr.stop();
  4985. thread.join();
  4986. ASSERT_FALSE(svr.is_running());
  4987. });
  4988. svr.wait_until_ready();
  4989. {
  4990. Client cli(HOST, PORT);
  4991. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4995. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4996. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4997. }
  4998. }
  4999. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5000. TEST(ExceptionTest, WithoutExceptionHandler) {
  5001. Server svr;
  5002. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5003. throw std::runtime_error("exception...");
  5004. });
  5005. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5006. throw std::runtime_error("exception\r\n...");
  5007. });
  5008. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. listen_thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli("localhost", PORT);
  5016. {
  5017. auto res = cli.Get("/exception");
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5020. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5021. }
  5022. {
  5023. auto res = cli.Get("/unknown");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5026. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5027. }
  5028. }
  5029. TEST(ExceptionTest, WithExceptionHandler) {
  5030. Server svr;
  5031. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5032. std::exception_ptr ep) {
  5033. EXPECT_FALSE(ep == nullptr);
  5034. try {
  5035. std::rethrow_exception(ep);
  5036. } catch (std::exception &e) {
  5037. EXPECT_EQ("abc", std::string(e.what()));
  5038. } catch (...) {}
  5039. res.status = StatusCode::InternalServerError_500;
  5040. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5041. "text/html"); // <= Content-Length still 13 at this point
  5042. });
  5043. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5044. res.set_content("Hello World!\n", "text/plain");
  5045. throw std::runtime_error("abc");
  5046. });
  5047. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5048. auto se = detail::scope_exit([&] {
  5049. svr.stop();
  5050. thread.join();
  5051. ASSERT_FALSE(svr.is_running());
  5052. });
  5053. svr.wait_until_ready();
  5054. for (size_t i = 0; i < 10; i++) {
  5055. Client cli(HOST, PORT);
  5056. for (size_t j = 0; j < 100; j++) {
  5057. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5059. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5060. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5061. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5063. }
  5064. cli.set_keep_alive(true);
  5065. for (size_t j = 0; j < 100; j++) {
  5066. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5068. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5069. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5070. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5071. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5072. }
  5073. }
  5074. }
  5075. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5076. Server svr;
  5077. svr.set_exception_handler(
  5078. [](const Request &, Response &res, std::exception_ptr) {
  5079. res.set_content("oops", "text/plain");
  5080. });
  5081. svr.Get("/throw", [](const Request &, Response &) {
  5082. throw std::runtime_error("throw");
  5083. });
  5084. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5085. res.status = StatusCode::Created_201;
  5086. throw std::runtime_error("created-then-throw");
  5087. });
  5088. auto port = svr.bind_to_any_port(HOST);
  5089. ASSERT_GT(port, 0);
  5090. thread t = thread([&] { svr.listen_after_bind(); });
  5091. auto se = detail::scope_exit([&] {
  5092. svr.stop();
  5093. t.join();
  5094. ASSERT_FALSE(svr.is_running());
  5095. });
  5096. svr.wait_until_ready();
  5097. Client cli(HOST, port);
  5098. for (auto path : {"/throw", "/created-then-throw"}) {
  5099. auto res = cli.Get(path);
  5100. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5101. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5102. }
  5103. }
  5104. TEST(ExceptionTest, AndErrorHandler) {
  5105. Server svr;
  5106. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5107. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5108. });
  5109. svr.set_exception_handler(
  5110. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5111. EXPECT_FALSE(ep == nullptr);
  5112. try {
  5113. std::rethrow_exception(ep);
  5114. } catch (std::exception &e) {
  5115. res.set_content(e.what(), "text/html");
  5116. } catch (...) {}
  5117. res.status = StatusCode::InternalServerError_500;
  5118. });
  5119. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5120. throw std::runtime_error("EXCEPTION");
  5121. });
  5122. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5123. res.set_content("ERROR", "text/html");
  5124. res.status = StatusCode::InternalServerError_500;
  5125. });
  5126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5127. auto se = detail::scope_exit([&] {
  5128. svr.stop();
  5129. thread.join();
  5130. ASSERT_FALSE(svr.is_running());
  5131. });
  5132. svr.wait_until_ready();
  5133. Client cli(HOST, PORT);
  5134. {
  5135. auto res = cli.Get("/exception");
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5138. EXPECT_EQ("EXCEPTION", res->body);
  5139. }
  5140. {
  5141. auto res = cli.Get("/error");
  5142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5143. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5144. EXPECT_EQ("ERROR", res->body);
  5145. }
  5146. {
  5147. auto res = cli.Get("/invalid");
  5148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5150. EXPECT_EQ("NOT_FOUND", res->body);
  5151. }
  5152. }
  5153. #endif
  5154. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5155. // An exception from a user callback outside process_request()'s try/catch
  5156. // used to unwind into the task queue - which does not catch - and terminate
  5157. // the process. Each test below runs the server on a single worker thread: a
  5158. // guard that catches the exception but still loses the thread would otherwise
  5159. // be hidden by a spare worker serving the follow-up request. Note that a
  5160. // regression here aborts the whole test binary rather than failing one test.
  5161. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5162. Server svr;
  5163. svr.new_task_queue = [] { return new ThreadPool(1); };
  5164. std::atomic<int> reported{0};
  5165. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5166. if (err == Error::UserCallbackException) { reported++; }
  5167. });
  5168. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5169. res.set_content_provider(
  5170. 1024, "text/plain",
  5171. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5172. sink.write("hello", 5);
  5173. throw std::runtime_error("from the content provider");
  5174. });
  5175. });
  5176. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5177. res.set_content("ok", "text/plain");
  5178. });
  5179. auto port = svr.bind_to_any_port(HOST);
  5180. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5181. auto se = detail::scope_exit([&] {
  5182. svr.stop();
  5183. listen_thread.join();
  5184. ASSERT_FALSE(svr.is_running());
  5185. });
  5186. svr.wait_until_ready();
  5187. {
  5188. Client cli(HOST, port);
  5189. cli.set_read_timeout(5, 0);
  5190. EXPECT_FALSE(cli.Get("/throw"));
  5191. }
  5192. EXPECT_TRUE(svr.is_running());
  5193. EXPECT_EQ(1, reported.load());
  5194. // A request on a fresh connection is still served.
  5195. {
  5196. Client cli(HOST, port);
  5197. auto res = cli.Get("/ok");
  5198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. EXPECT_EQ("ok", res->body);
  5201. }
  5202. }
  5203. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5204. Server svr;
  5205. svr.new_task_queue = [] { return new ThreadPool(1); };
  5206. std::atomic<bool> should_throw{true};
  5207. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5208. res.set_content("hi", "text/plain");
  5209. });
  5210. svr.set_post_routing_handler(
  5211. [&](const Request & /*req*/, Response & /*res*/) {
  5212. if (should_throw) {
  5213. throw std::runtime_error("from the post-routing handler");
  5214. }
  5215. });
  5216. auto port = svr.bind_to_any_port(HOST);
  5217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5218. auto se = detail::scope_exit([&] {
  5219. svr.stop();
  5220. listen_thread.join();
  5221. ASSERT_FALSE(svr.is_running());
  5222. });
  5223. svr.wait_until_ready();
  5224. {
  5225. Client cli(HOST, port);
  5226. cli.set_read_timeout(5, 0);
  5227. EXPECT_FALSE(cli.Get("/hi"));
  5228. }
  5229. EXPECT_TRUE(svr.is_running());
  5230. should_throw = false;
  5231. {
  5232. Client cli(HOST, port);
  5233. auto res = cli.Get("/hi");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. EXPECT_EQ("hi", res->body);
  5237. }
  5238. }
  5239. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5240. // The guard reports the caught exception through the error logger, which is
  5241. // a user callback too. A logger that throws has to be contained as well, or
  5242. // the process would terminate from inside the catch.
  5243. Server svr;
  5244. svr.new_task_queue = [] { return new ThreadPool(1); };
  5245. std::atomic<int> reported{0};
  5246. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5247. if (err == Error::UserCallbackException) {
  5248. reported++;
  5249. throw std::runtime_error("from the error logger");
  5250. }
  5251. });
  5252. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5253. res.set_content_provider(
  5254. 1024, "text/plain",
  5255. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5256. sink.write("hello", 5);
  5257. throw std::runtime_error("from the content provider");
  5258. });
  5259. });
  5260. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5261. res.set_content("ok", "text/plain");
  5262. });
  5263. auto port = svr.bind_to_any_port(HOST);
  5264. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5265. auto se = detail::scope_exit([&] {
  5266. svr.stop();
  5267. listen_thread.join();
  5268. ASSERT_FALSE(svr.is_running());
  5269. });
  5270. svr.wait_until_ready();
  5271. {
  5272. Client cli(HOST, port);
  5273. cli.set_read_timeout(5, 0);
  5274. EXPECT_FALSE(cli.Get("/throw"));
  5275. }
  5276. EXPECT_TRUE(svr.is_running());
  5277. EXPECT_EQ(1, reported.load());
  5278. {
  5279. Client cli(HOST, port);
  5280. auto res = cli.Get("/ok");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. EXPECT_EQ(StatusCode::OK_200, res->status);
  5283. EXPECT_EQ("ok", res->body);
  5284. }
  5285. }
  5286. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5287. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5288. // so the exception unwinds through the ws::WebSocket object on its way to
  5289. // the guard. None of the HTTP cases above cross that.
  5290. Server svr;
  5291. svr.new_task_queue = [] { return new ThreadPool(1); };
  5292. std::atomic<int> reported{0};
  5293. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5294. if (err == Error::UserCallbackException) { reported++; }
  5295. });
  5296. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5297. throw std::runtime_error("from the WebSocket handler");
  5298. });
  5299. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5300. res.set_content("ok", "text/plain");
  5301. });
  5302. auto port = svr.bind_to_any_port(HOST);
  5303. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5304. auto se = detail::scope_exit([&] {
  5305. svr.stop();
  5306. listen_thread.join();
  5307. ASSERT_FALSE(svr.is_running());
  5308. });
  5309. svr.wait_until_ready();
  5310. {
  5311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5312. "/ws");
  5313. auto res = client.connect();
  5314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5315. // The server dropped the connection instead of dying.
  5316. std::string msg;
  5317. EXPECT_FALSE(client.read(msg));
  5318. client.close();
  5319. }
  5320. EXPECT_TRUE(svr.is_running());
  5321. EXPECT_EQ(1, reported.load());
  5322. {
  5323. Client cli(HOST, port);
  5324. auto res = cli.Get("/ok");
  5325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5326. EXPECT_EQ(StatusCode::OK_200, res->status);
  5327. EXPECT_EQ("ok", res->body);
  5328. }
  5329. }
  5330. #ifdef CPPHTTPLIB_SSL_ENABLED
  5331. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5332. // SSLServer::process_and_close_socket() is a separate overload with its own
  5333. // guard, so it is exercised on its own.
  5334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5335. ASSERT_TRUE(svr.is_valid());
  5336. svr.new_task_queue = [] { return new ThreadPool(1); };
  5337. std::atomic<int> reported{0};
  5338. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5339. if (err == Error::UserCallbackException) { reported++; }
  5340. });
  5341. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5342. res.set_content_provider(
  5343. 1024, "text/plain",
  5344. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5345. sink.write("hello", 5);
  5346. throw std::runtime_error("from the content provider");
  5347. });
  5348. });
  5349. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5350. res.set_content("ok", "text/plain");
  5351. });
  5352. auto port = svr.bind_to_any_port(HOST);
  5353. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5354. auto se = detail::scope_exit([&] {
  5355. svr.stop();
  5356. listen_thread.join();
  5357. ASSERT_FALSE(svr.is_running());
  5358. });
  5359. svr.wait_until_ready();
  5360. {
  5361. SSLClient cli(HOST, port);
  5362. cli.enable_server_certificate_verification(false);
  5363. cli.set_read_timeout(5, 0);
  5364. EXPECT_FALSE(cli.Get("/throw"));
  5365. }
  5366. EXPECT_TRUE(svr.is_running());
  5367. EXPECT_EQ(1, reported.load());
  5368. {
  5369. SSLClient cli(HOST, port);
  5370. cli.enable_server_certificate_verification(false);
  5371. auto res = cli.Get("/ok");
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::OK_200, res->status);
  5374. EXPECT_EQ("ok", res->body);
  5375. }
  5376. }
  5377. #endif
  5378. #endif
  5379. TEST(NoContentTest, ContentLength) {
  5380. Server svr;
  5381. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5382. res.status = StatusCode::NoContent_204;
  5383. });
  5384. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5385. auto se = detail::scope_exit([&] {
  5386. svr.stop();
  5387. thread.join();
  5388. ASSERT_FALSE(svr.is_running());
  5389. });
  5390. svr.wait_until_ready();
  5391. {
  5392. Client cli(HOST, PORT);
  5393. auto res = cli.Get("/hi");
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5396. // RFC 9110 8.6: none in a 204 response
  5397. EXPECT_FALSE(res->has_header("Content-Length"));
  5398. }
  5399. }
  5400. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5401. Server svr;
  5402. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5403. res.set_header("Content-Length", "5");
  5404. res.set_content("hello world", "text/plain");
  5405. });
  5406. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5407. // A body that reads as the last chunk, were it taken as chunked
  5408. res.set_header("Transfer-Encoding", "chunked");
  5409. res.set_content("0\r\n\r\n", "text/plain");
  5410. });
  5411. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5412. res.set_header("Content-Length", "2");
  5413. res.set_content_provider(5, "text/plain",
  5414. [](size_t offset, size_t length, DataSink &sink) {
  5415. sink.write(&"hello"[offset], length);
  5416. return true;
  5417. });
  5418. });
  5419. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5420. res.set_header("Content-Length", "1234");
  5421. });
  5422. thread t = thread([&] { svr.listen(HOST, PORT); });
  5423. auto se = detail::scope_exit([&] {
  5424. svr.stop();
  5425. t.join();
  5426. ASSERT_FALSE(svr.is_running());
  5427. });
  5428. svr.wait_until_ready();
  5429. Client cli(HOST, PORT);
  5430. cli.set_read_timeout(1, 0);
  5431. auto expect_body = [&](const Result &res, const std::string &body) {
  5432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5433. EXPECT_EQ(body, res->body);
  5434. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5435. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5436. };
  5437. Headers identity{{"Accept-Encoding", ""}};
  5438. expect_body(cli.Get("/body", identity), "hello world");
  5439. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5440. expect_body(cli.Get("/body",
  5441. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5442. "he");
  5443. expect_body(cli.Get("/provider", identity), "hello");
  5444. expect_body(cli.Get("/empty", identity), "");
  5445. // A HEAD response may give the length of the body a GET would get.
  5446. auto res = cli.Head("/empty");
  5447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5448. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5449. }
  5450. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5451. Server svr;
  5452. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5453. res.set_content("short", "text/plain");
  5454. });
  5455. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5456. res.body += " with a footer";
  5457. res.set_header("Transfer-Encoding", "chunked");
  5458. });
  5459. thread t = thread([&] { svr.listen(HOST, PORT); });
  5460. auto se = detail::scope_exit([&] {
  5461. svr.stop();
  5462. t.join();
  5463. ASSERT_FALSE(svr.is_running());
  5464. });
  5465. svr.wait_until_ready();
  5466. Client cli(HOST, PORT);
  5467. cli.set_read_timeout(1, 0);
  5468. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5470. EXPECT_EQ("short with a footer", res->body);
  5471. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5472. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5473. }
  5474. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5475. Server svr;
  5476. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5477. res.set_header("Content-Length", "3");
  5478. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5479. sink.write("abc", 3);
  5480. sink.done();
  5481. return true;
  5482. });
  5483. });
  5484. thread t = thread([&] { svr.listen(HOST, PORT); });
  5485. auto se = detail::scope_exit([&] {
  5486. svr.stop();
  5487. t.join();
  5488. ASSERT_FALSE(svr.is_running());
  5489. });
  5490. svr.wait_until_ready();
  5491. Client cli(HOST, PORT);
  5492. cli.set_keep_alive(true);
  5493. auto res = cli.Get("/");
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. EXPECT_EQ("abc", res->body);
  5496. EXPECT_FALSE(res->has_header("Content-Length"));
  5497. EXPECT_EQ("close", res->get_header_value("Connection"));
  5498. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5499. // No body to delimit
  5500. auto head = cli.Head("/");
  5501. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5502. EXPECT_FALSE(head->has_header("Connection"));
  5503. }
  5504. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5505. #ifdef CPPHTTPLIB_SSL_ENABLED
  5506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5507. ASSERT_TRUE(svr.is_valid());
  5508. #else
  5509. Server svr;
  5510. #endif
  5511. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5512. if (req.path == "/routing_handler") {
  5513. res.set_header("PRE_ROUTING", "on");
  5514. res.set_content("Routing Handler", "text/plain");
  5515. return httplib::Server::HandlerResponse::Handled;
  5516. }
  5517. return httplib::Server::HandlerResponse::Unhandled;
  5518. });
  5519. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5520. res.set_content("Error", "text/html");
  5521. });
  5522. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5523. if (req.path == "/routing_handler") {
  5524. res.set_header("POST_ROUTING", "on");
  5525. }
  5526. });
  5527. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5528. res.set_content("Hello World!\n", "text/plain");
  5529. });
  5530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5531. auto se = detail::scope_exit([&] {
  5532. svr.stop();
  5533. thread.join();
  5534. ASSERT_FALSE(svr.is_running());
  5535. });
  5536. svr.wait_until_ready();
  5537. {
  5538. #ifdef CPPHTTPLIB_SSL_ENABLED
  5539. SSLClient cli(HOST, PORT);
  5540. cli.enable_server_certificate_verification(false);
  5541. #else
  5542. Client cli(HOST, PORT);
  5543. #endif
  5544. auto res = cli.Get("/routing_handler");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. EXPECT_EQ("Routing Handler", res->body);
  5548. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5549. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5550. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5551. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5552. }
  5553. {
  5554. #ifdef CPPHTTPLIB_SSL_ENABLED
  5555. SSLClient cli(HOST, PORT);
  5556. cli.enable_server_certificate_verification(false);
  5557. #else
  5558. Client cli(HOST, PORT);
  5559. #endif
  5560. auto res = cli.Get("/hi");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ("Hello World!\n", res->body);
  5564. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5565. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5566. }
  5567. {
  5568. #ifdef CPPHTTPLIB_SSL_ENABLED
  5569. SSLClient cli(HOST, PORT);
  5570. cli.enable_server_certificate_verification(false);
  5571. #else
  5572. Client cli(HOST, PORT);
  5573. #endif
  5574. auto res = cli.Get("/aaa");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5577. EXPECT_EQ("Error", res->body);
  5578. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5579. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5580. }
  5581. }
  5582. TEST(RequestHandlerTest, PreRequestHandler) {
  5583. auto route_path = "/user/:user";
  5584. Server svr;
  5585. svr.Get("/hi", [](const Request &, Response &res) {
  5586. res.set_content("hi", "text/plain");
  5587. });
  5588. svr.Get(route_path, [](const Request &req, Response &res) {
  5589. res.set_content(req.path_params.at("user"), "text/plain");
  5590. });
  5591. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5592. if (req.matched_route == route_path) {
  5593. auto user = req.path_params.at("user");
  5594. if (user != "john") {
  5595. res.status = StatusCode::Forbidden_403;
  5596. res.set_content("error", "text/html");
  5597. return Server::HandlerResponse::Handled;
  5598. }
  5599. }
  5600. return Server::HandlerResponse::Unhandled;
  5601. });
  5602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5603. auto se = detail::scope_exit([&] {
  5604. svr.stop();
  5605. thread.join();
  5606. ASSERT_FALSE(svr.is_running());
  5607. });
  5608. svr.wait_until_ready();
  5609. Client cli(HOST, PORT);
  5610. {
  5611. auto res = cli.Get("/hi");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::OK_200, res->status);
  5614. EXPECT_EQ("hi", res->body);
  5615. }
  5616. {
  5617. auto res = cli.Get("/user/john");
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. EXPECT_EQ("john", res->body);
  5621. }
  5622. {
  5623. auto res = cli.Get("/user/invalid-user");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5626. EXPECT_EQ("error", res->body);
  5627. }
  5628. }
  5629. // The pre-request handler must run before the request body is read, so a
  5630. // rejected request never forces the server to buffer a (potentially large)
  5631. // body. Here the posted body is larger than the payload limit: if the body
  5632. // were read first the server would answer 413, but because the pre-request
  5633. // handler runs first it answers 403 and the body is never read.
  5634. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5635. Server svr;
  5636. svr.set_payload_max_length(8);
  5637. auto handler_ran = false;
  5638. svr.Post("/reject", [&](const Request &req, Response &res) {
  5639. handler_ran = true;
  5640. res.set_content(req.body, "text/plain");
  5641. });
  5642. svr.Post("/accept", [](const Request &req, Response &res) {
  5643. res.set_content(req.body, "text/plain");
  5644. });
  5645. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5646. if (req.matched_route == "/reject") {
  5647. res.status = StatusCode::Forbidden_403;
  5648. res.set_content("denied", "text/plain");
  5649. return Server::HandlerResponse::Handled;
  5650. }
  5651. return Server::HandlerResponse::Unhandled;
  5652. });
  5653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5654. auto se = detail::scope_exit([&] {
  5655. svr.stop();
  5656. thread.join();
  5657. ASSERT_FALSE(svr.is_running());
  5658. });
  5659. svr.wait_until_ready();
  5660. Client cli(HOST, PORT);
  5661. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5662. // rejects with 403 before the body is read, so 413 is never reached.
  5663. {
  5664. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5667. EXPECT_EQ("denied", res->body);
  5668. EXPECT_FALSE(handler_ran);
  5669. }
  5670. // An approved route still reads the body and enforces the payload limit.
  5671. {
  5672. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5675. }
  5676. }
  5677. TEST(UserDataTest, BasicOperations) {
  5678. httplib::UserData ud;
  5679. // Initially empty
  5680. EXPECT_FALSE(ud.has("key"));
  5681. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5682. // set and get
  5683. ud.set("key", 42);
  5684. EXPECT_TRUE(ud.has("key"));
  5685. auto *p = ud.get<int>("key");
  5686. ASSERT_NE(nullptr, p);
  5687. EXPECT_EQ(42, *p);
  5688. // Type mismatch → nullptr
  5689. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5690. // Overwrite with different type
  5691. ud.set("key", std::string("hello"));
  5692. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5693. auto *s = ud.get<std::string>("key");
  5694. ASSERT_NE(nullptr, s);
  5695. EXPECT_EQ("hello", *s);
  5696. // erase
  5697. ud.erase("key");
  5698. EXPECT_FALSE(ud.has("key"));
  5699. // clear
  5700. ud.set("a", 1);
  5701. ud.set("b", 2);
  5702. ud.clear();
  5703. EXPECT_FALSE(ud.has("a"));
  5704. EXPECT_FALSE(ud.has("b"));
  5705. }
  5706. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5707. struct AuthCtx {
  5708. std::string user_id;
  5709. };
  5710. Server svr;
  5711. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5712. res.user_data.set("auth", AuthCtx{"alice"});
  5713. return Server::HandlerResponse::Unhandled;
  5714. });
  5715. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5716. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5717. ASSERT_NE(nullptr, ctx);
  5718. res.set_content("Hello " + ctx->user_id, "text/plain");
  5719. });
  5720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5721. auto se = detail::scope_exit([&] {
  5722. svr.stop();
  5723. thread.join();
  5724. ASSERT_FALSE(svr.is_running());
  5725. });
  5726. svr.wait_until_ready();
  5727. Client cli(HOST, PORT);
  5728. auto res = cli.Get("/me");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. EXPECT_EQ("Hello alice", res->body);
  5732. }
  5733. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5734. struct RoleCtx {
  5735. std::string role;
  5736. };
  5737. Server svr;
  5738. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5739. res.user_data.set("role", RoleCtx{"admin"});
  5740. return Server::HandlerResponse::Unhandled;
  5741. });
  5742. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5743. auto *ctx = res.user_data.get<RoleCtx>("role");
  5744. ASSERT_NE(nullptr, ctx);
  5745. res.set_content(ctx->role, "text/plain");
  5746. });
  5747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5748. auto se = detail::scope_exit([&] {
  5749. svr.stop();
  5750. thread.join();
  5751. ASSERT_FALSE(svr.is_running());
  5752. });
  5753. svr.wait_until_ready();
  5754. Client cli(HOST, PORT);
  5755. auto res = cli.Get("/role");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. EXPECT_EQ("admin", res->body);
  5759. }
  5760. TEST(InvalidFormatTest, StatusCode) {
  5761. Server svr;
  5762. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5763. res.set_content("Hello World!\n", "text/plain");
  5764. res.status = 9999; // Status should be a three-digit code...
  5765. });
  5766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5767. auto se = detail::scope_exit([&] {
  5768. svr.stop();
  5769. thread.join();
  5770. ASSERT_FALSE(svr.is_running());
  5771. });
  5772. svr.wait_until_ready();
  5773. {
  5774. Client cli(HOST, PORT);
  5775. auto res = cli.Get("/hi");
  5776. ASSERT_FALSE(res);
  5777. }
  5778. }
  5779. TEST(URLFragmentTest, WithFragment) {
  5780. Server svr;
  5781. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5782. EXPECT_TRUE(req.target == "/hi");
  5783. });
  5784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5785. auto se = detail::scope_exit([&] {
  5786. svr.stop();
  5787. thread.join();
  5788. ASSERT_FALSE(svr.is_running());
  5789. });
  5790. svr.wait_until_ready();
  5791. {
  5792. Client cli(HOST, PORT);
  5793. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5794. EXPECT_TRUE(res);
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. res = cli.Get("/hi%23key1=val1=key2=val2");
  5797. EXPECT_TRUE(res);
  5798. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5799. }
  5800. }
  5801. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5802. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5803. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5804. Server svr;
  5805. std::vector<std::string> targets;
  5806. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5807. targets.push_back(req.target);
  5808. });
  5809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5810. auto se = detail::scope_exit([&] {
  5811. svr.stop();
  5812. thread.join();
  5813. ASSERT_FALSE(svr.is_running());
  5814. });
  5815. svr.wait_until_ready();
  5816. Client cli(HOST, PORT);
  5817. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5818. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5819. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5820. // A '?' after the '#' belongs to the fragment, not to the query.
  5821. Request req;
  5822. req.method = "GET";
  5823. req.path = "/hi#f?x=1";
  5824. req.params.emplace("a", "1");
  5825. Response res;
  5826. auto error = Error::Success;
  5827. EXPECT_TRUE(cli.send(req, res, error));
  5828. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5829. "/hi?a=1"}),
  5830. targets);
  5831. }
  5832. TEST(HeaderWriter, SetHeaderWriter) {
  5833. Server svr;
  5834. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5835. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5836. return detail::write_headers(strm, hdrs);
  5837. });
  5838. svr.Get("/hi", [](const Request &req, Response &res) {
  5839. auto it = req.headers.find("CustomClientHeader");
  5840. EXPECT_TRUE(it != req.headers.end());
  5841. EXPECT_EQ(it->second, "CustomClientValue");
  5842. res.set_content("Hello World!\n", "text/plain");
  5843. });
  5844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5845. auto se = detail::scope_exit([&] {
  5846. svr.stop();
  5847. thread.join();
  5848. ASSERT_FALSE(svr.is_running());
  5849. });
  5850. svr.wait_until_ready();
  5851. {
  5852. Client cli(HOST, PORT);
  5853. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5854. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5855. return detail::write_headers(strm, hdrs);
  5856. });
  5857. auto res = cli.Get("/hi");
  5858. EXPECT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. auto it = res->headers.find("CustomServerHeader");
  5861. EXPECT_TRUE(it != res->headers.end());
  5862. EXPECT_EQ(it->second, "CustomServerValue");
  5863. }
  5864. }
  5865. class ServerTest : public ::testing::Test {
  5866. protected:
  5867. ServerTest()
  5868. : cli_(HOST, PORT)
  5869. #ifdef CPPHTTPLIB_SSL_ENABLED
  5870. ,
  5871. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5872. #endif
  5873. {
  5874. #ifdef CPPHTTPLIB_SSL_ENABLED
  5875. cli_.enable_server_certificate_verification(false);
  5876. #endif
  5877. // Allow LARGE_DATA (100MB) responses
  5878. cli_.set_payload_max_length(200 * 1024 * 1024);
  5879. }
  5880. virtual void SetUp() {
  5881. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5882. svr_.set_payload_max_length(200 * 1024 * 1024);
  5883. svr_.set_mount_point("/", "./www");
  5884. svr_.set_mount_point("/mount", "./www2");
  5885. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5886. svr_.Get("/hi",
  5887. [&](const Request & /*req*/, Response &res) {
  5888. res.set_content("Hello World!", "text/plain");
  5889. })
  5890. .Get("/file_content",
  5891. [&](const Request & /*req*/, Response &res) {
  5892. res.set_file_content("./www/dir/test.html");
  5893. })
  5894. .Get("/file_content_with_content_type",
  5895. [&](const Request & /*req*/, Response &res) {
  5896. res.set_file_content("./www/file", "text/plain");
  5897. })
  5898. .Get("/invalid_file_content",
  5899. [&](const Request & /*req*/, Response &res) {
  5900. res.set_file_content("./www/dir/invalid_file_path");
  5901. })
  5902. .Get("/http_response_splitting",
  5903. [&](const Request & /*req*/, Response &res) {
  5904. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5905. EXPECT_EQ(0U, res.headers.size());
  5906. EXPECT_FALSE(res.has_header("a"));
  5907. res.set_header("a", "1\nSet-Cookie: a=1");
  5908. EXPECT_EQ(0U, res.headers.size());
  5909. EXPECT_FALSE(res.has_header("a"));
  5910. res.set_header("a", "1\rSet-Cookie: a=1");
  5911. EXPECT_EQ(0U, res.headers.size());
  5912. EXPECT_FALSE(res.has_header("a"));
  5913. res.set_header("a\r\nb", "0");
  5914. EXPECT_EQ(0U, res.headers.size());
  5915. EXPECT_FALSE(res.has_header("a"));
  5916. res.set_header("a\rb", "0");
  5917. EXPECT_EQ(0U, res.headers.size());
  5918. EXPECT_FALSE(res.has_header("a"));
  5919. res.set_header("a\nb", "0");
  5920. EXPECT_EQ(0U, res.headers.size());
  5921. EXPECT_FALSE(res.has_header("a"));
  5922. res.set_redirect("1\r\nSet-Cookie: a=1");
  5923. EXPECT_EQ(0U, res.headers.size());
  5924. EXPECT_FALSE(res.has_header("Location"));
  5925. })
  5926. .Get("/slow",
  5927. [&](const Request & /*req*/, Response &res) {
  5928. std::this_thread::sleep_for(std::chrono::seconds(4));
  5929. res.set_content("slow", "text/plain");
  5930. })
  5931. #if 0
  5932. .Post("/slowpost",
  5933. [&](const Request & /*req*/, Response &res) {
  5934. std::this_thread::sleep_for(std::chrono::seconds(2));
  5935. res.set_content("slow", "text/plain");
  5936. })
  5937. #endif
  5938. .Get("/remote_addr",
  5939. [&](const Request &req, Response &res) {
  5940. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5941. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5942. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5943. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5944. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5945. #endif
  5946. res.set_content(req.remote_addr, "text/plain");
  5947. })
  5948. .Get("/local_addr",
  5949. [&](const Request &req, Response &res) {
  5950. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5951. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5952. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5953. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5954. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5955. #endif
  5956. auto local_addr = req.local_addr;
  5957. auto local_port = std::to_string(req.local_port);
  5958. res.set_content(local_addr.append(":").append(local_port),
  5959. "text/plain");
  5960. })
  5961. .Get("/endwith%",
  5962. [&](const Request & /*req*/, Response &res) {
  5963. res.set_content("Hello World!", "text/plain");
  5964. })
  5965. .Get("/a\\+\\+b",
  5966. [&](const Request &req, Response &res) {
  5967. ASSERT_TRUE(req.has_param("a +b"));
  5968. auto val = req.get_param_value("a +b");
  5969. res.set_content(val, "text/plain");
  5970. })
  5971. .Get("/", [&](const Request & /*req*/,
  5972. Response &res) { res.set_redirect("/hi"); })
  5973. .Post("/1",
  5974. [](const Request & /*req*/, Response &res) {
  5975. res.set_redirect("/2", StatusCode::SeeOther_303);
  5976. })
  5977. .Get("/2",
  5978. [](const Request & /*req*/, Response &res) {
  5979. res.set_content("redirected.", "text/plain");
  5980. res.status = StatusCode::OK_200;
  5981. })
  5982. .Post("/person",
  5983. [&](const Request &req, Response &res) {
  5984. if (req.has_param("name") && req.has_param("note")) {
  5985. persons_[req.get_param_value("name")] =
  5986. req.get_param_value("note");
  5987. } else {
  5988. res.status = StatusCode::BadRequest_400;
  5989. }
  5990. })
  5991. .Put("/person",
  5992. [&](const Request &req, Response &res) {
  5993. if (req.has_param("name") && req.has_param("note")) {
  5994. persons_[req.get_param_value("name")] =
  5995. req.get_param_value("note");
  5996. } else {
  5997. res.status = StatusCode::BadRequest_400;
  5998. }
  5999. })
  6000. .Get("/person/(.*)",
  6001. [&](const Request &req, Response &res) {
  6002. string name = req.matches[1];
  6003. if (persons_.find(name) != persons_.end()) {
  6004. auto note = persons_[name];
  6005. res.set_content(note, "text/plain");
  6006. } else {
  6007. res.status = StatusCode::NotFound_404;
  6008. }
  6009. })
  6010. .Delete("/person",
  6011. [&](const Request &req, Response &res) {
  6012. if (req.has_param("name")) {
  6013. string name = req.get_param_value("name");
  6014. if (persons_.find(name) != persons_.end()) {
  6015. persons_.erase(name);
  6016. res.set_content("DELETED", "text/plain");
  6017. } else {
  6018. res.status = StatusCode::NotFound_404;
  6019. }
  6020. } else {
  6021. res.status = StatusCode::BadRequest_400;
  6022. }
  6023. })
  6024. .Post("/x-www-form-urlencoded-json",
  6025. [&](const Request &req, Response &res) {
  6026. auto json = req.get_param_value("json");
  6027. ASSERT_EQ(JSON_DATA, json);
  6028. res.set_content(json, "appliation/json");
  6029. res.status = StatusCode::OK_200;
  6030. })
  6031. .Get("/streamed-chunked",
  6032. [&](const Request & /*req*/, Response &res) {
  6033. res.set_chunked_content_provider(
  6034. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6035. sink.os << "123";
  6036. sink.os << "456";
  6037. sink.os << "789";
  6038. sink.done();
  6039. return true;
  6040. });
  6041. })
  6042. .Get("/streamed-chunked-with-prohibited-trailer",
  6043. [&](const Request & /*req*/, Response &res) {
  6044. auto i = new int(0);
  6045. // Declare both a prohibited trailer (Content-Length) and an
  6046. // allowed one
  6047. res.set_header("Trailer", "Content-Length, X-Allowed");
  6048. res.set_chunked_content_provider(
  6049. "text/plain",
  6050. [i](size_t /*offset*/, DataSink &sink) {
  6051. switch (*i) {
  6052. case 0: sink.os << "123"; break;
  6053. case 1: sink.os << "456"; break;
  6054. case 2: sink.os << "789"; break;
  6055. case 3: {
  6056. sink.done_with_trailer(
  6057. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6058. } break;
  6059. }
  6060. (*i)++;
  6061. return true;
  6062. },
  6063. [i](bool success) {
  6064. EXPECT_TRUE(success);
  6065. delete i;
  6066. });
  6067. })
  6068. .Get("/streamed-chunked2",
  6069. [&](const Request & /*req*/, Response &res) {
  6070. auto i = new int(0);
  6071. res.set_chunked_content_provider(
  6072. "text/plain",
  6073. [i](size_t /*offset*/, DataSink &sink) {
  6074. switch (*i) {
  6075. case 0: sink.os << "123"; break;
  6076. case 1: sink.os << "456"; break;
  6077. case 2: sink.os << "789"; break;
  6078. case 3: sink.done(); break;
  6079. }
  6080. (*i)++;
  6081. return true;
  6082. },
  6083. [i](bool success) {
  6084. EXPECT_TRUE(success);
  6085. delete i;
  6086. });
  6087. })
  6088. .Get("/streamed-chunked-with-trailer",
  6089. [&](const Request & /*req*/, Response &res) {
  6090. auto i = new int(0);
  6091. res.set_header("Trailer", "Dummy1, Dummy2");
  6092. res.set_chunked_content_provider(
  6093. "text/plain",
  6094. [i](size_t /*offset*/, DataSink &sink) {
  6095. switch (*i) {
  6096. case 0: sink.os << "123"; break;
  6097. case 1: sink.os << "456"; break;
  6098. case 2: sink.os << "789"; break;
  6099. case 3: {
  6100. sink.done_with_trailer(
  6101. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6102. } break;
  6103. }
  6104. (*i)++;
  6105. return true;
  6106. },
  6107. [i](bool success) {
  6108. EXPECT_TRUE(success);
  6109. delete i;
  6110. });
  6111. })
  6112. .Get("/streamed",
  6113. [&](const Request & /*req*/, Response &res) {
  6114. res.set_content_provider(
  6115. 6, "text/plain",
  6116. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6117. sink.os << (offset < 3 ? "a" : "b");
  6118. return true;
  6119. });
  6120. })
  6121. .Get("/streamed-without-length",
  6122. [&](const Request & /*req*/, Response &res) {
  6123. auto data = new std::string("abcdefg");
  6124. res.set_content_provider(
  6125. "text/plain",
  6126. [data](size_t offset, DataSink &sink) {
  6127. if (offset < data->size()) {
  6128. sink.os << data->substr(offset);
  6129. }
  6130. sink.done();
  6131. return true;
  6132. },
  6133. [data](bool success) {
  6134. EXPECT_TRUE(success);
  6135. delete data;
  6136. });
  6137. })
  6138. .Get("/streamed-with-range",
  6139. [&](const Request &req, Response &res) {
  6140. auto data = new std::string("abcdefg");
  6141. // An explicit status keeps the server from picking the 206 it
  6142. // would otherwise choose for a ranged request, so the response
  6143. // is not a partial representation.
  6144. auto status = req.get_param_value("status");
  6145. if (status == "200") {
  6146. res.status = StatusCode::OK_200;
  6147. } else if (status == "403") {
  6148. res.status = StatusCode::Forbidden_403;
  6149. }
  6150. res.set_content_provider(
  6151. data->size(), "text/plain",
  6152. [data](size_t offset, size_t length, DataSink &sink) {
  6153. size_t DATA_CHUNK_SIZE = 4;
  6154. const auto &d = *data;
  6155. auto out_len =
  6156. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6157. auto ret =
  6158. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6159. EXPECT_TRUE(ret);
  6160. return true;
  6161. },
  6162. [data, &req](bool success) {
  6163. EXPECT_EQ(success, !req.has_param("error"));
  6164. delete data;
  6165. });
  6166. })
  6167. .Get("/streamed-cancel",
  6168. [&](const Request & /*req*/, Response &res) {
  6169. res.set_content_provider(
  6170. size_t(-1), "text/plain",
  6171. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6172. sink.os << "data_chunk";
  6173. return true;
  6174. });
  6175. })
  6176. .Get("/regex-with-delimiter",
  6177. [&](const Request &req, Response & /*res*/) {
  6178. ASSERT_TRUE(req.has_param("key"));
  6179. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6180. })
  6181. .Get("/with-range",
  6182. [&](const Request & /*req*/, Response &res) {
  6183. res.set_content("abcdefg", "text/plain");
  6184. })
  6185. .Get("/test-start-time",
  6186. [&](const Request &req, Response & /*res*/) {
  6187. EXPECT_NE(req.start_time_,
  6188. std::chrono::steady_clock::time_point::min());
  6189. })
  6190. .Get("/with-range-customized-response",
  6191. [&](const Request & /*req*/, Response &res) {
  6192. res.status = StatusCode::BadRequest_400;
  6193. res.set_content(JSON_DATA, "application/json");
  6194. })
  6195. .Post("/chunked",
  6196. [&](const Request &req, Response & /*res*/) {
  6197. EXPECT_EQ(req.body, "dechunked post body");
  6198. })
  6199. .Post("/large-chunked",
  6200. [&](const Request &req, Response & /*res*/) {
  6201. std::string expected(6 * 30 * 1024u, 'a');
  6202. EXPECT_EQ(req.body, expected);
  6203. })
  6204. .Post("/multipart",
  6205. [&](const Request &req, Response & /*res*/) {
  6206. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6207. req.form.get_field_count("text2") +
  6208. req.form.get_field_count("file3") +
  6209. req.form.get_field_count("file4"));
  6210. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6211. req.form.get_file_count("file2"));
  6212. ASSERT_TRUE(!req.form.has_file("???"));
  6213. ASSERT_TRUE(!req.form.has_field("???"));
  6214. ASSERT_TRUE(req.body.empty());
  6215. {
  6216. const auto &text = req.form.get_field("text1");
  6217. EXPECT_EQ("text default", text);
  6218. }
  6219. {
  6220. const auto &text = req.form.get_field("text2");
  6221. EXPECT_EQ("aωb", text);
  6222. }
  6223. {
  6224. const auto &file = req.form.get_file("file1");
  6225. EXPECT_EQ("hello.txt", file.filename);
  6226. EXPECT_EQ("text/plain", file.content_type);
  6227. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6228. }
  6229. {
  6230. const auto &file = req.form.get_file("file2");
  6231. EXPECT_EQ("world.json", file.filename);
  6232. EXPECT_EQ("application/json", file.content_type);
  6233. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6234. }
  6235. {
  6236. const auto &text = req.form.get_field("file3");
  6237. EXPECT_EQ(0u, text.size());
  6238. }
  6239. {
  6240. const auto &text = req.form.get_field("file4");
  6241. EXPECT_EQ(0u, text.size());
  6242. }
  6243. })
  6244. .Post("/multipart/multi_file_values",
  6245. [&](const Request &req, Response & /*res*/) {
  6246. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6247. req.form.get_field_count("multi_text1"));
  6248. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6249. ASSERT_TRUE(!req.form.has_file("???"));
  6250. ASSERT_TRUE(!req.form.has_field("???"));
  6251. ASSERT_TRUE(req.body.empty());
  6252. {
  6253. const auto &text = req.form.get_field("text");
  6254. EXPECT_EQ("default text", text);
  6255. }
  6256. {
  6257. const auto &text1_values = req.form.get_fields("multi_text1");
  6258. EXPECT_EQ(2u, text1_values.size());
  6259. EXPECT_EQ("aaaaa", text1_values[0]);
  6260. EXPECT_EQ("bbbbb", text1_values[1]);
  6261. }
  6262. {
  6263. const auto &file1_values = req.form.get_files("multi_file1");
  6264. EXPECT_EQ(2u, file1_values.size());
  6265. auto file1 = file1_values[0];
  6266. EXPECT_EQ(file1.filename, "hello.txt");
  6267. EXPECT_EQ(file1.content_type, "text/plain");
  6268. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6269. auto file2 = file1_values[1];
  6270. EXPECT_EQ(file2.filename, "world.json");
  6271. EXPECT_EQ(file2.content_type, "application/json");
  6272. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6273. }
  6274. })
  6275. .Post("/empty",
  6276. [&](const Request &req, Response &res) {
  6277. EXPECT_EQ(req.body, "");
  6278. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6279. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6280. res.set_content("empty", "text/plain");
  6281. })
  6282. .Post("/empty-no-content-type",
  6283. [&](const Request &req, Response &res) {
  6284. EXPECT_EQ(req.body, "");
  6285. EXPECT_FALSE(req.has_header("Content-Type"));
  6286. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6287. res.set_content("empty-no-content-type", "text/plain");
  6288. })
  6289. .Post("/path-only",
  6290. [&](const Request &req, Response &res) {
  6291. EXPECT_EQ(req.body, "");
  6292. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6293. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6294. res.set_content("path-only", "text/plain");
  6295. })
  6296. .Post("/path-headers-only",
  6297. [&](const Request &req, Response &res) {
  6298. EXPECT_EQ(req.body, "");
  6299. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6300. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6301. EXPECT_EQ("world", req.get_header_value("hello"));
  6302. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6303. res.set_content("path-headers-only", "text/plain");
  6304. })
  6305. .Post("/post-large",
  6306. [&](const Request &req, Response &res) {
  6307. EXPECT_EQ(req.body, LARGE_DATA);
  6308. res.set_content(req.body, "text/plain");
  6309. })
  6310. .Post("/post-loopback",
  6311. [&](const Request &, Response &res,
  6312. ContentReader const &content_reader) {
  6313. std::string body;
  6314. content_reader([&](const char *data, size_t data_length) {
  6315. body.append(data, data_length);
  6316. return true;
  6317. });
  6318. res.set_content(body, "text/plain");
  6319. })
  6320. .Put("/put-loopback",
  6321. [&](const Request &, Response &res,
  6322. ContentReader const &content_reader) {
  6323. std::string body;
  6324. content_reader([&](const char *data, size_t data_length) {
  6325. body.append(data, data_length);
  6326. return true;
  6327. });
  6328. res.set_content(body, "text/plain");
  6329. })
  6330. .Patch("/patch-loopback",
  6331. [&](const Request &, Response &res,
  6332. ContentReader const &content_reader) {
  6333. std::string body;
  6334. content_reader([&](const char *data, size_t data_length) {
  6335. body.append(data, data_length);
  6336. return true;
  6337. });
  6338. res.set_content(body, "text/plain");
  6339. })
  6340. .Put("/empty-no-content-type",
  6341. [&](const Request &req, Response &res) {
  6342. EXPECT_EQ(req.body, "");
  6343. EXPECT_FALSE(req.has_header("Content-Type"));
  6344. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6345. res.set_content("empty-no-content-type", "text/plain");
  6346. })
  6347. .Put("/put",
  6348. [&](const Request &req, Response &res) {
  6349. EXPECT_EQ(req.body, "PUT");
  6350. res.set_content(req.body, "text/plain");
  6351. })
  6352. .Put("/put-large",
  6353. [&](const Request &req, Response &res) {
  6354. EXPECT_EQ(req.body, LARGE_DATA);
  6355. res.set_content(req.body, "text/plain");
  6356. })
  6357. .Patch("/patch",
  6358. [&](const Request &req, Response &res) {
  6359. EXPECT_EQ(req.body, "PATCH");
  6360. res.set_content(req.body, "text/plain");
  6361. })
  6362. .Delete("/delete",
  6363. [&](const Request & /*req*/, Response &res) {
  6364. res.set_content("DELETE", "text/plain");
  6365. })
  6366. .Delete("/delete-body",
  6367. [&](const Request &req, Response &res) {
  6368. EXPECT_EQ(req.body, "content");
  6369. res.set_content(req.body, "text/plain");
  6370. })
  6371. .Options(R"(\*)",
  6372. [&](const Request & /*req*/, Response &res) {
  6373. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6374. })
  6375. .CustomRoute("PROPFIND", "/dav/:id",
  6376. [&](const Request &req, Response &res) {
  6377. res.set_header("x-body-size",
  6378. std::to_string(req.body.size()));
  6379. res.set_header("x-matched-route", req.matched_route);
  6380. res.set_header("x-dav-id", req.path_params.at("id"));
  6381. res.status = StatusCode::MultiStatus_207;
  6382. res.set_content(req.body, "application/xml");
  6383. })
  6384. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6385. [&](const Request &req, Response &res) {
  6386. res.set_header("x-dav-match", req.matches[1]);
  6387. res.status = StatusCode::MultiStatus_207;
  6388. })
  6389. .CustomRoute("MKCOL", "/dav-mkcol",
  6390. [&](const Request &req, Response &res) {
  6391. EXPECT_TRUE(req.body.empty());
  6392. res.status = StatusCode::Created_201;
  6393. })
  6394. .CustomRoute(
  6395. "REPORT", "/dav-report",
  6396. [&](const Request & /*req*/, Response &res,
  6397. const ContentReader &content_reader) {
  6398. std::string body;
  6399. content_reader([&](const char *data, size_t data_length) {
  6400. body.append(data, data_length);
  6401. return true;
  6402. });
  6403. res.set_header("x-body-size", std::to_string(body.size()));
  6404. res.status = StatusCode::MultiStatus_207;
  6405. res.set_content(body, "application/xml");
  6406. })
  6407. .Get("/request-target",
  6408. [&](const Request &req, Response & /*res*/) {
  6409. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6410. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6411. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6412. })
  6413. .Get("/long-query-value",
  6414. [&](const Request &req, Response & /*res*/) {
  6415. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6416. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6417. })
  6418. .Get("/too-long-query-value",
  6419. [&](const Request &req, Response & /*res*/) {
  6420. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6421. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6422. })
  6423. .Get("/array-param",
  6424. [&](const Request &req, Response & /*res*/) {
  6425. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6426. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6427. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6428. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6429. })
  6430. .Get("/array-param-values",
  6431. [&](const Request &req, Response & /*res*/) {
  6432. auto values = req.get_param_values("array");
  6433. EXPECT_EQ(3u, values.size());
  6434. EXPECT_EQ("value1", values[0]);
  6435. EXPECT_EQ("value2", values[1]);
  6436. EXPECT_EQ("value3", values[2]);
  6437. auto empty = req.get_param_values("nonexistent");
  6438. EXPECT_TRUE(empty.empty());
  6439. })
  6440. .Post("/validate-no-multiple-headers",
  6441. [&](const Request &req, Response & /*res*/) {
  6442. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6443. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6444. })
  6445. .Post("/content_receiver",
  6446. [&](const Request &req, Response &res,
  6447. const ContentReader &content_reader) {
  6448. if (req.is_multipart_form_data()) {
  6449. std::vector<FormData> items;
  6450. content_reader(
  6451. [&](const FormData &file) {
  6452. items.push_back(file);
  6453. return true;
  6454. },
  6455. [&](const char *data, size_t data_length) {
  6456. items.back().content.append(data, data_length);
  6457. return true;
  6458. });
  6459. EXPECT_EQ(5u, items.size());
  6460. {
  6461. const auto &file = get_file_value(items, "text1");
  6462. EXPECT_TRUE(file.filename.empty());
  6463. EXPECT_EQ("text default", file.content);
  6464. }
  6465. {
  6466. const auto &file = get_file_value(items, "text2");
  6467. EXPECT_TRUE(file.filename.empty());
  6468. EXPECT_EQ("aωb", file.content);
  6469. }
  6470. {
  6471. const auto &file = get_file_value(items, "file1");
  6472. EXPECT_EQ("hello.txt", file.filename);
  6473. EXPECT_EQ("text/plain", file.content_type);
  6474. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6475. }
  6476. {
  6477. const auto &file = get_file_value(items, "file2");
  6478. EXPECT_EQ("world.json", file.filename);
  6479. EXPECT_EQ("application/json", file.content_type);
  6480. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6481. }
  6482. {
  6483. const auto &file = get_file_value(items, "file3");
  6484. EXPECT_TRUE(file.filename.empty());
  6485. EXPECT_EQ("application/octet-stream", file.content_type);
  6486. EXPECT_EQ(0u, file.content.size());
  6487. }
  6488. } else {
  6489. std::string body;
  6490. content_reader([&](const char *data, size_t data_length) {
  6491. EXPECT_EQ(7U, data_length);
  6492. body.append(data, data_length);
  6493. return true;
  6494. });
  6495. EXPECT_EQ(body, "content");
  6496. res.set_content(body, "text/plain");
  6497. }
  6498. })
  6499. .Put("/content_receiver",
  6500. [&](const Request & /*req*/, Response &res,
  6501. const ContentReader &content_reader) {
  6502. std::string body;
  6503. content_reader([&](const char *data, size_t data_length) {
  6504. body.append(data, data_length);
  6505. return true;
  6506. });
  6507. EXPECT_EQ(body, "content");
  6508. res.set_content(body, "text/plain");
  6509. })
  6510. .Patch("/content_receiver",
  6511. [&](const Request & /*req*/, Response &res,
  6512. const ContentReader &content_reader) {
  6513. std::string body;
  6514. content_reader([&](const char *data, size_t data_length) {
  6515. body.append(data, data_length);
  6516. return true;
  6517. });
  6518. EXPECT_EQ(body, "content");
  6519. res.set_content(body, "text/plain");
  6520. })
  6521. .Post("/query-string-and-body",
  6522. [&](const Request &req, Response & /*res*/) {
  6523. ASSERT_TRUE(req.has_param("key"));
  6524. EXPECT_EQ(req.get_param_value("key"), "value");
  6525. EXPECT_EQ(req.body, "content");
  6526. })
  6527. .Get("/last-request",
  6528. [&](const Request &req, Response & /*res*/) {
  6529. EXPECT_EQ("close", req.get_header_value("Connection"));
  6530. })
  6531. .Get(R"(/redirect/(\d+))",
  6532. [&](const Request &req, Response &res) {
  6533. auto num = std::stoi(req.matches[1]) + 1;
  6534. std::string url = "/redirect/" + std::to_string(num);
  6535. res.set_redirect(url);
  6536. })
  6537. .Post("/binary",
  6538. [&](const Request &req, Response &res) {
  6539. EXPECT_EQ(4U, req.body.size());
  6540. EXPECT_EQ("application/octet-stream",
  6541. req.get_header_value("Content-Type"));
  6542. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6543. res.set_content(req.body, "application/octet-stream");
  6544. })
  6545. .Put("/binary",
  6546. [&](const Request &req, Response &res) {
  6547. EXPECT_EQ(4U, req.body.size());
  6548. EXPECT_EQ("application/octet-stream",
  6549. req.get_header_value("Content-Type"));
  6550. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6551. res.set_content(req.body, "application/octet-stream");
  6552. })
  6553. .Patch("/binary",
  6554. [&](const Request &req, Response &res) {
  6555. EXPECT_EQ(4U, req.body.size());
  6556. EXPECT_EQ("application/octet-stream",
  6557. req.get_header_value("Content-Type"));
  6558. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6559. res.set_content(req.body, "application/octet-stream");
  6560. })
  6561. .Delete("/binary",
  6562. [&](const Request &req, Response &res) {
  6563. EXPECT_EQ(4U, req.body.size());
  6564. EXPECT_EQ("application/octet-stream",
  6565. req.get_header_value("Content-Type"));
  6566. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6567. res.set_content(req.body, "application/octet-stream");
  6568. })
  6569. .Get("/issue1772",
  6570. [&](const Request & /*req*/, Response &res) {
  6571. res.status = 401;
  6572. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6573. })
  6574. .Delete("/issue609",
  6575. [](const httplib::Request &, httplib::Response &res,
  6576. const httplib::ContentReader &) {
  6577. res.set_content("ok", "text/plain");
  6578. })
  6579. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6580. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6581. .Get("/compress",
  6582. [&](const Request & /*req*/, Response &res) {
  6583. res.set_content(
  6584. "12345678901234567890123456789012345678901234567890123456789"
  6585. "01234567890123456789012345678901234567890",
  6586. "text/plain");
  6587. })
  6588. .Get("/compress-with-charset",
  6589. [&](const Request & /*req*/, Response &res) {
  6590. res.set_content(
  6591. "12345678901234567890123456789012345678901234567890123456789"
  6592. "01234567890123456789012345678901234567890",
  6593. "application/json; charset=utf-8");
  6594. })
  6595. .Get("/nocompress",
  6596. [&](const Request & /*req*/, Response &res) {
  6597. res.set_content(
  6598. "12345678901234567890123456789012345678901234567890123456789"
  6599. "01234567890123456789012345678901234567890",
  6600. "application/octet-stream");
  6601. })
  6602. .Post("/compress-multipart",
  6603. [&](const Request &req, Response & /*res*/) {
  6604. EXPECT_EQ(2u, req.form.fields.size());
  6605. ASSERT_TRUE(!req.form.has_field("???"));
  6606. {
  6607. const auto &text = req.form.get_field("key1");
  6608. EXPECT_EQ("test", text);
  6609. }
  6610. {
  6611. const auto &text = req.form.get_field("key2");
  6612. EXPECT_EQ("--abcdefg123", text);
  6613. }
  6614. })
  6615. #endif
  6616. ;
  6617. persons_["john"] = "programmer";
  6618. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6619. svr_.wait_until_ready();
  6620. }
  6621. virtual void TearDown() {
  6622. svr_.stop();
  6623. if (!request_threads_.empty()) {
  6624. std::this_thread::sleep_for(std::chrono::seconds(1));
  6625. for (auto &t : request_threads_) {
  6626. t.join();
  6627. }
  6628. }
  6629. t_.join();
  6630. }
  6631. map<string, string> persons_;
  6632. #ifdef CPPHTTPLIB_SSL_ENABLED
  6633. SSLClient cli_;
  6634. SSLServer svr_;
  6635. #else
  6636. Client cli_;
  6637. Server svr_;
  6638. #endif
  6639. thread t_;
  6640. std::vector<thread> request_threads_;
  6641. };
  6642. TEST_F(ServerTest, GetMethod200) {
  6643. auto res = cli_.Get("/hi");
  6644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6645. EXPECT_EQ("HTTP/1.1", res->version);
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ("OK", res->reason);
  6648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6649. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6650. EXPECT_EQ("Hello World!", res->body);
  6651. }
  6652. TEST_F(ServerTest, GetEmptyFile) {
  6653. auto res = cli_.Get("/empty_file");
  6654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6655. EXPECT_EQ(StatusCode::OK_200, res->status);
  6656. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6657. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6658. EXPECT_EQ("", res->body);
  6659. }
  6660. TEST_F(ServerTest, GetFileContent) {
  6661. auto res = cli_.Get("/file_content");
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::OK_200, res->status);
  6664. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6665. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6666. EXPECT_EQ("test.html", res->body);
  6667. }
  6668. TEST_F(ServerTest, GetFileContentWithRange) {
  6669. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6673. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6674. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6675. EXPECT_EQ("est", res->body);
  6676. }
  6677. TEST_F(ServerTest, GetFileContentWithContentType) {
  6678. auto res = cli_.Get("/file_content_with_content_type");
  6679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6680. EXPECT_EQ(StatusCode::OK_200, res->status);
  6681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6682. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6683. EXPECT_EQ("file\n", res->body);
  6684. }
  6685. TEST_F(ServerTest, GetInvalidFileContent) {
  6686. auto res = cli_.Get("/invalid_file_content");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6689. }
  6690. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6691. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ("HTTP/1.1", res->version);
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6696. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6697. EXPECT_EQ("Hello World!", res->body);
  6698. }
  6699. TEST_F(ServerTest, GetMethod302) {
  6700. auto res = cli_.Get("/");
  6701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6702. EXPECT_EQ(StatusCode::Found_302, res->status);
  6703. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6704. }
  6705. TEST_F(ServerTest, GetMethod302Redirect) {
  6706. cli_.set_follow_location(true);
  6707. auto res = cli_.Get("/");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. EXPECT_EQ("Hello World!", res->body);
  6711. EXPECT_EQ("/hi", res->location);
  6712. }
  6713. TEST_F(ServerTest, GetMethod404) {
  6714. auto res = cli_.Get("/invalid");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6717. }
  6718. TEST_F(ServerTest, HeadMethod200) {
  6719. auto res = cli_.Head("/hi");
  6720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6721. EXPECT_EQ(StatusCode::OK_200, res->status);
  6722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6723. EXPECT_TRUE(res->body.empty());
  6724. }
  6725. TEST_F(ServerTest, HeadMethod200Static) {
  6726. auto res = cli_.Head("/mount/dir/index.html");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6731. EXPECT_TRUE(res->body.empty());
  6732. }
  6733. TEST_F(ServerTest, HeadMethod404) {
  6734. auto res = cli_.Head("/invalid");
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6737. EXPECT_TRUE(res->body.empty());
  6738. }
  6739. TEST_F(ServerTest, GetMethodPersonJohn) {
  6740. auto res = cli_.Get("/person/john");
  6741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6744. EXPECT_EQ("programmer", res->body);
  6745. }
  6746. TEST_F(ServerTest, PostMethod1) {
  6747. auto res = cli_.Get("/person/john1");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6750. res = cli_.Post("/person", "name=john1&note=coder",
  6751. "application/x-www-form-urlencoded");
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. ASSERT_EQ(StatusCode::OK_200, res->status);
  6754. res = cli_.Get("/person/john1");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. ASSERT_EQ(StatusCode::OK_200, res->status);
  6757. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6758. ASSERT_EQ("coder", res->body);
  6759. }
  6760. TEST_F(ServerTest, PostMethod2) {
  6761. auto res = cli_.Get("/person/john2");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6764. Params params;
  6765. params.emplace("name", "john2");
  6766. params.emplace("note", "coder");
  6767. res = cli_.Post("/person", params);
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. ASSERT_EQ(StatusCode::OK_200, res->status);
  6770. res = cli_.Get("/person/john2");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. ASSERT_EQ(StatusCode::OK_200, res->status);
  6773. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6774. ASSERT_EQ("coder", res->body);
  6775. }
  6776. TEST_F(ServerTest, PutMethod3) {
  6777. auto res = cli_.Get("/person/john3");
  6778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6779. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6780. Params params;
  6781. params.emplace("name", "john3");
  6782. params.emplace("note", "coder");
  6783. res = cli_.Put("/person", params);
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. ASSERT_EQ(StatusCode::OK_200, res->status);
  6786. res = cli_.Get("/person/john3");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. ASSERT_EQ(StatusCode::OK_200, res->status);
  6789. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6790. ASSERT_EQ("coder", res->body);
  6791. }
  6792. TEST_F(ServerTest, DeleteMethod1) {
  6793. auto res = cli_.Get("/person/john4");
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6796. Params params;
  6797. params.emplace("name", "john4");
  6798. params.emplace("note", "coder");
  6799. res = cli_.Post("/person", params);
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. ASSERT_EQ(StatusCode::OK_200, res->status);
  6802. res = cli_.Get("/person/john4");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. ASSERT_EQ(StatusCode::OK_200, res->status);
  6805. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6806. ASSERT_EQ("coder", res->body);
  6807. Params delete_params;
  6808. delete_params.emplace("name", "john4");
  6809. res = cli_.Delete("/person", delete_params);
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. ASSERT_EQ(StatusCode::OK_200, res->status);
  6812. ASSERT_EQ("DELETED", res->body);
  6813. res = cli_.Get("/person/john4");
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6816. }
  6817. TEST_F(ServerTest, DeleteMethod2) {
  6818. auto res = cli_.Get("/person/john5");
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6821. Params params;
  6822. params.emplace("name", "john5");
  6823. params.emplace("note", "developer");
  6824. res = cli_.Post("/person", params);
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. ASSERT_EQ(StatusCode::OK_200, res->status);
  6827. res = cli_.Get("/person/john5");
  6828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6829. ASSERT_EQ(StatusCode::OK_200, res->status);
  6830. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6831. ASSERT_EQ("developer", res->body);
  6832. Params delete_params;
  6833. delete_params.emplace("name", "john5");
  6834. Headers headers;
  6835. headers.emplace("Custom-Header", "test-value");
  6836. res = cli_.Delete("/person", headers, delete_params);
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. ASSERT_EQ(StatusCode::OK_200, res->status);
  6839. ASSERT_EQ("DELETED", res->body);
  6840. res = cli_.Get("/person/john5");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6843. }
  6844. TEST_F(ServerTest, DeleteMethod3) {
  6845. auto res = cli_.Get("/person/john6");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6848. Params params;
  6849. params.emplace("name", "john6");
  6850. params.emplace("note", "tester");
  6851. res = cli_.Post("/person", params);
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. ASSERT_EQ(StatusCode::OK_200, res->status);
  6854. res = cli_.Get("/person/john6");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. ASSERT_EQ(StatusCode::OK_200, res->status);
  6857. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6858. ASSERT_EQ("tester", res->body);
  6859. Params delete_params;
  6860. delete_params.emplace("name", "john6");
  6861. Headers headers;
  6862. headers.emplace("Custom-Header", "test-value");
  6863. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. ASSERT_EQ(StatusCode::OK_200, res->status);
  6866. ASSERT_EQ("DELETED", res->body);
  6867. res = cli_.Get("/person/john6");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6870. }
  6871. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6872. Params params;
  6873. params.emplace("json", JSON_DATA);
  6874. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. ASSERT_EQ(StatusCode::OK_200, res->status);
  6877. ASSERT_EQ(JSON_DATA, res->body);
  6878. }
  6879. TEST_F(ServerTest, PostEmptyContent) {
  6880. auto res = cli_.Post("/empty", "", "text/plain");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. ASSERT_EQ(StatusCode::OK_200, res->status);
  6883. ASSERT_EQ("empty", res->body);
  6884. }
  6885. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6886. auto res = cli_.Post("/empty-no-content-type");
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. ASSERT_EQ(StatusCode::OK_200, res->status);
  6889. ASSERT_EQ("empty-no-content-type", res->body);
  6890. }
  6891. TEST_F(ServerTest, PostPathOnly) {
  6892. auto res = cli_.Post("/path-only");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::OK_200, res->status);
  6895. ASSERT_EQ("path-only", res->body);
  6896. }
  6897. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6898. auto res = cli_.Post("/path-headers-only",
  6899. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. ASSERT_EQ(StatusCode::OK_200, res->status);
  6902. ASSERT_EQ("path-headers-only", res->body);
  6903. }
  6904. TEST_F(ServerTest, PostLarge) {
  6905. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. ASSERT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ(LARGE_DATA, res->body);
  6909. }
  6910. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6911. auto res = cli_.Put("/empty-no-content-type");
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. ASSERT_EQ(StatusCode::OK_200, res->status);
  6914. ASSERT_EQ("empty-no-content-type", res->body);
  6915. }
  6916. TEST_F(ServerTest, GetMethodDir) {
  6917. auto res = cli_.Get("/dir/");
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_EQ(StatusCode::OK_200, res->status);
  6920. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6921. auto body = R"(<html>
  6922. <head>
  6923. </head>
  6924. <body>
  6925. <a href="/dir/test.html">Test</a>
  6926. <a href="/hi">hi</a>
  6927. </body>
  6928. </html>
  6929. )";
  6930. EXPECT_EQ(body, res->body);
  6931. }
  6932. TEST_F(ServerTest, GetMethodDirTest) {
  6933. auto res = cli_.Get("/dir/test.html");
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6937. EXPECT_EQ("test.html", res->body);
  6938. }
  6939. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6940. auto res = cli_.Get("/dir/../dir/test.html");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6943. }
  6944. TEST_F(ServerTest, GetMethodInvalidPath) {
  6945. auto res = cli_.Get("/dir/../test.html");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6948. }
  6949. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6950. auto res = cli_.Get("/../www/dir/test.html");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6953. }
  6954. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6955. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6958. }
  6959. TEST_F(ServerTest, GetMethodDirMountTest) {
  6960. auto res = cli_.Get("/mount/dir/test.html");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6964. EXPECT_EQ("test.html", res->body);
  6965. }
  6966. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6967. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6970. }
  6971. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6972. auto res = cli_.Get("/mount/dir/../test.html");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6975. }
  6976. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6977. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6980. }
  6981. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6982. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6985. }
  6986. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6987. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6990. }
  6991. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6992. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6994. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6995. }
  6996. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6997. auto res = cli_.Get("/mount/dir");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7000. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7001. }
  7002. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7003. auto res = cli_.Get("//dir");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7006. EXPECT_FALSE(res->has_header("Location"));
  7007. }
  7008. TEST_F(ServerTest, PostMethod303) {
  7009. auto res = cli_.Post("/1", "body", "text/plain");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7012. EXPECT_EQ("/2", res->get_header_value("Location"));
  7013. }
  7014. TEST_F(ServerTest, PostMethod303Redirect) {
  7015. cli_.set_follow_location(true);
  7016. auto res = cli_.Post("/1", "body", "text/plain");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("redirected.", res->body);
  7020. EXPECT_EQ("/2", res->location);
  7021. }
  7022. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7023. auto res = cli_.Get("/dir/test.abcde");
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7027. EXPECT_EQ("abcde", res->body);
  7028. }
  7029. TEST_F(ServerTest, StaticFileRange) {
  7030. auto res =
  7031. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7034. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7035. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7036. EXPECT_EQ(true, res->has_header("Content-Range"));
  7037. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7038. EXPECT_EQ(std::string("cd"), res->body);
  7039. }
  7040. TEST_F(ServerTest, StaticFileRanges) {
  7041. auto res = cli_.Get("/dir/test.abcde",
  7042. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7045. EXPECT_TRUE(
  7046. res->get_header_value("Content-Type")
  7047. .find(
  7048. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7049. 0);
  7050. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7051. }
  7052. TEST_F(ServerTest, StaticFileRangeHead) {
  7053. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7056. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7057. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7058. EXPECT_EQ(true, res->has_header("Content-Range"));
  7059. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7060. }
  7061. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7062. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7066. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7067. EXPECT_EQ(true, res->has_header("Content-Range"));
  7068. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7069. res->get_header_value("Content-Range"));
  7070. EXPECT_EQ("LAST\n", res->body);
  7071. }
  7072. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7073. auto res =
  7074. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7078. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7079. EXPECT_EQ(true, res->has_header("Content-Range"));
  7080. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7081. }
  7082. TEST_F(ServerTest, StaticFileBigFile) {
  7083. auto res = cli_.Get("/dir/1MB.txt");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::OK_200, res->status);
  7086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7087. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7088. }
  7089. TEST_F(ServerTest, InvalidBaseDirMount) {
  7090. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7091. }
  7092. TEST_F(ServerTest, Binary) {
  7093. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7094. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7095. "application/octet-stream");
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. ASSERT_EQ(StatusCode::OK_200, res->status);
  7098. ASSERT_EQ(4U, res->body.size());
  7099. res = cli_.Put("/binary", binary.data(), binary.size(),
  7100. "application/octet-stream");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. ASSERT_EQ(StatusCode::OK_200, res->status);
  7103. ASSERT_EQ(4U, res->body.size());
  7104. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7105. "application/octet-stream");
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. ASSERT_EQ(StatusCode::OK_200, res->status);
  7108. ASSERT_EQ(4U, res->body.size());
  7109. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7110. "application/octet-stream");
  7111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7112. ASSERT_EQ(StatusCode::OK_200, res->status);
  7113. ASSERT_EQ(4U, res->body.size());
  7114. }
  7115. TEST_F(ServerTest, BinaryString) {
  7116. auto binary = std::string("\x00\x01\x02\x03", 4);
  7117. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. ASSERT_EQ(StatusCode::OK_200, res->status);
  7120. ASSERT_EQ(4U, res->body.size());
  7121. res = cli_.Put("/binary", binary, "application/octet-stream");
  7122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7123. ASSERT_EQ(StatusCode::OK_200, res->status);
  7124. ASSERT_EQ(4U, res->body.size());
  7125. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. ASSERT_EQ(StatusCode::OK_200, res->status);
  7128. ASSERT_EQ(4U, res->body.size());
  7129. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7131. ASSERT_EQ(StatusCode::OK_200, res->status);
  7132. ASSERT_EQ(4U, res->body.size());
  7133. }
  7134. TEST_F(ServerTest, EmptyRequest) {
  7135. auto res = cli_.Get("");
  7136. ASSERT_TRUE(!res);
  7137. EXPECT_EQ(Error::Connection, res.error());
  7138. }
  7139. TEST_F(ServerTest, LongRequest) {
  7140. std::string request;
  7141. for (size_t i = 0; i < 545; i++) {
  7142. request += "/TooLongRequest";
  7143. }
  7144. request += "OK";
  7145. auto res = cli_.Get(request.c_str());
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7148. }
  7149. TEST_F(ServerTest, TooLongRequest) {
  7150. std::string request;
  7151. for (size_t i = 0; i < 546; i++) {
  7152. request += "/TooLongRequest";
  7153. }
  7154. request += "_NG";
  7155. auto start = std::chrono::high_resolution_clock::now();
  7156. cli_.set_keep_alive(true);
  7157. auto res = cli_.Get(request.c_str());
  7158. auto end = std::chrono::high_resolution_clock::now();
  7159. auto elapsed =
  7160. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7161. .count();
  7162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7163. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7164. EXPECT_LE(elapsed, 1000);
  7165. EXPECT_EQ("close", res->get_header_value("Connection"));
  7166. EXPECT_FALSE(cli_.is_socket_open());
  7167. }
  7168. TEST_F(ServerTest, AlmostTooLongRequest) {
  7169. // test for #2046 - URI length check shouldn't include other content on req
  7170. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7171. // leading /, space, HTTP/1.1)
  7172. std::string request =
  7173. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7174. auto res = cli_.Get(request.c_str());
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7177. }
  7178. TEST_F(ServerTest, LongHeader) {
  7179. Request req;
  7180. req.method = "GET";
  7181. req.path = "/hi";
  7182. std::string host_and_port;
  7183. host_and_port += HOST;
  7184. host_and_port += ":";
  7185. host_and_port += std::to_string(PORT);
  7186. req.headers.emplace("Host", host_and_port.c_str());
  7187. req.headers.emplace("Accept", "*/*");
  7188. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7189. req.headers.emplace(
  7190. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7219. "@@@@@@@@@@@@@@@@");
  7220. auto res = std::make_shared<Response>();
  7221. auto error = Error::Success;
  7222. auto ret = cli_.send(req, *res, error);
  7223. ASSERT_TRUE(ret);
  7224. EXPECT_EQ(StatusCode::OK_200, res->status);
  7225. }
  7226. TEST_F(ServerTest, LongQueryValue) {
  7227. auto start = std::chrono::high_resolution_clock::now();
  7228. cli_.set_keep_alive(true);
  7229. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7230. auto end = std::chrono::high_resolution_clock::now();
  7231. auto elapsed =
  7232. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7233. .count();
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7236. EXPECT_LE(elapsed, 1000);
  7237. EXPECT_EQ("close", res->get_header_value("Connection"));
  7238. EXPECT_FALSE(cli_.is_socket_open());
  7239. }
  7240. TEST_F(ServerTest, TooLongQueryValue) {
  7241. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7242. ASSERT_FALSE(res);
  7243. EXPECT_EQ(Error::Read, res.error());
  7244. }
  7245. TEST_F(ServerTest, TooLongHeader) {
  7246. Request req;
  7247. req.method = "GET";
  7248. req.path = "/hi";
  7249. std::string host_and_port;
  7250. host_and_port += HOST;
  7251. host_and_port += ":";
  7252. host_and_port += std::to_string(PORT);
  7253. req.headers.emplace("Host", host_and_port.c_str());
  7254. req.headers.emplace("Accept", "*/*");
  7255. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7256. req.headers.emplace(
  7257. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7286. "@@@@@@@@@@@@@@@@@");
  7287. auto res = std::make_shared<Response>();
  7288. auto error = Error::Success;
  7289. auto ret = cli_.send(req, *res, error);
  7290. ASSERT_TRUE(ret);
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. TEST_F(ServerTest, HeaderCountAtLimit) {
  7294. // Test with headers just under the 100 limit
  7295. httplib::Headers headers;
  7296. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7297. // This should keep us just under the 100 header limit
  7298. for (int i = 0; i < 95; i++) {
  7299. std::string name = "X-Test-Header-" + std::to_string(i);
  7300. std::string value = "value" + std::to_string(i);
  7301. headers.emplace(name, value);
  7302. }
  7303. // This should work fine as we're under the limit
  7304. auto res = cli_.Get("/hi", headers);
  7305. EXPECT_TRUE(res);
  7306. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7307. }
  7308. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7309. // Test with many headers to exceed the 100 limit
  7310. httplib::Headers headers;
  7311. // Add 150 headers to definitely exceed the 100 limit
  7312. for (int i = 0; i < 150; i++) {
  7313. std::string name = "X-Test-Header-" + std::to_string(i);
  7314. std::string value = "value" + std::to_string(i);
  7315. headers.emplace(name, value);
  7316. }
  7317. // This should fail due to exceeding header count limit
  7318. cli_.set_keep_alive(true);
  7319. auto res = cli_.Get("/hi", headers);
  7320. // The server should respond with 400 Bad Request
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7323. EXPECT_EQ("close", res->get_header_value("Connection"));
  7324. EXPECT_FALSE(cli_.is_socket_open());
  7325. }
  7326. TEST_F(ServerTest, PercentEncoding) {
  7327. auto res = cli_.Get("/e%6edwith%");
  7328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7329. EXPECT_EQ(StatusCode::OK_200, res->status);
  7330. }
  7331. TEST_F(ServerTest, PercentEncodingUnicode) {
  7332. auto res = cli_.Get("/e%u006edwith%");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. }
  7336. TEST_F(ServerTest, InvalidPercentEncoding) {
  7337. auto res = cli_.Get("/%endwith%");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7340. }
  7341. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7342. auto res = cli_.Get("/%uendwith%");
  7343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7345. }
  7346. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7347. auto res = cli_.Get("/hello?aaa=bbb%");
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7350. }
  7351. TEST_F(ServerTest, PlusSignEncoding) {
  7352. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7354. EXPECT_EQ(StatusCode::OK_200, res->status);
  7355. EXPECT_EQ("a +b", res->body);
  7356. }
  7357. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7358. // This test simulates a potential DoS attack using many headers
  7359. // to verify our security fix prevents memory exhaustion
  7360. httplib::Headers attack_headers;
  7361. // Attempt to add many headers like an attacker would (200 headers to far
  7362. // exceed limit)
  7363. for (int i = 0; i < 200; i++) {
  7364. std::string name = "X-Attack-Header-" + std::to_string(i);
  7365. std::string value = "attack_payload_" + std::to_string(i);
  7366. attack_headers.emplace(name, value);
  7367. }
  7368. // Try to POST with excessive headers
  7369. cli_.set_keep_alive(true);
  7370. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7371. // Should either fail or return 400 Bad Request due to security limit
  7372. if (res) {
  7373. // If we get a response, it should be 400 Bad Request
  7374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7375. EXPECT_EQ("close", res->get_header_value("Connection"));
  7376. }
  7377. EXPECT_FALSE(cli_.is_socket_open());
  7378. }
  7379. TEST_F(ServerTest, MultipartFormData) {
  7380. UploadFormDataItems items = {
  7381. {"text1", "text default", "", ""},
  7382. {"text2", "aωb", "", ""},
  7383. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7384. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7385. {"file3", "", "", "application/octet-stream"},
  7386. {"file4", "", "", " application/json tmp-string "}};
  7387. auto res = cli_.Post("/multipart", items);
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::OK_200, res->status);
  7390. }
  7391. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7392. UploadFormDataItems items = {
  7393. {"text", "default text", "", ""},
  7394. {"multi_text1", "aaaaa", "", ""},
  7395. {"multi_text1", "bbbbb", "", ""},
  7396. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7397. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7398. "application/json"},
  7399. };
  7400. auto res = cli_.Post("/multipart/multi_file_values", items);
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. }
  7404. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7405. auto res = cli_.Get("/hi");
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7409. EXPECT_EQ("Hello World!", res->body);
  7410. }
  7411. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7412. Request req;
  7413. req.method = "POST";
  7414. req.path = "/chunked";
  7415. std::string host_and_port;
  7416. host_and_port += HOST;
  7417. host_and_port += ":";
  7418. host_and_port += std::to_string(PORT);
  7419. req.headers.emplace("Host", host_and_port.c_str());
  7420. req.headers.emplace("Accept", "*/*");
  7421. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7422. req.headers.emplace("Content-Type", "text/plain");
  7423. req.headers.emplace("Content-Length", "0");
  7424. req.headers.emplace(
  7425. "Transfer-Encoding",
  7426. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7427. // Client does not chunk, so make a chunked body manually.
  7428. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7429. auto res = std::make_shared<Response>();
  7430. auto error = Error::Success;
  7431. auto ret = cli_.send(req, *res, error);
  7432. ASSERT_TRUE(ret);
  7433. EXPECT_EQ(StatusCode::OK_200, res->status);
  7434. }
  7435. template <typename ClientT>
  7436. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7437. int expected_status) {
  7438. Request req;
  7439. req.method = "POST";
  7440. req.path = "/chunked";
  7441. std::string host_and_port;
  7442. host_and_port += HOST;
  7443. host_and_port += ":";
  7444. host_and_port += std::to_string(PORT);
  7445. req.headers.emplace("Host", host_and_port.c_str());
  7446. req.headers.emplace("Content-Length", "0");
  7447. req.headers.emplace("Transfer-Encoding", "chunked");
  7448. req.body = body;
  7449. auto res = std::make_shared<Response>();
  7450. auto error = Error::Success;
  7451. ASSERT_TRUE(cli.send(req, *res, error));
  7452. EXPECT_EQ(expected_status, res->status);
  7453. }
  7454. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7455. // rather than treat them as valid lengths.
  7456. template <typename ClientT>
  7457. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7458. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7459. }
  7460. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7461. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7462. }
  7463. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7464. expect_chunked_body_rejected(
  7465. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7466. }
  7467. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7468. // chunk-size line carries no CR, LF or other control character ahead of its
  7469. // terminator. Such a line must be refused rather than read as extension text.
  7470. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7471. expect_chunked_body_rejected(
  7472. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7473. }
  7474. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7475. expect_chunked_body_rejected(
  7476. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7477. }
  7478. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7479. expect_chunked_body_rejected(
  7480. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7481. }
  7482. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7483. // The literal stays split: a hex escape consumes every hex digit that
  7484. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7485. expect_chunked_body_rejected(
  7486. cli_, "4;a\x01"
  7487. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7488. }
  7489. // The bytes around chunk data are no payload, so they cannot ride on the
  7490. // payload limit
  7491. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7492. // Small enough that the whole request is sent before the server turns it
  7493. // down, yet past the limit by the last chunks
  7494. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7495. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7496. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7497. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7498. SCOPED_TRACE(size_line.substr(0, 2));
  7499. std::string body;
  7500. for (auto c : std::string("dechunked post body")) {
  7501. body += size_line + "\r\n" + c + "\r\n";
  7502. }
  7503. body += "0\r\n\r\n";
  7504. expect_chunked_body_rejected(cli_, body.c_str());
  7505. }
  7506. }
  7507. TEST_F(ServerTest, AcceptsChunkExtension) {
  7508. expect_chunked_body_status(cli_,
  7509. "4;name=value\r\ndech\r\n"
  7510. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7511. "0;last\r\n\r\n",
  7512. StatusCode::OK_200);
  7513. }
  7514. TEST_F(ServerTest, GetStreamed2) {
  7515. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7518. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7519. EXPECT_EQ(true, res->has_header("Content-Range"));
  7520. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7521. EXPECT_EQ(std::string("ab"), res->body);
  7522. }
  7523. TEST_F(ServerTest, GetStreamed) {
  7524. auto res = cli_.Get("/streamed");
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::OK_200, res->status);
  7527. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7528. EXPECT_EQ(std::string("aaabbb"), res->body);
  7529. }
  7530. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7531. auto res = cli_.Get("/streamed-without-length",
  7532. Headers{make_range_header({{0, -1}})});
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(false, res->has_header("Content-Length"));
  7536. EXPECT_EQ(false, res->has_header("Content-Range"));
  7537. EXPECT_EQ(std::string("abcdefg"), res->body);
  7538. }
  7539. TEST_F(ServerTest, GetStreamedWithRange1) {
  7540. auto res =
  7541. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7543. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7544. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7545. EXPECT_EQ(true, res->has_header("Content-Range"));
  7546. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7547. EXPECT_EQ(std::string("def"), res->body);
  7548. }
  7549. TEST_F(ServerTest, GetStreamedWithRange2) {
  7550. auto res =
  7551. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7554. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7555. EXPECT_EQ(true, res->has_header("Content-Range"));
  7556. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7557. EXPECT_EQ(std::string("bcdefg"), res->body);
  7558. }
  7559. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7560. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7563. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7564. EXPECT_EQ(true, res->has_header("Content-Range"));
  7565. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7566. EXPECT_EQ(std::string("efg"), res->body);
  7567. }
  7568. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7569. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7570. // the entire representation.
  7571. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7572. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7575. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7576. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7577. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7578. }
  7579. }
  7580. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7581. auto res =
  7582. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7584. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7585. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7586. EXPECT_EQ(false, res->has_header("Content-Range"));
  7587. EXPECT_EQ(0U, res->body.size());
  7588. }
  7589. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7590. // Only a 206 is served as a partial representation. Under any other status
  7591. // `apply_ranges()` reported the full content length, so the body must match
  7592. // that header, and the content provider must never be asked for an offset
  7593. // outside the representation.
  7594. auto check = [&](int status, const char *range) {
  7595. auto path =
  7596. std::string("/streamed-with-range?status=") + std::to_string(status);
  7597. auto ctx = path + " Range: " + range;
  7598. auto res = cli_.Get(path, Headers{{"Range", range}});
  7599. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7600. EXPECT_EQ(status, res->status) << ctx;
  7601. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7602. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7603. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7604. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7605. };
  7606. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7607. check(403, "bytes=3-5");
  7608. // The offset is far past the representation.
  7609. check(403, "bytes=100000-100200");
  7610. // `first_pos` is still -1 here, and the bounds asserts in
  7611. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7612. check(403, "bytes=-3");
  7613. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7614. // multipart branch would have written one that is empty.
  7615. check(403, "bytes=1-2, 4-5");
  7616. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7617. // covers the whole representation.
  7618. check(200, "bytes=3-5");
  7619. check(200, "bytes=1-2, 4-5");
  7620. }
  7621. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7622. auto res =
  7623. cli_.Get("/streamed-with-range",
  7624. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7625. "92233720368547758079223372036854775807"}});
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7628. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7629. EXPECT_EQ(false, res->has_header("Content-Range"));
  7630. EXPECT_EQ(0U, res->body.size());
  7631. }
  7632. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7633. auto res = cli_.Get(
  7634. "/with-range",
  7635. Headers{{"Range",
  7636. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7637. {"Accept-Encoding", ""}});
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7640. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ(true, res->has_header("Content-Range"));
  7642. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7643. EXPECT_EQ(std::string("abcdefg"), res->body);
  7644. }
  7645. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7646. auto res = cli_.Get("/with-range", Headers{
  7647. {"Range", "bytes=0-"},
  7648. {"Accept-Encoding", ""},
  7649. });
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7652. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7653. EXPECT_EQ(true, res->has_header("Content-Range"));
  7654. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7655. EXPECT_EQ(std::string("abcdefg"), res->body);
  7656. }
  7657. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7658. auto res = cli_.Get("/streamed-with-range",
  7659. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7662. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7663. EXPECT_EQ(false, res->has_header("Content-Range"));
  7664. EXPECT_EQ(267U, res->body.size());
  7665. // Check that both range contents are present
  7666. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7667. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7668. // Check that Content-Range headers are present for both ranges
  7669. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7670. std::string::npos);
  7671. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7672. std::string::npos);
  7673. }
  7674. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7675. Ranges ranges;
  7676. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7677. ranges.emplace_back(0, -1);
  7678. }
  7679. auto res = cli_.Get("/streamed-with-range?error",
  7680. Headers{{make_range_header(ranges)}});
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7683. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7684. EXPECT_EQ(false, res->has_header("Content-Range"));
  7685. EXPECT_EQ(0U, res->body.size());
  7686. }
  7687. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7688. auto res = cli_.Get("/streamed-with-range",
  7689. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7692. EXPECT_EQ(5U, res->body.size());
  7693. // Check that overlapping ranges are coalesced into a single range
  7694. EXPECT_EQ("bcdef", res->body);
  7695. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7696. // Should be single range, not multipart
  7697. EXPECT_TRUE(res->has_header("Content-Range"));
  7698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7699. }
  7700. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7701. auto res = cli_.Get("/streamed-with-range",
  7702. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7705. EXPECT_EQ(268U, res->body.size());
  7706. // Check that both range contents are present
  7707. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7708. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7709. // Check that Content-Range headers are present for both ranges
  7710. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7711. std::string::npos);
  7712. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7713. std::string::npos);
  7714. }
  7715. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7716. auto res = cli_.Get("/streamed-with-range",
  7717. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7720. EXPECT_EQ(269U, res->body.size());
  7721. // Check that both duplicate range contents are present
  7722. size_t first_abc = res->body.find("abc\r\n");
  7723. EXPECT_TRUE(first_abc != std::string::npos);
  7724. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7725. EXPECT_TRUE(second_abc != std::string::npos);
  7726. // Check that Content-Range headers are present for both ranges
  7727. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7728. EXPECT_TRUE(first_range != std::string::npos);
  7729. size_t second_range =
  7730. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7731. EXPECT_TRUE(second_range != std::string::npos);
  7732. }
  7733. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7734. auto res =
  7735. cli_.Get("/streamed-with-range?error",
  7736. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7739. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7740. EXPECT_EQ(false, res->has_header("Content-Range"));
  7741. EXPECT_EQ(0U, res->body.size());
  7742. }
  7743. TEST_F(ServerTest, GetStreamedEndless) {
  7744. uint64_t offset = 0;
  7745. auto res = cli_.Get("/streamed-cancel",
  7746. [&](const char * /*data*/, uint64_t data_length) {
  7747. if (offset < 100) {
  7748. offset += data_length;
  7749. return true;
  7750. }
  7751. return false;
  7752. });
  7753. ASSERT_TRUE(!res);
  7754. EXPECT_EQ(Error::Canceled, res.error());
  7755. }
  7756. TEST_F(ServerTest, ClientStop) {
  7757. std::atomic_size_t count{4};
  7758. std::vector<std::thread> threads;
  7759. for (auto i = count.load(); i != 0; --i) {
  7760. threads.emplace_back([&]() {
  7761. auto res = cli_.Get("/streamed-cancel",
  7762. [&](const char *, uint64_t) { return true; });
  7763. --count;
  7764. ASSERT_TRUE(!res);
  7765. EXPECT_TRUE(res.error() == Error::Canceled ||
  7766. res.error() == Error::Read || res.error() == Error::Write);
  7767. });
  7768. }
  7769. std::this_thread::sleep_for(std::chrono::seconds(2));
  7770. while (count != 0) {
  7771. cli_.stop();
  7772. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7773. }
  7774. for (auto &t : threads) {
  7775. t.join();
  7776. }
  7777. }
  7778. TEST_F(ServerTest, GetWithRange1) {
  7779. auto res = cli_.Get("/with-range", Headers{
  7780. make_range_header({{3, 5}}),
  7781. {"Accept-Encoding", ""},
  7782. });
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7785. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7786. EXPECT_EQ(true, res->has_header("Content-Range"));
  7787. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7788. EXPECT_EQ(std::string("def"), res->body);
  7789. }
  7790. TEST_F(ServerTest, GetWithRange2) {
  7791. auto res = cli_.Get("/with-range", Headers{
  7792. make_range_header({{1, -1}}),
  7793. {"Accept-Encoding", ""},
  7794. });
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7797. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7798. EXPECT_EQ(true, res->has_header("Content-Range"));
  7799. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7800. EXPECT_EQ(std::string("bcdefg"), res->body);
  7801. }
  7802. TEST_F(ServerTest, GetWithRange3) {
  7803. auto res = cli_.Get("/with-range", Headers{
  7804. make_range_header({{0, 0}}),
  7805. {"Accept-Encoding", ""},
  7806. });
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7809. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7810. EXPECT_EQ(true, res->has_header("Content-Range"));
  7811. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7812. EXPECT_EQ(std::string("a"), res->body);
  7813. }
  7814. TEST_F(ServerTest, GetWithRange4) {
  7815. auto res = cli_.Get("/with-range", Headers{
  7816. make_range_header({{-1, 2}}),
  7817. {"Accept-Encoding", ""},
  7818. });
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7821. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(true, res->has_header("Content-Range"));
  7823. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7824. EXPECT_EQ(std::string("fg"), res->body);
  7825. }
  7826. TEST_F(ServerTest, GetWithRange5) {
  7827. auto res = cli_.Get("/with-range", Headers{
  7828. make_range_header({{0, 5}}),
  7829. {"Accept-Encoding", ""},
  7830. });
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7833. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7834. EXPECT_EQ(true, res->has_header("Content-Range"));
  7835. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7836. EXPECT_EQ(std::string("abcdef"), res->body);
  7837. }
  7838. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7839. auto res =
  7840. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7843. }
  7844. TEST_F(ServerTest, GetWithRangeMultipart) {
  7845. auto res =
  7846. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7849. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7850. EXPECT_EQ(false, res->has_header("Content-Range"));
  7851. EXPECT_EQ(267U, res->body.size());
  7852. }
  7853. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7854. auto res = cli_.Get("/with-range",
  7855. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7857. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7858. }
  7859. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7860. auto res = cli_.Get("/with-range-customized-response",
  7861. Headers{{make_range_header({{1, 2}})}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7864. EXPECT_EQ(true, res->has_header("Content-Length"));
  7865. EXPECT_EQ(false, res->has_header("Content-Range"));
  7866. EXPECT_EQ(JSON_DATA, res->body);
  7867. }
  7868. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7869. auto res = cli_.Get("/with-range-customized-response",
  7870. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7873. EXPECT_EQ(true, res->has_header("Content-Length"));
  7874. EXPECT_EQ(false, res->has_header("Content-Range"));
  7875. EXPECT_EQ(JSON_DATA, res->body);
  7876. }
  7877. TEST_F(ServerTest, Issue1772) {
  7878. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7881. }
  7882. TEST_F(ServerTest, Issue609) {
  7883. auto res = cli_.Delete("/issue609");
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_EQ(std::string("ok"), res->body);
  7887. }
  7888. TEST_F(ServerTest, GetStreamedChunked) {
  7889. auto res = cli_.Get("/streamed-chunked");
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. EXPECT_EQ(StatusCode::OK_200, res->status);
  7892. EXPECT_EQ(std::string("123456789"), res->body);
  7893. }
  7894. TEST_F(ServerTest, GetStreamedChunked2) {
  7895. auto res = cli_.Get("/streamed-chunked2");
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ(StatusCode::OK_200, res->status);
  7898. EXPECT_EQ(std::string("123456789"), res->body);
  7899. }
  7900. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7901. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7903. EXPECT_EQ(StatusCode::OK_200, res->status);
  7904. EXPECT_EQ(std::string("123456789"), res->body);
  7905. EXPECT_TRUE(res->has_header("Trailer"));
  7906. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7907. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7908. // Trailers are now stored separately from headers (security fix)
  7909. EXPECT_EQ(2U, res->trailers.size());
  7910. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7911. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7912. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7913. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7914. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7915. // Verify trailers are NOT in headers (security verification)
  7916. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7917. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7918. }
  7919. TEST_F(ServerTest, LargeChunkedPost) {
  7920. Request req;
  7921. req.method = "POST";
  7922. req.path = "/large-chunked";
  7923. std::string host_and_port;
  7924. host_and_port += HOST;
  7925. host_and_port += ":";
  7926. host_and_port += std::to_string(PORT);
  7927. req.headers.emplace("Host", host_and_port.c_str());
  7928. req.headers.emplace("Accept", "*/*");
  7929. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7930. req.headers.emplace("Content-Type", "text/plain");
  7931. req.headers.emplace("Content-Length", "0");
  7932. req.headers.emplace("Transfer-Encoding", "chunked");
  7933. std::string long_string(30 * 1024u, 'a');
  7934. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7935. // Attempt to make a large enough post to exceed OS buffers, to test that
  7936. // the server handles short reads if the full chunk data isn't available.
  7937. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7938. auto res = std::make_shared<Response>();
  7939. auto error = Error::Success;
  7940. auto ret = cli_.send(req, *res, error);
  7941. ASSERT_TRUE(ret);
  7942. EXPECT_EQ(StatusCode::OK_200, res->status);
  7943. }
  7944. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7945. auto res = cli_.Get("/remote_addr");
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7949. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7950. }
  7951. TEST_F(ServerTest, GetMethodLocalAddr) {
  7952. auto res = cli_.Get("/local_addr");
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. EXPECT_EQ(StatusCode::OK_200, res->status);
  7955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7956. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7957. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7958. }
  7959. TEST_F(ServerTest, HTTPResponseSplitting) {
  7960. auto res = cli_.Get("/http_response_splitting");
  7961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7962. EXPECT_EQ(StatusCode::OK_200, res->status);
  7963. }
  7964. TEST_F(ServerTest, SlowRequest) {
  7965. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7966. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7967. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7968. }
  7969. #if 0
  7970. TEST_F(ServerTest, SlowPost) {
  7971. char buffer[64 * 1024];
  7972. memset(buffer, 0x42, sizeof(buffer));
  7973. auto res = cli_.Post(
  7974. "/slowpost", 64 * 1024 * 1024,
  7975. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7976. auto ret = sink.write(buffer, sizeof(buffer));
  7977. EXPECT_TRUE(ret);
  7978. return true;
  7979. },
  7980. "text/plain");
  7981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7982. EXPECT_EQ(StatusCode::OK_200, res->status);
  7983. }
  7984. TEST_F(ServerTest, SlowPostFail) {
  7985. char buffer[64 * 1024];
  7986. memset(buffer, 0x42, sizeof(buffer));
  7987. cli_.set_write_timeout(std::chrono::seconds(0));
  7988. auto res = cli_.Post(
  7989. "/slowpost", 64 * 1024 * 1024,
  7990. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7991. sink.write(buffer, sizeof(buffer));
  7992. return true;
  7993. },
  7994. "text/plain");
  7995. ASSERT_TRUE(!res);
  7996. EXPECT_EQ(Error::Write, res.error());
  7997. }
  7998. #endif
  7999. TEST_F(ServerTest, Put) {
  8000. auto res = cli_.Put("/put", "PUT", "text/plain");
  8001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. EXPECT_EQ("PUT", res->body);
  8004. }
  8005. TEST_F(ServerTest, PutWithContentProvider) {
  8006. auto res = cli_.Put(
  8007. "/put", 3,
  8008. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8009. sink.os << "PUT";
  8010. return true;
  8011. },
  8012. "text/plain");
  8013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. EXPECT_EQ("PUT", res->body);
  8016. }
  8017. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8018. auto res = cli_.Post(
  8019. "/post", 42,
  8020. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8021. return false;
  8022. },
  8023. "text/plain");
  8024. ASSERT_TRUE(!res);
  8025. EXPECT_EQ(Error::Canceled, res.error());
  8026. }
  8027. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8028. auto res = cli_.Put(
  8029. "/put",
  8030. [](size_t /*offset*/, DataSink &sink) {
  8031. sink.os << "PUT";
  8032. sink.done();
  8033. return true;
  8034. },
  8035. "text/plain");
  8036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. EXPECT_EQ("PUT", res->body);
  8039. }
  8040. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8041. auto res = cli_.Post(
  8042. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8043. "text/plain");
  8044. ASSERT_TRUE(!res);
  8045. EXPECT_EQ(Error::Canceled, res.error());
  8046. }
  8047. TEST_F(ServerTest, PostLoopBack) {
  8048. std::string body;
  8049. auto res = cli_.Post(
  8050. "/post-loopback", 9,
  8051. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8052. EXPECT_EQ(9u, length);
  8053. sink.write("123", 3);
  8054. sink.write("456", 3);
  8055. sink.write("789", 3);
  8056. return true;
  8057. },
  8058. "text/plain",
  8059. [&body](const char *data, size_t data_length) {
  8060. body.append(data, data_length);
  8061. return true;
  8062. });
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ(StatusCode::OK_200, res->status);
  8065. EXPECT_EQ("123456789", body);
  8066. }
  8067. TEST_F(ServerTest, PutLoopBack) {
  8068. std::string body;
  8069. auto res = cli_.Put(
  8070. "/put-loopback", 9,
  8071. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8072. EXPECT_EQ(9u, length);
  8073. sink.write("123", 3);
  8074. sink.write("456", 3);
  8075. sink.write("789", 3);
  8076. return true;
  8077. },
  8078. "text/plain",
  8079. [&body](const char *data, size_t data_length) {
  8080. body.append(data, data_length);
  8081. return true;
  8082. });
  8083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8084. EXPECT_EQ(StatusCode::OK_200, res->status);
  8085. EXPECT_EQ("123456789", body);
  8086. }
  8087. TEST_F(ServerTest, PatchLoopBack) {
  8088. std::string body;
  8089. auto res = cli_.Patch(
  8090. "/patch-loopback", 9,
  8091. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8092. EXPECT_EQ(9u, length);
  8093. sink.write("123", 3);
  8094. sink.write("456", 3);
  8095. sink.write("789", 3);
  8096. return true;
  8097. },
  8098. "text/plain",
  8099. [&body](const char *data, size_t data_length) {
  8100. body.append(data, data_length);
  8101. return true;
  8102. });
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ("123456789", body);
  8106. }
  8107. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8108. std::string body;
  8109. auto res = cli_.Post(
  8110. "/post-loopback",
  8111. [](size_t /*offset*/, DataSink &sink) {
  8112. sink.write("123", 3);
  8113. sink.write("456", 3);
  8114. sink.write("789", 3);
  8115. sink.done();
  8116. return true;
  8117. },
  8118. "text/plain",
  8119. [&body](const char *data, size_t data_length) {
  8120. body.append(data, data_length);
  8121. return true;
  8122. });
  8123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8124. EXPECT_EQ(StatusCode::OK_200, res->status);
  8125. EXPECT_EQ("123456789", body);
  8126. }
  8127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8128. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8129. cli_.set_compress(true);
  8130. auto res = cli_.Put(
  8131. "/put", 3,
  8132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8133. sink.os << "PUT";
  8134. return true;
  8135. },
  8136. "text/plain");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::OK_200, res->status);
  8139. EXPECT_EQ("PUT", res->body);
  8140. }
  8141. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8142. cli_.set_compress(true);
  8143. auto res = cli_.Post(
  8144. "/post", 42,
  8145. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8146. return false;
  8147. },
  8148. "text/plain");
  8149. ASSERT_TRUE(!res);
  8150. EXPECT_EQ(Error::Canceled, res.error());
  8151. }
  8152. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8153. cli_.set_compress(true);
  8154. auto res = cli_.Put(
  8155. "/put",
  8156. [](size_t /*offset*/, DataSink &sink) {
  8157. sink.os << "PUT";
  8158. sink.done();
  8159. return true;
  8160. },
  8161. "text/plain");
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ(StatusCode::OK_200, res->status);
  8164. EXPECT_EQ("PUT", res->body);
  8165. }
  8166. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8167. cli_.set_compress(true);
  8168. auto res = cli_.Post(
  8169. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8170. "text/plain");
  8171. ASSERT_TRUE(!res);
  8172. EXPECT_EQ(Error::Canceled, res.error());
  8173. }
  8174. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8175. cli_.set_compress(true);
  8176. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. EXPECT_EQ(LARGE_DATA, res->body);
  8180. }
  8181. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8182. #ifdef CPPHTTPLIB_SSL_ENABLED
  8183. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8184. Client cli(s.c_str());
  8185. cli.enable_server_certificate_verification(false);
  8186. #else
  8187. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8188. Client cli(s.c_str());
  8189. #endif
  8190. cli.set_compress(true);
  8191. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ(LARGE_DATA, res->body);
  8195. // The compressed size should be less than a 10th of the original. May vary
  8196. // depending on the zlib library.
  8197. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8198. static_cast<uint64_t>(10 * 1024 * 1024));
  8199. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8200. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8201. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8202. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8203. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8204. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8205. #endif
  8206. }
  8207. TEST_F(ServerTest, PutContentWithDeflate) {
  8208. cli_.set_compress(false);
  8209. Headers headers;
  8210. headers.emplace("Content-Encoding", "deflate");
  8211. // PUT in deflate format:
  8212. auto res = cli_.Put("/put", headers,
  8213. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::OK_200, res->status);
  8216. EXPECT_EQ("PUT", res->body);
  8217. }
  8218. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8219. Headers headers;
  8220. headers.emplace("Accept-Encoding", "gzip, deflate");
  8221. auto res = cli_.Get("/streamed-chunked", headers);
  8222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8223. EXPECT_EQ(StatusCode::OK_200, res->status);
  8224. EXPECT_EQ(std::string("123456789"), res->body);
  8225. }
  8226. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8227. Headers headers;
  8228. headers.emplace("Accept-Encoding", "gzip, deflate");
  8229. auto res = cli_.Get("/streamed-chunked2", headers);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::OK_200, res->status);
  8232. EXPECT_EQ(std::string("123456789"), res->body);
  8233. }
  8234. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8235. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8237. EXPECT_EQ(StatusCode::OK_200, res->status);
  8238. }
  8239. TEST(GzipDecompressor, ChunkedDecompression) {
  8240. std::string data;
  8241. for (size_t i = 0; i < 32 * 1024; ++i) {
  8242. data.push_back(static_cast<char>('a' + i % 26));
  8243. }
  8244. std::string compressed_data;
  8245. {
  8246. httplib::detail::gzip_compressor compressor;
  8247. bool result = compressor.compress(
  8248. data.data(), data.size(),
  8249. /*last=*/true,
  8250. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8251. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8252. compressed_data_size);
  8253. return true;
  8254. });
  8255. ASSERT_TRUE(result);
  8256. }
  8257. std::string decompressed_data;
  8258. {
  8259. httplib::detail::gzip_decompressor decompressor;
  8260. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8261. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8262. size_t chunk_size = 130;
  8263. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8264. chunk_begin += chunk_size) {
  8265. size_t current_chunk_size =
  8266. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8267. bool result = decompressor.decompress(
  8268. compressed_data.data() + chunk_begin, current_chunk_size,
  8269. [&](const char *decompressed_data_chunk,
  8270. size_t decompressed_data_chunk_size) {
  8271. decompressed_data.insert(decompressed_data.size(),
  8272. decompressed_data_chunk,
  8273. decompressed_data_chunk_size);
  8274. return true;
  8275. });
  8276. ASSERT_TRUE(result);
  8277. }
  8278. }
  8279. ASSERT_EQ(data, decompressed_data);
  8280. }
  8281. TEST(GzipDecompressor, DeflateDecompression) {
  8282. std::string original_text = "Raw deflate without gzip";
  8283. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8284. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8285. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8286. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8287. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8288. std::string decompressed_data;
  8289. {
  8290. httplib::detail::gzip_decompressor decompressor;
  8291. bool result = decompressor.decompress(
  8292. compressed_data.data(), compressed_data.size(),
  8293. [&](const char *decompressed_data_chunk,
  8294. size_t decompressed_data_chunk_size) {
  8295. decompressed_data.insert(decompressed_data.size(),
  8296. decompressed_data_chunk,
  8297. decompressed_data_chunk_size);
  8298. return true;
  8299. });
  8300. ASSERT_TRUE(result);
  8301. }
  8302. ASSERT_EQ(original_text, decompressed_data);
  8303. }
  8304. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8305. std::string original_text = "Raw deflate without gzip";
  8306. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8307. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8308. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8309. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8310. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8311. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8312. std::string decompressed_data;
  8313. {
  8314. httplib::detail::gzip_decompressor decompressor;
  8315. bool result = decompressor.decompress(
  8316. compressed_data.data(), compressed_data.size(),
  8317. [&](const char *decompressed_data_chunk,
  8318. size_t decompressed_data_chunk_size) {
  8319. decompressed_data.insert(decompressed_data.size(),
  8320. decompressed_data_chunk,
  8321. decompressed_data_chunk_size);
  8322. return true;
  8323. });
  8324. ASSERT_TRUE(result);
  8325. }
  8326. ASSERT_EQ(original_text, decompressed_data);
  8327. }
  8328. #endif
  8329. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8330. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8331. Headers headers;
  8332. headers.emplace("Accept-Encoding", "br");
  8333. auto res = cli_.Get("/streamed-chunked", headers);
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ(StatusCode::OK_200, res->status);
  8336. EXPECT_EQ(std::string("123456789"), res->body);
  8337. }
  8338. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8339. Headers headers;
  8340. headers.emplace("Accept-Encoding", "br");
  8341. auto res = cli_.Get("/streamed-chunked2", headers);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::OK_200, res->status);
  8344. EXPECT_EQ(std::string("123456789"), res->body);
  8345. }
  8346. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8347. cli_.set_compress(true);
  8348. auto res = cli_.Put(
  8349. "/put", 3,
  8350. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8351. sink.os << "PUT";
  8352. return true;
  8353. },
  8354. "text/plain");
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("PUT", res->body);
  8358. }
  8359. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8360. cli_.set_compress(true);
  8361. auto res = cli_.Put(
  8362. "/put",
  8363. [](size_t /*offset*/, DataSink &sink) {
  8364. sink.os << "PUT";
  8365. sink.done();
  8366. return true;
  8367. },
  8368. "text/plain");
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. EXPECT_EQ("PUT", res->body);
  8372. }
  8373. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8374. cli_.set_compress(true);
  8375. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. EXPECT_EQ(LARGE_DATA, res->body);
  8379. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8380. }
  8381. #endif
  8382. TEST_F(ServerTest, Patch) {
  8383. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. EXPECT_EQ("PATCH", res->body);
  8387. }
  8388. TEST_F(ServerTest, Delete) {
  8389. auto res = cli_.Delete("/delete");
  8390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8391. EXPECT_EQ(StatusCode::OK_200, res->status);
  8392. EXPECT_EQ("DELETE", res->body);
  8393. }
  8394. TEST_F(ServerTest, DeleteContentReceiver) {
  8395. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_EQ(StatusCode::OK_200, res->status);
  8398. EXPECT_EQ("content", res->body);
  8399. }
  8400. TEST_F(ServerTest, Options) {
  8401. auto res = cli_.Options("*");
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8405. EXPECT_TRUE(res->body.empty());
  8406. }
  8407. TEST_F(ServerTest, URL) {
  8408. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. }
  8412. TEST_F(ServerTest, ArrayParam) {
  8413. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::OK_200, res->status);
  8416. }
  8417. TEST_F(ServerTest, ArrayParamValues) {
  8418. auto res =
  8419. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. }
  8423. TEST_F(ServerTest, NoMultipleHeaders) {
  8424. Headers headers = {{"Content-Length", "5"}};
  8425. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8426. "text/plain");
  8427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8428. EXPECT_EQ(StatusCode::OK_200, res->status);
  8429. }
  8430. TEST_F(ServerTest, PostContentReceiver) {
  8431. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. ASSERT_EQ(StatusCode::OK_200, res->status);
  8434. ASSERT_EQ("content", res->body);
  8435. }
  8436. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8437. UploadFormDataItems items = {
  8438. {"text1", "text default", "", ""},
  8439. {"text2", "aωb", "", ""},
  8440. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8441. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8442. {"file3", "", "", "application/octet-stream"},
  8443. };
  8444. auto res = cli_.Post("/content_receiver", items);
  8445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8449. UploadFormDataItems items = {
  8450. {"text1", "text default", "", ""},
  8451. {"text2", "aωb", "", ""},
  8452. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8453. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8454. {"file3", "", "", "application/octet-stream"},
  8455. };
  8456. auto boundary = std::string("+++++");
  8457. std::string body;
  8458. for (const auto &item : items) {
  8459. body += "--" + boundary + "\r\n";
  8460. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8461. if (!item.filename.empty()) {
  8462. body += "; filename=\"" + item.filename + "\"";
  8463. }
  8464. body += "\r\n";
  8465. if (!item.content_type.empty()) {
  8466. body += "Content-Type: " + item.content_type + "\r\n";
  8467. }
  8468. body += "\r\n";
  8469. body += item.content + "\r\n";
  8470. }
  8471. body += "--" + boundary + "--\r\n";
  8472. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8473. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8475. EXPECT_EQ(StatusCode::OK_200, res->status);
  8476. }
  8477. TEST(MultipartFormDataTest, FieldEscaping) {
  8478. Server svr;
  8479. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8480. const ContentReader &content_reader) {
  8481. ASSERT_TRUE(req.is_multipart_form_data());
  8482. std::vector<FormData> received;
  8483. content_reader(
  8484. [&](const FormData &file) {
  8485. received.push_back(file);
  8486. return true;
  8487. },
  8488. [&](const char *data, size_t data_length) {
  8489. received.back().content.append(data, data_length);
  8490. return true;
  8491. });
  8492. // '"', CR and LF in names and filenames are escaped following the
  8493. // WHATWG HTML standard, so each part still parses as a single part
  8494. // with no injected headers. Content types get CR/LF escaped too,
  8495. // while '"' (legal there, e.g. quoted charset) is preserved.
  8496. ASSERT_EQ(4U, received.size());
  8497. EXPECT_EQ("na%22me", received[0].name);
  8498. EXPECT_EQ("quoted name", received[0].content);
  8499. EXPECT_EQ("file", received[1].name);
  8500. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8501. received[1].filename);
  8502. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8503. EXPECT_EQ("injected", received[1].content);
  8504. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8505. EXPECT_EQ("my%22file.txt", received[2].filename);
  8506. EXPECT_EQ("cr lf name", received[2].content);
  8507. EXPECT_EQ("typed", received[3].name);
  8508. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8509. received[3].content_type);
  8510. EXPECT_EQ("typed content", received[3].content);
  8511. });
  8512. auto port = svr.bind_to_any_port("localhost");
  8513. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8514. auto se = detail::scope_exit([&] {
  8515. svr.stop();
  8516. t.join();
  8517. ASSERT_FALSE(svr.is_running());
  8518. });
  8519. svr.wait_until_ready();
  8520. Client cli("localhost", port);
  8521. UploadFormDataItems items = {
  8522. {"na\"me", "quoted name", "", ""},
  8523. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8524. "application/octet-stream"},
  8525. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8526. {"typed", "typed content", "",
  8527. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8528. };
  8529. auto res = cli.Post("/post", items);
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8534. const UploadFormDataItems items = {
  8535. {"name1", "Content 1", "", ""},
  8536. {"name2", "Content 2", "file2.txt", "text/plain"},
  8537. };
  8538. Server svr;
  8539. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8540. const ContentReader &content_reader) {
  8541. ASSERT_TRUE(req.is_multipart_form_data());
  8542. std::vector<FormData> received;
  8543. content_reader(
  8544. [&](const FormData &file) {
  8545. received.push_back(file);
  8546. return true;
  8547. },
  8548. [&](const char *data, size_t data_length) {
  8549. received.back().content.append(data, data_length);
  8550. return true;
  8551. });
  8552. ASSERT_EQ(2U, received.size());
  8553. EXPECT_EQ("name1", received[0].name);
  8554. EXPECT_EQ("Content 1", received[0].content);
  8555. EXPECT_EQ("name2", received[1].name);
  8556. EXPECT_EQ("Content 2", received[1].content);
  8557. EXPECT_EQ("file2.txt", received[1].filename);
  8558. EXPECT_EQ("text/plain", received[1].content_type);
  8559. });
  8560. auto port = svr.bind_to_any_port("localhost");
  8561. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. t.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. });
  8567. svr.wait_until_ready();
  8568. Client cli("localhost", port);
  8569. // Whole-body serialization with a generated boundary
  8570. {
  8571. MultipartFormDataWriter writer;
  8572. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8573. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8574. writer.content_type());
  8575. auto body = writer.serialize(items);
  8576. EXPECT_EQ(body.size(), writer.content_length(items));
  8577. auto res = cli.Post("/post", body, writer.content_type());
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. // Per-part framing with a custom boundary via a content provider
  8582. {
  8583. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8584. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8585. MultipartFormDataWriter writer("custom-boundary_123");
  8586. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8587. std::string body;
  8588. for (const auto &item : items) {
  8589. body += writer.item_begin(item);
  8590. body += item.content;
  8591. body += MultipartFormDataWriter::item_end();
  8592. }
  8593. body += writer.finish();
  8594. EXPECT_EQ(body.size(), writer.content_length(items));
  8595. auto res = cli.Post(
  8596. "/post", body.size(),
  8597. [&](size_t offset, size_t length, DataSink &sink) {
  8598. sink.write(body.data() + offset, length);
  8599. return true;
  8600. },
  8601. writer.content_type());
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. }
  8605. }
  8606. TEST_F(ServerTest, PostContentReceiverGzip) {
  8607. cli_.set_compress(true);
  8608. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. ASSERT_EQ(StatusCode::OK_200, res->status);
  8611. ASSERT_EQ("content", res->body);
  8612. }
  8613. TEST_F(ServerTest, PutContentReceiver) {
  8614. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. ASSERT_EQ(StatusCode::OK_200, res->status);
  8617. ASSERT_EQ("content", res->body);
  8618. }
  8619. TEST_F(ServerTest, PatchContentReceiver) {
  8620. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. ASSERT_EQ(StatusCode::OK_200, res->status);
  8623. ASSERT_EQ("content", res->body);
  8624. }
  8625. template <typename ClientType>
  8626. void TestWithHeadersAndContentReceiver(
  8627. ClientType &cli,
  8628. std::function<Result(ClientType &, const std::string &, const Headers &,
  8629. const std::string &, const std::string &,
  8630. ContentReceiver, DownloadProgress)>
  8631. request_func) {
  8632. Headers headers;
  8633. headers.emplace("X-Custom-Header", "test-value");
  8634. std::string received_body;
  8635. auto res = request_func(
  8636. cli, "/content_receiver", headers, "content", "application/json",
  8637. [&](const char *data, size_t data_length) {
  8638. received_body.append(data, data_length);
  8639. return true;
  8640. },
  8641. nullptr);
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ("content", received_body);
  8645. }
  8646. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8647. #ifdef CPPHTTPLIB_SSL_ENABLED
  8648. using ClientT = SSLClient;
  8649. #else
  8650. using ClientT = Client;
  8651. #endif
  8652. TestWithHeadersAndContentReceiver<ClientT>(
  8653. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8654. const std::string &body, const std::string &content_type,
  8655. ContentReceiver receiver, DownloadProgress progress) {
  8656. return cli.Post(path, headers, body, content_type, receiver, progress);
  8657. });
  8658. }
  8659. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8660. #ifdef CPPHTTPLIB_SSL_ENABLED
  8661. using ClientT = SSLClient;
  8662. #else
  8663. using ClientT = Client;
  8664. #endif
  8665. TestWithHeadersAndContentReceiver<ClientT>(
  8666. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8667. const std::string &body, const std::string &content_type,
  8668. ContentReceiver receiver, DownloadProgress progress) {
  8669. return cli.Put(path, headers, body, content_type, receiver, progress);
  8670. });
  8671. }
  8672. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8673. #ifdef CPPHTTPLIB_SSL_ENABLED
  8674. using ClientT = SSLClient;
  8675. #else
  8676. using ClientT = Client;
  8677. #endif
  8678. TestWithHeadersAndContentReceiver<ClientT>(
  8679. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8680. const std::string &body, const std::string &content_type,
  8681. ContentReceiver receiver, DownloadProgress progress) {
  8682. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8683. });
  8684. }
  8685. template <typename ClientType>
  8686. void TestWithHeadersAndContentReceiverWithProgress(
  8687. ClientType &cli,
  8688. std::function<Result(ClientType &, const std::string &, const Headers &,
  8689. const std::string &, const std::string &,
  8690. ContentReceiver, DownloadProgress)>
  8691. request_func) {
  8692. Headers headers;
  8693. headers.emplace("X-Test-Header", "progress-test");
  8694. std::string received_body;
  8695. auto progress_called = false;
  8696. auto res = request_func(
  8697. cli, "/content_receiver", headers, "content", "text/plain",
  8698. [&](const char *data, size_t data_length) {
  8699. received_body.append(data, data_length);
  8700. return true;
  8701. },
  8702. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8703. progress_called = true;
  8704. return true;
  8705. });
  8706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8707. EXPECT_EQ(StatusCode::OK_200, res->status);
  8708. EXPECT_EQ("content", received_body);
  8709. EXPECT_TRUE(progress_called);
  8710. }
  8711. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8712. #ifdef CPPHTTPLIB_SSL_ENABLED
  8713. using ClientT = SSLClient;
  8714. #else
  8715. using ClientT = Client;
  8716. #endif
  8717. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8719. const std::string &body, const std::string &content_type,
  8720. ContentReceiver receiver, DownloadProgress progress) {
  8721. return cli.Post(path, headers, body, content_type, receiver, progress);
  8722. });
  8723. }
  8724. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8725. #ifdef CPPHTTPLIB_SSL_ENABLED
  8726. using ClientT = SSLClient;
  8727. #else
  8728. using ClientT = Client;
  8729. #endif
  8730. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8732. const std::string &body, const std::string &content_type,
  8733. ContentReceiver receiver, DownloadProgress progress) {
  8734. return cli.Put(path, headers, body, content_type, receiver, progress);
  8735. });
  8736. }
  8737. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8738. #ifdef CPPHTTPLIB_SSL_ENABLED
  8739. using ClientT = SSLClient;
  8740. #else
  8741. using ClientT = Client;
  8742. #endif
  8743. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8744. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8745. const std::string &body, const std::string &content_type,
  8746. ContentReceiver receiver, DownloadProgress progress) {
  8747. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8748. });
  8749. }
  8750. template <typename ClientType>
  8751. void TestWithHeadersAndContentReceiverError(
  8752. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8753. const Headers &, const std::string &,
  8754. const std::string &, ContentReceiver)>
  8755. request_func) {
  8756. Headers headers;
  8757. headers.emplace("X-Error-Test", "true");
  8758. std::string received_body;
  8759. auto receiver_failed = false;
  8760. auto res =
  8761. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8762. [&](const char *data, size_t data_length) {
  8763. received_body.append(data, data_length);
  8764. receiver_failed = true;
  8765. return false;
  8766. });
  8767. ASSERT_FALSE(res);
  8768. EXPECT_TRUE(receiver_failed);
  8769. }
  8770. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8771. #ifdef CPPHTTPLIB_SSL_ENABLED
  8772. using ClientT = SSLClient;
  8773. #else
  8774. using ClientT = Client;
  8775. #endif
  8776. TestWithHeadersAndContentReceiverError<ClientT>(
  8777. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8778. const std::string &body, const std::string &content_type,
  8779. ContentReceiver receiver) {
  8780. return cli.Post(path, headers, body, content_type, receiver);
  8781. });
  8782. }
  8783. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8784. #ifdef CPPHTTPLIB_SSL_ENABLED
  8785. using ClientT = SSLClient;
  8786. #else
  8787. using ClientT = Client;
  8788. #endif
  8789. TestWithHeadersAndContentReceiverError<ClientT>(
  8790. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8791. const std::string &body, const std::string &content_type,
  8792. ContentReceiver receiver) {
  8793. return cli.Put(path, headers, body, content_type, receiver);
  8794. });
  8795. }
  8796. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8797. #ifdef CPPHTTPLIB_SSL_ENABLED
  8798. using ClientT = SSLClient;
  8799. #else
  8800. using ClientT = Client;
  8801. #endif
  8802. TestWithHeadersAndContentReceiverError<ClientT>(
  8803. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8804. const std::string &body, const std::string &content_type,
  8805. ContentReceiver receiver) {
  8806. return cli.Patch(path, headers, body, content_type, receiver);
  8807. });
  8808. }
  8809. TEST_F(ServerTest, PostQueryStringAndBody) {
  8810. auto res =
  8811. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8813. ASSERT_EQ(StatusCode::OK_200, res->status);
  8814. }
  8815. TEST_F(ServerTest, HTTP2Magic) {
  8816. Request req;
  8817. req.method = "PRI";
  8818. req.path = "*";
  8819. req.body = "SM";
  8820. auto res = std::make_shared<Response>();
  8821. auto error = Error::Success;
  8822. auto ret = cli_.send(req, *res, error);
  8823. ASSERT_TRUE(ret);
  8824. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8825. }
  8826. TEST_F(ServerTest, KeepAlive) {
  8827. auto res = cli_.Get("/hi");
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ(StatusCode::OK_200, res->status);
  8830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8831. EXPECT_EQ("Hello World!", res->body);
  8832. res = cli_.Get("/hi");
  8833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8834. EXPECT_EQ(StatusCode::OK_200, res->status);
  8835. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8836. EXPECT_EQ("Hello World!", res->body);
  8837. res = cli_.Get("/hi");
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8841. EXPECT_EQ("Hello World!", res->body);
  8842. res = cli_.Get("/not-exist");
  8843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8845. res = cli_.Post("/empty", "", "text/plain");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("empty", res->body);
  8850. EXPECT_EQ("close", res->get_header_value("Connection"));
  8851. res = cli_.Post(
  8852. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8853. "text/plain");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ(StatusCode::OK_200, res->status);
  8856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8857. EXPECT_EQ("empty", res->body);
  8858. cli_.set_keep_alive(false);
  8859. res = cli_.Get("/last-request");
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ(StatusCode::OK_200, res->status);
  8862. EXPECT_EQ("close", res->get_header_value("Connection"));
  8863. }
  8864. TEST_F(ServerTest, TooManyRedirect) {
  8865. cli_.set_follow_location(true);
  8866. auto res = cli_.Get("/redirect/0");
  8867. ASSERT_TRUE(!res);
  8868. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8869. }
  8870. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8871. Request req;
  8872. req.method = "FOOBAR";
  8873. req.path = "/hi";
  8874. cli_.set_keep_alive(true);
  8875. auto res = cli_.send(req);
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8878. EXPECT_EQ("close", res->get_header_value("Connection"));
  8879. EXPECT_FALSE(cli_.is_socket_open());
  8880. }
  8881. TEST_F(ServerTest, CustomRouteReadsBody) {
  8882. const std::string xml =
  8883. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8884. Request req;
  8885. req.method = "PROPFIND";
  8886. req.path = "/dav/dir";
  8887. req.set_header("Depth", "1");
  8888. req.body = xml;
  8889. auto res = cli_.send(req);
  8890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8891. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8892. EXPECT_EQ(xml, res->body);
  8893. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8894. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8895. }
  8896. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8897. Request req;
  8898. req.method = "PROPFIND";
  8899. req.path = "/dav/42";
  8900. auto res = cli_.send(req);
  8901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8902. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8903. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8904. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8905. }
  8906. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8907. Request req;
  8908. req.method = "PROPFIND";
  8909. req.path = "/dav-re/123";
  8910. auto res = cli_.send(req);
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8913. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8914. }
  8915. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8916. Request req;
  8917. req.method = "MKCOL";
  8918. req.path = "/dav-mkcol";
  8919. auto res = cli_.send(req);
  8920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8921. EXPECT_EQ(StatusCode::Created_201, res->status);
  8922. }
  8923. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8924. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8925. Request req;
  8926. req.method = "REPORT";
  8927. req.path = "/dav-report";
  8928. req.body = xml;
  8929. auto res = cli_.send(req);
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8932. EXPECT_EQ(xml, res->body);
  8933. }
  8934. // A content reader route must fire even when the request carries no body,
  8935. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8936. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8937. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8938. Request req;
  8939. req.method = "REPORT";
  8940. req.path = "/dav-report";
  8941. auto res = cli_.send(req);
  8942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8943. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8944. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8945. }
  8946. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8947. Request req;
  8948. req.method = "PROPFIND";
  8949. req.path = "/not-dav";
  8950. auto res = cli_.send(req);
  8951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8953. }
  8954. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8955. Request req;
  8956. req.method = "UNLOCK";
  8957. req.path = "/dav/dir";
  8958. cli_.set_keep_alive(true);
  8959. auto res = cli_.send(req);
  8960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8962. EXPECT_EQ("close", res->get_header_value("Connection"));
  8963. EXPECT_FALSE(cli_.is_socket_open());
  8964. }
  8965. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8966. // The mount point serves this path, but only for GET and HEAD.
  8967. auto get_res = cli_.Get("/dir/index.html");
  8968. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8969. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8970. Request req;
  8971. req.method = "PROPFIND";
  8972. req.path = "/dir/index.html";
  8973. auto res = cli_.send(req);
  8974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8975. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8976. }
  8977. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8978. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8979. cli_.set_keep_alive(true);
  8980. for (auto i = 0; i < 2; i++) {
  8981. Request req;
  8982. req.method = "PROPFIND";
  8983. req.path = "/dav/dir";
  8984. req.body = xml;
  8985. auto res = cli_.send(req);
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8988. EXPECT_EQ(xml, res->body);
  8989. EXPECT_TRUE(cli_.is_socket_open());
  8990. }
  8991. // A built-in method must still be served on the same connection.
  8992. cli_.set_keep_alive(false);
  8993. auto res = cli_.Get("/hi");
  8994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8995. EXPECT_EQ(StatusCode::OK_200, res->status);
  8996. EXPECT_EQ("close", res->get_header_value("Connection"));
  8997. }
  8998. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8999. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9000. Request req;
  9001. req.method = "PROPFIND";
  9002. req.path = "/dav/dir";
  9003. req.set_header("Expect", "100-continue");
  9004. req.body = xml;
  9005. auto res = cli_.send(req);
  9006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9007. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9008. EXPECT_EQ(xml, res->body);
  9009. }
  9010. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9011. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9012. TEST_F(ServerTest, Gzip) {
  9013. Headers headers;
  9014. headers.emplace("Accept-Encoding", "gzip, deflate");
  9015. auto res = cli_.Get("/compress", headers);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9019. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9020. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9021. "7890123456789012345678901234567890",
  9022. res->body);
  9023. EXPECT_EQ(StatusCode::OK_200, res->status);
  9024. }
  9025. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9026. Headers headers;
  9027. headers.emplace("Accept-Encoding", "gzip, deflate");
  9028. auto res = cli_.Get("/compress-with-charset", headers);
  9029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9031. EXPECT_EQ("application/json; charset=utf-8",
  9032. res->get_header_value("Content-Type"));
  9033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9034. "7890123456789012345678901234567890",
  9035. res->body);
  9036. EXPECT_EQ(StatusCode::OK_200, res->status);
  9037. }
  9038. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9039. Headers headers;
  9040. headers.emplace("Accept-Encoding", "");
  9041. auto res = cli_.Get("/compress", headers);
  9042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9043. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9047. "7890123456789012345678901234567890",
  9048. res->body);
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. }
  9051. TEST_F(ServerTest, GzipWithContentReceiver) {
  9052. Headers headers;
  9053. headers.emplace("Accept-Encoding", "gzip, deflate");
  9054. std::string body;
  9055. auto res =
  9056. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9057. EXPECT_EQ(100U, data_length);
  9058. body.append(data, data_length);
  9059. return true;
  9060. });
  9061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9062. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9063. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9064. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9065. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9066. "7890123456789012345678901234567890",
  9067. body);
  9068. EXPECT_EQ(StatusCode::OK_200, res->status);
  9069. }
  9070. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9071. Headers headers;
  9072. headers.emplace("Accept-Encoding", "gzip, deflate");
  9073. cli_.set_decompress(false);
  9074. auto res = cli_.Get("/compress", headers);
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9078. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9079. EXPECT_EQ(33U, res->body.size());
  9080. EXPECT_EQ(StatusCode::OK_200, res->status);
  9081. }
  9082. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9083. Headers headers;
  9084. headers.emplace("Accept-Encoding", "");
  9085. std::string body;
  9086. auto res =
  9087. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9088. EXPECT_EQ(100U, data_length);
  9089. body.append(data, data_length);
  9090. return true;
  9091. });
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9095. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9096. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9097. "7890123456789012345678901234567890",
  9098. body);
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. }
  9101. TEST_F(ServerTest, NoGzip) {
  9102. Headers headers;
  9103. headers.emplace("Accept-Encoding", "gzip, deflate");
  9104. auto res = cli_.Get("/nocompress", headers);
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9107. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9108. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9109. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9110. "7890123456789012345678901234567890",
  9111. res->body);
  9112. EXPECT_EQ(StatusCode::OK_200, res->status);
  9113. }
  9114. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9115. Headers headers;
  9116. headers.emplace("Accept-Encoding", "gzip, deflate");
  9117. std::string body;
  9118. auto res = cli_.Get("/nocompress", headers,
  9119. [&](const char *data, size_t data_length) {
  9120. EXPECT_EQ(100U, data_length);
  9121. body.append(data, data_length);
  9122. return true;
  9123. });
  9124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9125. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9126. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9127. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9128. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9129. "7890123456789012345678901234567890",
  9130. body);
  9131. EXPECT_EQ(StatusCode::OK_200, res->status);
  9132. }
  9133. TEST_F(ServerTest, MultipartFormDataGzip) {
  9134. UploadFormDataItems items = {
  9135. {"key1", "test", "", ""},
  9136. {"key2", "--abcdefg123", "", ""},
  9137. };
  9138. cli_.set_compress(true);
  9139. auto res = cli_.Post("/compress-multipart", items);
  9140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. }
  9143. #endif
  9144. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9145. // Static file compression is opt-in, so these run their own server rather than
  9146. // flipping it on for the shared ServerTest fixture, which would silently
  9147. // rewrite what every other static file test is asserting.
  9148. class StaticFileCompressionTest : public ::testing::Test {
  9149. protected:
  9150. void TearDown() override {
  9151. if (t_.joinable()) {
  9152. svr_.stop();
  9153. t_.join();
  9154. }
  9155. }
  9156. int start(const std::function<void(Server &)> &configure = nullptr) {
  9157. // Serves the same tree as a directory of build-time compressed assets
  9158. // would be served: the mount point names the coding the files are already
  9159. // stored in. Registered before "/" so it is the one that matches.
  9160. svr_.set_mount_point("/pre-encoded", "./www",
  9161. {{"Content-Encoding", "gzip"}});
  9162. svr_.set_mount_point("/", "./www");
  9163. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9164. res.set_file_content("./www/dir/index.html", "text/html");
  9165. });
  9166. svr_.Get("/pre-encoded-file-content",
  9167. [](const Request & /*req*/, Response &res) {
  9168. res.set_header("Content-Encoding", "gzip");
  9169. res.set_file_content("./www/dir/index.html", "text/html");
  9170. });
  9171. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9172. res.set_content_provider(
  9173. 6, "text/plain",
  9174. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9175. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9176. return true;
  9177. });
  9178. });
  9179. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9180. res.set_content_provider(
  9181. 1000, "text/plain",
  9182. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9183. if (offset < 100) {
  9184. std::string data(100, 'A');
  9185. sink.write(data.data(), data.size());
  9186. return true;
  9187. }
  9188. std::this_thread::sleep_for(std::chrono::seconds(2));
  9189. std::string data(900, 'B');
  9190. sink.write(data.data(), data.size());
  9191. return true;
  9192. });
  9193. });
  9194. if (configure) { configure(svr_); }
  9195. auto port = svr_.bind_to_any_port(HOST);
  9196. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9197. svr_.wait_until_ready();
  9198. return port;
  9199. }
  9200. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9201. // Every file under ./www except 1MB.txt is smaller than the default
  9202. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9203. // it out of the way.
  9204. static void enable_without_floor(Server &svr) {
  9205. svr.set_static_file_compression(true);
  9206. svr.set_static_file_compression_min_length(0);
  9207. }
  9208. Server svr_;
  9209. std::thread t_;
  9210. };
  9211. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9212. auto port = start();
  9213. Client cli(HOST, port);
  9214. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9216. EXPECT_EQ(StatusCode::OK_200, res->status);
  9217. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9218. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9219. EXPECT_EQ(1048576U, res->body.size());
  9220. }
  9221. TEST_F(StaticFileCompressionTest, MountPoint) {
  9222. auto port = start(enable);
  9223. Client cli(HOST, port);
  9224. cli.set_decompress(false);
  9225. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. EXPECT_EQ(StatusCode::OK_200, res->status);
  9228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9229. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9230. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9231. // The response stays self-delimiting: a length, not a chunked body.
  9232. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9233. EXPECT_EQ(std::to_string(res->body.size()),
  9234. res->get_header_value("Content-Length"));
  9235. EXPECT_LT(res->body.size(), 1048576U);
  9236. EXPECT_FALSE(res->body.empty());
  9237. }
  9238. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9239. auto port = start(enable);
  9240. Client cli(HOST, port);
  9241. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9243. EXPECT_EQ(StatusCode::OK_200, res->status);
  9244. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9245. EXPECT_EQ(1048576U, res->body.size());
  9246. }
  9247. TEST_F(StaticFileCompressionTest, FileContent) {
  9248. auto port = start(enable_without_floor);
  9249. Client cli(HOST, port);
  9250. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9252. EXPECT_EQ(StatusCode::OK_200, res->status);
  9253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9254. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9255. EXPECT_EQ(104U, res->body.size());
  9256. }
  9257. // A handler that serves an already-encoded file names the coding itself. The
  9258. // file-backed path decided its coding from Accept-Encoding and the content
  9259. // type alone, so it compressed the stored bytes a second time and appended a
  9260. // second Content-Encoding field line.
  9261. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9262. auto port = start(enable_without_floor);
  9263. Client cli(HOST, port);
  9264. cli.set_decompress(false);
  9265. auto res = cli.Get("/pre-encoded-file-content",
  9266. Headers{{"Accept-Encoding", "gzip"}});
  9267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9268. EXPECT_EQ(StatusCode::OK_200, res->status);
  9269. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9270. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9271. // Vary belongs to a coding the server chose, and it chose none here.
  9272. EXPECT_FALSE(res->has_header("Vary"));
  9273. // The file travels exactly as it is stored on disk.
  9274. EXPECT_EQ(104U, res->body.size());
  9275. }
  9276. // The 1MB file clears the default floor, so this one runs the configuration a
  9277. // deployment would actually have.
  9278. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9279. auto port = start(enable);
  9280. Client cli(HOST, port);
  9281. cli.set_decompress(false);
  9282. auto res =
  9283. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9285. EXPECT_EQ(StatusCode::OK_200, res->status);
  9286. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9288. EXPECT_FALSE(res->has_header("Vary"));
  9289. EXPECT_EQ(1048576U, res->body.size());
  9290. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9291. }
  9292. TEST_F(StaticFileCompressionTest, Head) {
  9293. auto port = start(enable);
  9294. Client cli(HOST, port);
  9295. cli.set_decompress(false);
  9296. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9297. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9298. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9300. EXPECT_EQ(StatusCode::OK_200, res->status);
  9301. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9302. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9303. // HEAD still reports the size a GET would return.
  9304. EXPECT_EQ(get->get_header_value("Content-Length"),
  9305. res->get_header_value("Content-Length"));
  9306. EXPECT_TRUE(res->body.empty());
  9307. }
  9308. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9309. auto port = start(enable);
  9310. Client cli(HOST, port);
  9311. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9312. {"Accept-Encoding", "gzip"}});
  9313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9315. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9316. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9317. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9318. EXPECT_EQ("cd", res->body);
  9319. }
  9320. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9321. auto port = start(enable);
  9322. Client cli(HOST, port);
  9323. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9325. EXPECT_EQ(StatusCode::OK_200, res->status);
  9326. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9327. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9328. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9329. }
  9330. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9331. auto port = start(enable);
  9332. Client cli(HOST, port);
  9333. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9335. EXPECT_EQ(StatusCode::OK_200, res->status);
  9336. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9337. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9338. EXPECT_TRUE(res->body.empty());
  9339. }
  9340. TEST_F(StaticFileCompressionTest, MinLength) {
  9341. auto port = start(enable);
  9342. Client cli(HOST, port);
  9343. // 104 bytes, well under the default floor. Compressing it would add the
  9344. // gzip header and trailer to a body that already fits in one packet.
  9345. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9347. EXPECT_EQ(StatusCode::OK_200, res->status);
  9348. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9349. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9350. }
  9351. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9352. auto port = start([](Server &svr) {
  9353. svr.set_static_file_compression(true);
  9354. svr.set_static_file_compression_min_length(1);
  9355. });
  9356. Client cli(HOST, port);
  9357. cli.set_decompress(false);
  9358. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9360. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9361. // A 9-byte file comes back larger than it went in, because gzip's header and
  9362. // trailer outweigh anything deflate can save. That is the end of the range
  9363. // the floor exists to keep out.
  9364. EXPECT_GT(res->body.size(), 9U);
  9365. }
  9366. TEST_F(StaticFileCompressionTest, MaxLength) {
  9367. auto port = start([](Server &svr) {
  9368. svr.set_static_file_compression(true);
  9369. svr.set_static_file_compression_min_length(0);
  9370. svr.set_static_file_compression_max_length(1024);
  9371. });
  9372. Client cli(HOST, port);
  9373. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9374. // defines `small` as a macro on Windows.
  9375. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9376. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9377. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9378. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9379. // Under it: compressed.
  9380. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9381. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9382. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9383. }
  9384. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9385. auto port = start(enable_without_floor);
  9386. Client cli(HOST, port);
  9387. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9388. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9389. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9390. auto identity_etag = identity->get_header_value("ETag");
  9391. ASSERT_FALSE(identity_etag.empty());
  9392. auto gzipped =
  9393. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9394. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9395. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9396. auto gzip_etag = gzipped->get_header_value("ETag");
  9397. ASSERT_FALSE(gzip_etag.empty());
  9398. // Two representations, two validators.
  9399. EXPECT_NE(identity_etag, gzip_etag);
  9400. // Each one revalidates against the request that would produce it...
  9401. auto fresh =
  9402. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9403. {"If-None-Match", gzip_etag}});
  9404. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9405. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9406. auto fresh_identity =
  9407. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9408. {"If-None-Match", identity_etag}});
  9409. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9410. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9411. // ...and not against the other representation.
  9412. auto crossed =
  9413. cli.Get("/dir/index.html",
  9414. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9415. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9416. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9417. }
  9418. // The opt-in covers responses the server reads off disk itself. A caller's own
  9419. // known-length provider keeps its Content-Length and, more importantly, keeps
  9420. // delivering incrementally: routing it through a compressor would hold every
  9421. // write back until zlib's window filled.
  9422. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9423. auto port = start(enable);
  9424. Client cli(HOST, port);
  9425. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9429. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9430. EXPECT_EQ("aaabbb", res->body);
  9431. }
  9432. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9433. auto port = start(enable);
  9434. Client cli(HOST, port);
  9435. cli.set_read_timeout(1, 0);
  9436. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9437. Headers{{"Accept-Encoding", "gzip"}});
  9438. ASSERT_TRUE(handle.is_valid());
  9439. // The provider writes 100 bytes and then stalls for longer than the read
  9440. // timeout. Those first bytes have to arrive anyway: run the response through
  9441. // a compressor and zlib holds them until its window fills, so the read would
  9442. // come back empty instead.
  9443. char buf[256];
  9444. auto n = handle.read(buf, sizeof(buf));
  9445. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9446. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9447. }
  9448. #endif
  9449. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9450. TEST_F(ServerTest, Brotli) {
  9451. Headers headers;
  9452. headers.emplace("Accept-Encoding", "br");
  9453. auto res = cli_.Get("/compress", headers);
  9454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9455. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9457. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9458. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9459. "7890123456789012345678901234567890",
  9460. res->body);
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. }
  9463. #endif
  9464. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9465. TEST_F(ServerTest, Zstd) {
  9466. Headers headers;
  9467. headers.emplace("Accept-Encoding", "zstd");
  9468. auto res = cli_.Get("/compress", headers);
  9469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9470. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9472. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9473. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9474. "7890123456789012345678901234567890",
  9475. res->body);
  9476. EXPECT_EQ(StatusCode::OK_200, res->status);
  9477. }
  9478. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9479. Headers headers;
  9480. headers.emplace("Accept-Encoding", "");
  9481. auto res = cli_.Get("/compress", headers);
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9484. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9485. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9486. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9487. "7890123456789012345678901234567890",
  9488. res->body);
  9489. EXPECT_EQ(StatusCode::OK_200, res->status);
  9490. }
  9491. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9492. Headers headers;
  9493. headers.emplace("Accept-Encoding", "zstd");
  9494. std::string body;
  9495. auto res =
  9496. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9497. EXPECT_EQ(100U, data_length);
  9498. body.append(data, data_length);
  9499. return true;
  9500. });
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9503. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9504. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9505. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9506. "7890123456789012345678901234567890",
  9507. body);
  9508. EXPECT_EQ(StatusCode::OK_200, res->status);
  9509. }
  9510. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9511. Headers headers;
  9512. headers.emplace("Accept-Encoding", "zstd");
  9513. cli_.set_decompress(false);
  9514. auto res = cli_.Get("/compress", headers);
  9515. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9516. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9517. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9518. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9520. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9522. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9523. EXPECT_EQ(StatusCode::OK_200, res->status);
  9524. ASSERT_EQ(26U, res->body.size());
  9525. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9526. 0);
  9527. }
  9528. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9529. Headers headers;
  9530. headers.emplace("Accept-Encoding", "");
  9531. std::string body;
  9532. auto res =
  9533. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9534. EXPECT_EQ(100U, data_length);
  9535. body.append(data, data_length);
  9536. return true;
  9537. });
  9538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9539. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9541. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9542. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9543. "7890123456789012345678901234567890",
  9544. body);
  9545. EXPECT_EQ(StatusCode::OK_200, res->status);
  9546. }
  9547. TEST_F(ServerTest, NoZstd) {
  9548. Headers headers;
  9549. headers.emplace("Accept-Encoding", "zstd");
  9550. auto res = cli_.Get("/nocompress", headers);
  9551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9552. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9553. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9554. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9556. "7890123456789012345678901234567890",
  9557. res->body);
  9558. EXPECT_EQ(StatusCode::OK_200, res->status);
  9559. }
  9560. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9561. Headers headers;
  9562. headers.emplace("Accept-Encoding", "zstd");
  9563. std::string body;
  9564. auto res = cli_.Get("/nocompress", headers,
  9565. [&](const char *data, size_t data_length) {
  9566. EXPECT_EQ(100U, data_length);
  9567. body.append(data, data_length);
  9568. return true;
  9569. });
  9570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9571. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9572. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9573. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9574. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9575. "7890123456789012345678901234567890",
  9576. body);
  9577. EXPECT_EQ(StatusCode::OK_200, res->status);
  9578. }
  9579. // TODO: How to enable zstd ??
  9580. TEST_F(ServerTest, MultipartFormDataZstd) {
  9581. UploadFormDataItems items = {
  9582. {"key1", "test", "", ""},
  9583. {"key2", "--abcdefg123", "", ""},
  9584. };
  9585. Headers headers;
  9586. headers.emplace("Accept-Encoding", "zstd");
  9587. cli_.set_compress(true);
  9588. auto res = cli_.Post("/compress-multipart", headers, items);
  9589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9590. EXPECT_EQ(StatusCode::OK_200, res->status);
  9591. }
  9592. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9593. Headers headers;
  9594. headers.emplace("Accept-Encoding", "zstd");
  9595. cli_.set_compress(true);
  9596. auto res = cli_.Put(
  9597. "/put", headers, 3,
  9598. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9599. sink.os << "PUT";
  9600. return true;
  9601. },
  9602. "text/plain");
  9603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9604. EXPECT_EQ(StatusCode::OK_200, res->status);
  9605. EXPECT_EQ("PUT", res->body);
  9606. }
  9607. // Pre-compression logging tests
  9608. TEST_F(ServerTest, PreCompressionLogging) {
  9609. // Test data for compression (matches the actual /compress endpoint content)
  9610. const std::string test_content =
  9611. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9612. "3456789012345678901234567890";
  9613. // Variables to capture logging data
  9614. std::string pre_compression_body;
  9615. std::string pre_compression_content_type;
  9616. std::string pre_compression_content_encoding;
  9617. std::string post_compression_body;
  9618. std::string post_compression_content_type;
  9619. std::string post_compression_content_encoding;
  9620. // Set up pre-compression logger
  9621. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9622. const Response &res) {
  9623. pre_compression_body = res.body;
  9624. pre_compression_content_type = res.get_header_value("Content-Type");
  9625. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9626. });
  9627. // Set up post-compression logger
  9628. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9629. post_compression_body = res.body;
  9630. post_compression_content_type = res.get_header_value("Content-Type");
  9631. post_compression_content_encoding =
  9632. res.get_header_value("Content-Encoding");
  9633. });
  9634. // Test with gzip compression
  9635. Headers headers;
  9636. headers.emplace("Accept-Encoding", "gzip");
  9637. auto res = cli_.Get("/compress", headers);
  9638. // Verify response was compressed
  9639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9640. EXPECT_EQ(StatusCode::OK_200, res->status);
  9641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9642. // Verify pre-compression logger captured uncompressed content
  9643. EXPECT_EQ(test_content, pre_compression_body);
  9644. EXPECT_EQ("text/plain", pre_compression_content_type);
  9645. EXPECT_TRUE(pre_compression_content_encoding
  9646. .empty()); // No encoding header before compression
  9647. // Verify post-compression logger captured compressed content
  9648. EXPECT_NE(test_content,
  9649. post_compression_body); // Should be different after compression
  9650. EXPECT_EQ("text/plain", post_compression_content_type);
  9651. EXPECT_EQ("gzip", post_compression_content_encoding);
  9652. // Verify compressed content is smaller
  9653. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9654. }
  9655. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9656. const std::string test_content =
  9657. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9658. "3456789012345678901234567890";
  9659. std::string pre_compression_body;
  9660. std::string post_compression_body;
  9661. svr_.set_pre_compression_logger(
  9662. [&](const Request & /*req*/, const Response &res) {
  9663. pre_compression_body = res.body;
  9664. });
  9665. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9666. post_compression_body = res.body;
  9667. });
  9668. Headers headers;
  9669. headers.emplace("Accept-Encoding", "br");
  9670. auto res = cli_.Get("/compress", headers);
  9671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9672. EXPECT_EQ(StatusCode::OK_200, res->status);
  9673. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9674. // Verify pre-compression content is uncompressed
  9675. EXPECT_EQ(test_content, pre_compression_body);
  9676. // Verify post-compression content is compressed
  9677. EXPECT_NE(test_content, post_compression_body);
  9678. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9679. }
  9680. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9681. const std::string test_content =
  9682. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9683. "3456789012345678901234567890";
  9684. std::string pre_compression_body;
  9685. std::string post_compression_body;
  9686. svr_.set_pre_compression_logger(
  9687. [&](const Request & /*req*/, const Response &res) {
  9688. pre_compression_body = res.body;
  9689. });
  9690. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9691. post_compression_body = res.body;
  9692. });
  9693. // Request without compression (use /nocompress endpoint)
  9694. Headers headers;
  9695. auto res = cli_.Get("/nocompress", headers);
  9696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9697. EXPECT_EQ(StatusCode::OK_200, res->status);
  9698. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9699. // Pre-compression logger should not be called when no compression is applied
  9700. EXPECT_TRUE(
  9701. pre_compression_body.empty()); // Pre-compression logger not called
  9702. EXPECT_EQ(
  9703. test_content,
  9704. post_compression_body); // Post-compression logger captures final content
  9705. }
  9706. TEST_F(ServerTest, LoggerSeesContentLength) {
  9707. size_t logged_content_length = 0;
  9708. std::string logged_content_length_header;
  9709. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9710. logged_content_length = res.content_length_;
  9711. logged_content_length_header = res.get_header_value("Content-Length");
  9712. });
  9713. auto res = cli_.Get("/nocompress");
  9714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9715. EXPECT_EQ(StatusCode::OK_200, res->status);
  9716. EXPECT_EQ(res->body.size(), logged_content_length);
  9717. EXPECT_EQ(std::to_string(logged_content_length),
  9718. logged_content_length_header);
  9719. }
  9720. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9721. const std::string test_content =
  9722. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9723. "3456789012345678901234567890";
  9724. std::string pre_compression_body;
  9725. bool pre_logger_called = false;
  9726. // Set only pre-compression logger
  9727. svr_.set_pre_compression_logger(
  9728. [&](const Request & /*req*/, const Response &res) {
  9729. pre_compression_body = res.body;
  9730. pre_logger_called = true;
  9731. });
  9732. Headers headers;
  9733. headers.emplace("Accept-Encoding", "gzip");
  9734. auto res = cli_.Get("/compress", headers);
  9735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9736. EXPECT_EQ(StatusCode::OK_200, res->status);
  9737. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9738. // Verify pre-compression logger was called
  9739. EXPECT_TRUE(pre_logger_called);
  9740. EXPECT_EQ(test_content, pre_compression_body);
  9741. }
  9742. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9743. {
  9744. // Test with Expect: 100-continue header - success case
  9745. // Server returns 100 Continue, client sends body, server returns 200 OK
  9746. Request req;
  9747. req.method = "POST";
  9748. req.path = "/post-large";
  9749. req.set_header("Expect", "100-continue");
  9750. req.body = LARGE_DATA;
  9751. Response res;
  9752. auto error = Error::Success;
  9753. cli_.set_keep_alive(true);
  9754. auto ret = cli_.send(req, res, error);
  9755. EXPECT_TRUE(ret);
  9756. EXPECT_EQ(StatusCode::OK_200, res.status);
  9757. EXPECT_EQ(LARGE_DATA, res.body);
  9758. }
  9759. {
  9760. // Test with Expect: 100-continue header - error case
  9761. // Client should not send the body when server returns an error
  9762. Request req;
  9763. req.method = "POST";
  9764. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9765. req.set_header("Expect", "100-continue");
  9766. req.body = LARGE_DATA;
  9767. Response res;
  9768. auto error = Error::Success;
  9769. auto start = std::chrono::high_resolution_clock::now();
  9770. cli_.set_keep_alive(true);
  9771. auto ret = cli_.send(req, res, error);
  9772. auto end = std::chrono::high_resolution_clock::now();
  9773. auto elapsed =
  9774. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9775. .count();
  9776. // With Expect: 100-continue, request completes successfully but with error
  9777. EXPECT_TRUE(ret);
  9778. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9779. EXPECT_EQ("close", res.get_header_value("Connection"));
  9780. EXPECT_FALSE(cli_.is_socket_open());
  9781. EXPECT_LE(elapsed, 2000);
  9782. }
  9783. {
  9784. // Send an extra GET request to ensure error recovery without hanging
  9785. Request req;
  9786. req.method = "GET";
  9787. req.path = "/hi";
  9788. auto start = std::chrono::high_resolution_clock::now();
  9789. auto res = cli_.send(req);
  9790. auto end = std::chrono::high_resolution_clock::now();
  9791. auto elapsed =
  9792. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9793. .count();
  9794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9795. EXPECT_EQ(StatusCode::OK_200, res->status);
  9796. EXPECT_EQ("Hello World!", res->body);
  9797. EXPECT_LE(elapsed, 500);
  9798. }
  9799. }
  9800. TEST(ZstdDecompressor, ChunkedDecompression) {
  9801. std::string data;
  9802. for (size_t i = 0; i < 32 * 1024; ++i) {
  9803. data.push_back(static_cast<char>('a' + i % 26));
  9804. }
  9805. std::string compressed_data;
  9806. {
  9807. httplib::detail::zstd_compressor compressor;
  9808. bool result = compressor.compress(
  9809. data.data(), data.size(),
  9810. /*last=*/true,
  9811. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9812. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9813. compressed_data_size);
  9814. return true;
  9815. });
  9816. ASSERT_TRUE(result);
  9817. }
  9818. std::string decompressed_data;
  9819. {
  9820. httplib::detail::zstd_decompressor decompressor;
  9821. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9822. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9823. size_t chunk_size = 130;
  9824. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9825. chunk_begin += chunk_size) {
  9826. size_t current_chunk_size =
  9827. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9828. bool result = decompressor.decompress(
  9829. compressed_data.data() + chunk_begin, current_chunk_size,
  9830. [&](const char *decompressed_data_chunk,
  9831. size_t decompressed_data_chunk_size) {
  9832. decompressed_data.insert(decompressed_data.size(),
  9833. decompressed_data_chunk,
  9834. decompressed_data_chunk_size);
  9835. return true;
  9836. });
  9837. ASSERT_TRUE(result);
  9838. }
  9839. }
  9840. ASSERT_EQ(data, decompressed_data);
  9841. }
  9842. TEST(ZstdDecompressor, Decompress) {
  9843. std::string original_text = "Compressed with ZSTD";
  9844. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9845. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9846. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9847. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9848. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9849. std::string decompressed_data;
  9850. {
  9851. httplib::detail::zstd_decompressor decompressor;
  9852. bool result = decompressor.decompress(
  9853. compressed_data.data(), compressed_data.size(),
  9854. [&](const char *decompressed_data_chunk,
  9855. size_t decompressed_data_chunk_size) {
  9856. decompressed_data.insert(decompressed_data.size(),
  9857. decompressed_data_chunk,
  9858. decompressed_data_chunk_size);
  9859. return true;
  9860. });
  9861. ASSERT_TRUE(result);
  9862. }
  9863. ASSERT_EQ(original_text, decompressed_data);
  9864. }
  9865. #endif
  9866. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9867. // separate chunks so that the server sees each part in its own read(). Used to
  9868. // place a read boundary at a specific offset of a request body.
  9869. static bool send_request_in_parts(time_t read_timeout_sec,
  9870. const std::vector<std::string> &parts,
  9871. std::string *resp = nullptr,
  9872. int port = PORT) {
  9873. auto error = Error::Success;
  9874. auto client_sock = detail::create_client_socket(
  9875. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9876. /*connection_timeout_sec=*/5, 0,
  9877. /*read_timeout_sec=*/5, 0,
  9878. /*write_timeout_sec=*/5, 0, std::string(), error);
  9879. if (client_sock == INVALID_SOCKET) { return false; }
  9880. auto ret = detail::process_client_socket(
  9881. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9882. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9883. for (size_t i = 0; i < parts.size(); i++) {
  9884. const auto &part = parts[i];
  9885. if (part.size() !=
  9886. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9887. return false;
  9888. }
  9889. if (i + 1 < parts.size()) {
  9890. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9891. }
  9892. }
  9893. char buf[512];
  9894. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9895. while (line_reader.getline()) {
  9896. if (resp) { *resp += line_reader.ptr(); }
  9897. }
  9898. return true;
  9899. });
  9900. detail::close_socket(client_sock);
  9901. return ret;
  9902. }
  9903. // Sends a raw request to a server listening at HOST:PORT.
  9904. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9905. std::string *resp = nullptr, int port = PORT) {
  9906. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9907. }
  9908. #ifdef CPPHTTPLIB_SSL_ENABLED
  9909. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9911. ASSERT_TRUE(svr.is_valid());
  9912. svr.set_read_timeout(1, 0);
  9913. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9914. auto se = detail::scope_exit([&] {
  9915. svr.stop();
  9916. t.join();
  9917. ASSERT_FALSE(svr.is_running());
  9918. });
  9919. svr.wait_until_ready();
  9920. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9921. // keeps each wait well within the read timeout. The server gives up a
  9922. // second in, so the bytes sent after that fail.
  9923. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9924. parts.resize(26, std::string(1, '\0'));
  9925. EXPECT_FALSE(send_request_in_parts(5, parts));
  9926. }
  9927. #endif
  9928. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9929. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9930. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9931. const std::vector<std::string> &parts,
  9932. std::string *resp = nullptr,
  9933. int port = PORT) {
  9934. auto error = Error::Success;
  9935. auto sock = detail::create_client_socket(
  9936. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9937. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9938. /*write_timeout_sec=*/5, 0, std::string(), error);
  9939. if (sock == INVALID_SOCKET) { return false; }
  9940. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9941. auto ctx = SSL_CTX_new(TLS_client_method());
  9942. auto ssl = SSL_new(ctx);
  9943. auto ssl_se = detail::scope_exit([&] {
  9944. SSL_free(ssl);
  9945. SSL_CTX_free(ctx);
  9946. });
  9947. SSL_set_fd(ssl, static_cast<int>(sock));
  9948. if (SSL_connect(ssl) != 1) { return false; }
  9949. for (size_t i = 0; i < parts.size(); i++) {
  9950. const auto &part = parts[i];
  9951. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9952. static_cast<int>(part.size())) {
  9953. return false;
  9954. }
  9955. if (i + 1 < parts.size()) {
  9956. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9957. }
  9958. }
  9959. char buf[512];
  9960. int n;
  9961. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9962. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9963. }
  9964. return true;
  9965. }
  9966. #endif
  9967. // The request line, then a header value a byte at a time.
  9968. static std::vector<std::string> slow_request_head_parts() {
  9969. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9970. parts.resize(26, "a");
  9971. parts.emplace_back("\r\n\r\n");
  9972. return parts;
  9973. }
  9974. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9975. // within the one-second read timeout. The server gives up a second in, before
  9976. // the head is complete.
  9977. static void
  9978. expect_slow_request_head_dropped(Server &svr,
  9979. const std::function<std::string()> &send) {
  9980. std::atomic<bool> handled(false);
  9981. svr.Get("/", [&](const Request &, Response &res) {
  9982. handled = true;
  9983. res.set_content("ok", "text/plain");
  9984. });
  9985. svr.set_read_timeout(1, 0);
  9986. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9987. auto se = detail::scope_exit([&] {
  9988. svr.stop();
  9989. t.join();
  9990. ASSERT_FALSE(svr.is_running());
  9991. });
  9992. svr.wait_until_ready();
  9993. auto resp = send();
  9994. EXPECT_FALSE(handled);
  9995. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9996. }
  9997. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9998. Server svr;
  9999. expect_slow_request_head_dropped(svr, [] {
  10000. std::string resp;
  10001. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10002. return resp;
  10003. });
  10004. }
  10005. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10006. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10008. ASSERT_TRUE(svr.is_valid());
  10009. expect_slow_request_head_dropped(svr, [] {
  10010. std::string resp;
  10011. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10012. return resp;
  10013. });
  10014. }
  10015. #endif
  10016. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10017. Server svr;
  10018. std::string header_value;
  10019. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10020. header_value = req.get_header_value("foo");
  10021. res.set_content("ok", "text/plain");
  10022. });
  10023. thread t = thread([&] { svr.listen(HOST, PORT); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. t.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.wait_until_ready();
  10030. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10031. // like characters are not treated the same - use vertical tab and escape.
  10032. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10033. "foo: \t \v bar \x1B\t \r\n"
  10034. "Connection: close\r\n"
  10035. "\r\n";
  10036. std::string res;
  10037. ASSERT_TRUE(send_request(5, req, &res));
  10038. EXPECT_EQ(header_value, "");
  10039. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10040. }
  10041. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10042. Server svr;
  10043. std::string received;
  10044. svr.Get("/order", [&](const Request &req, Response &res) {
  10045. received = entries_to_string(req.headers);
  10046. res.set_content("ok", "text/plain");
  10047. });
  10048. auto port = svr.bind_to_any_port(HOST);
  10049. thread t = thread([&] { svr.listen_after_bind(); });
  10050. auto se = detail::scope_exit([&] {
  10051. svr.stop();
  10052. t.join();
  10053. ASSERT_FALSE(svr.is_running());
  10054. });
  10055. svr.wait_until_ready();
  10056. const std::string req = "GET /order HTTP/1.1\r\n"
  10057. "Host: localhost\r\n"
  10058. "X-First: 1\r\n"
  10059. "X-Dup: a\r\n"
  10060. "X-Second: 2\r\n"
  10061. "X-Dup: b\r\n"
  10062. "Connection: close\r\n"
  10063. "\r\n";
  10064. std::string res;
  10065. ASSERT_TRUE(send_request(5, req, &res, port));
  10066. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10067. EXPECT_EQ(
  10068. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10069. received);
  10070. }
  10071. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10072. Server svr;
  10073. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10074. res.set_header("Set-Cookie", "first=1");
  10075. res.set_header("X-Between", "y");
  10076. res.set_header("Set-Cookie", "second=2");
  10077. res.set_content("ok", "text/plain");
  10078. });
  10079. auto port = svr.bind_to_any_port(HOST);
  10080. thread t = thread([&] { svr.listen_after_bind(); });
  10081. auto se = detail::scope_exit([&] {
  10082. svr.stop();
  10083. t.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. svr.wait_until_ready();
  10087. Client cli(HOST, port);
  10088. auto res = cli.Get("/cookies");
  10089. ASSERT_TRUE(res);
  10090. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10091. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10092. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10093. }
  10094. // A stream may send a byte at a time with a small extension on each chunk,
  10095. // however long it runs
  10096. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10097. Server svr;
  10098. svr.Post("/count", [](const Request &req, Response &res) {
  10099. res.set_content(std::to_string(req.body.size()), "text/plain");
  10100. });
  10101. auto port = svr.bind_to_any_port(HOST);
  10102. ASSERT_LT(0, port);
  10103. thread t = thread([&] { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. t.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10111. "\r\nTransfer-Encoding: chunked\r\n"
  10112. "Connection: close\r\n\r\n";
  10113. for (auto i = 0; i < 4096; i++) {
  10114. req += "1;a=b\r\nx\r\n";
  10115. }
  10116. req += "0\r\n\r\n";
  10117. std::string res;
  10118. ASSERT_TRUE(send_request(5, req, &res, port));
  10119. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10120. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10121. }
  10122. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10123. Server svr;
  10124. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10125. auto i = new int(0);
  10126. res.set_header("Trailer", "X-Safe, X-Reflected");
  10127. res.set_chunked_content_provider(
  10128. "text/plain",
  10129. [i](size_t /*offset*/, DataSink &sink) {
  10130. if (*i == 0) {
  10131. sink.os << "body";
  10132. } else {
  10133. Headers trailer;
  10134. // A valid trailer that must survive.
  10135. trailer.emplace("X-Safe", "safe");
  10136. // Attacker-controlled value carrying CR/LF (response splitting).
  10137. trailer.emplace("X-Reflected",
  10138. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10139. // Attacker-controlled name carrying CR/LF.
  10140. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10141. sink.done_with_trailer(trailer);
  10142. }
  10143. (*i)++;
  10144. return true;
  10145. },
  10146. [i](bool /*success*/) { delete i; });
  10147. });
  10148. thread t = thread([&] { svr.listen(HOST, PORT); });
  10149. auto se = detail::scope_exit([&] {
  10150. svr.stop();
  10151. t.join();
  10152. ASSERT_FALSE(svr.is_running());
  10153. });
  10154. svr.wait_until_ready();
  10155. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10156. "Host: " + HOST +
  10157. "\r\n"
  10158. "Connection: close\r\n"
  10159. "\r\n";
  10160. std::string res;
  10161. ASSERT_TRUE(send_request(5, req, &res));
  10162. // The injected fields must not appear anywhere in the raw response.
  10163. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10164. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10165. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10166. // Invalid trailers are dropped entirely, matching set_header().
  10167. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10168. // The valid trailer still passes through.
  10169. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10170. }
  10171. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10172. // A custom header writer gets only the fields the default one writes
  10173. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10174. std::string s;
  10175. for (const auto &h : hdrs) {
  10176. s += h.first + ": " + h.second + "\r\n";
  10177. }
  10178. s += "\r\n";
  10179. return strm.write(s.data(), s.size());
  10180. };
  10181. for (auto custom_writer : {false, true}) {
  10182. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10183. Server svr;
  10184. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10185. svr.set_post_routing_handler([](const Request &, Response &res) {
  10186. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10187. });
  10188. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10189. // res.headers is a public field an application can populate directly,
  10190. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10191. // A valid header that must survive.
  10192. res.headers.emplace("X-Safe", "safe");
  10193. // Attacker-controlled value carrying CR/LF (response splitting).
  10194. res.headers.emplace("X-Reflected",
  10195. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10196. // Attacker-controlled name carrying CR/LF.
  10197. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10198. res.set_content("body", "text/plain");
  10199. });
  10200. thread t = thread([&] { svr.listen(HOST, PORT); });
  10201. auto se = detail::scope_exit([&] {
  10202. svr.stop();
  10203. t.join();
  10204. ASSERT_FALSE(svr.is_running());
  10205. });
  10206. svr.wait_until_ready();
  10207. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10208. "Host: " + HOST +
  10209. "\r\n"
  10210. "Connection: close\r\n"
  10211. "\r\n";
  10212. std::string res;
  10213. ASSERT_TRUE(send_request(5, req, &res));
  10214. // The injected fields must not appear anywhere in the raw response.
  10215. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10216. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10217. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10218. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10219. // Invalid headers are dropped entirely, matching set_header().
  10220. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10221. // The valid header still passes through.
  10222. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10223. }
  10224. }
  10225. // Forward declaration: in split builds split.py strips `inline` and moves the
  10226. // definition into httplib.cc, so detail::write_request_line is not visible from
  10227. // the public httplib.h. Re-declaring it here lets the tests link against the
  10228. // symbol in both header-only and split builds.
  10229. namespace httplib {
  10230. namespace detail {
  10231. ssize_t write_request_line(Stream &strm, const std::string &method,
  10232. const std::string &path);
  10233. } // namespace detail
  10234. } // namespace httplib
  10235. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10236. // A well-formed target is written verbatim.
  10237. {
  10238. detail::BufferStream strm;
  10239. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10240. EXPECT_GT(n, 0);
  10241. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10242. }
  10243. // A target carrying CR/LF, SP or other control octets must be rejected
  10244. // before anything reaches the wire, otherwise it splits the request line and
  10245. // injects a header or a whole request.
  10246. const std::string evil_targets[] = {
  10247. "/a\r\nInjected: pwned",
  10248. "/a\rInjected",
  10249. "/a\nInjected",
  10250. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10251. "/a b",
  10252. "/a\tb",
  10253. "/a\x7f",
  10254. };
  10255. for (const auto &evil : evil_targets) {
  10256. detail::BufferStream strm;
  10257. auto n = detail::write_request_line(strm, "GET", evil);
  10258. EXPECT_LT(n, 0);
  10259. EXPECT_TRUE(strm.get_buffer().empty());
  10260. }
  10261. }
  10262. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10263. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10264. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10265. // target reaches write_request. The client must fail cleanly with
  10266. // Error::Write instead of putting a request-line-less, header-injecting
  10267. // request on the wire.
  10268. Server svr;
  10269. svr.Get("/a", [](const Request &, Response &res) {
  10270. res.set_content("ok", "text/plain");
  10271. });
  10272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10273. auto se = detail::scope_exit([&] {
  10274. svr.stop();
  10275. thread.join();
  10276. ASSERT_FALSE(svr.is_running());
  10277. });
  10278. svr.wait_until_ready();
  10279. {
  10280. Client cli(HOST, PORT);
  10281. cli.set_path_encode(false);
  10282. // The request is rejected before anything is written, so the connection
  10283. // stays silent and the subsequent response read would otherwise block for
  10284. // the full default read timeout. Shorten it -- the assertion is on the
  10285. // error, not the timeout.
  10286. cli.set_read_timeout(1, 0);
  10287. auto res = cli.Get("/a\r\nInjected: pwned");
  10288. EXPECT_FALSE(res);
  10289. EXPECT_EQ(Error::Write, res.error());
  10290. }
  10291. }
  10292. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10293. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10294. // including extension methods.
  10295. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10296. for (const auto &method : good_methods) {
  10297. detail::BufferStream strm;
  10298. auto n = detail::write_request_line(strm, method, "/");
  10299. EXPECT_GT(n, 0);
  10300. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10301. }
  10302. // A method carrying CR/LF would split the request line and smuggle a whole
  10303. // request ahead of the real one. A space or an empty method corrupts the
  10304. // request line. All must be rejected before anything reaches the wire.
  10305. const std::string evil_methods[] = {
  10306. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10307. "GET\r\nInjected: pwned",
  10308. "GET\r",
  10309. "GET\n",
  10310. "GE T",
  10311. "",
  10312. };
  10313. for (const auto &evil : evil_methods) {
  10314. detail::BufferStream strm;
  10315. auto n = detail::write_request_line(strm, evil, "/");
  10316. EXPECT_LT(n, 0);
  10317. EXPECT_TRUE(strm.get_buffer().empty());
  10318. }
  10319. }
  10320. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10321. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10322. // through Client::send must fail with Error::Write and no request, neither
  10323. // the smuggled one nor the real one, may reach the server.
  10324. Server svr;
  10325. std::atomic<int> request_count(0);
  10326. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10327. request_count++;
  10328. res.status = StatusCode::OK_200;
  10329. return Server::HandlerResponse::Handled;
  10330. });
  10331. auto port = svr.bind_to_any_port(HOST);
  10332. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10333. auto se = detail::scope_exit([&] {
  10334. svr.stop();
  10335. thread.join();
  10336. ASSERT_FALSE(svr.is_running());
  10337. });
  10338. svr.wait_until_ready();
  10339. {
  10340. Client cli(HOST, port);
  10341. const std::string evil_methods[] = {
  10342. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10343. "GE T",
  10344. "",
  10345. };
  10346. for (const auto &evil : evil_methods) {
  10347. Request req;
  10348. req.method = evil;
  10349. req.path = "/";
  10350. auto res = cli.send(req);
  10351. EXPECT_FALSE(res);
  10352. EXPECT_EQ(Error::Write, res.error());
  10353. }
  10354. auto handle =
  10355. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10356. EXPECT_FALSE(handle.is_valid());
  10357. EXPECT_EQ(Error::Write, handle.error);
  10358. // A valid request on the same client still goes through.
  10359. auto res = cli.Get("/");
  10360. ASSERT_TRUE(res);
  10361. EXPECT_EQ(StatusCode::OK_200, res->status);
  10362. }
  10363. EXPECT_EQ(1, request_count.load());
  10364. }
  10365. // Sends a raw request and verifies that there isn't a crash or exception.
  10366. static void test_raw_request(const std::string &req,
  10367. std::string *out = nullptr) {
  10368. Server svr;
  10369. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10370. res.set_content("ok", "text/plain");
  10371. });
  10372. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10373. res.set_content("ok", "text/plain");
  10374. });
  10375. svr.Get("/header_field_value_check",
  10376. [&](const Request & /*req*/, Response &res) {
  10377. res.set_content("ok", "text/plain");
  10378. });
  10379. svr.CustomRoute("PROPFIND", "/dav",
  10380. [&](const Request & /*req*/, Response &res) {
  10381. res.status = StatusCode::MultiStatus_207;
  10382. });
  10383. // Server read timeout must be longer than the client read timeout for the
  10384. // bug to reproduce, probably to force the server to process a request
  10385. // without a trailing blank line.
  10386. const time_t client_read_timeout_sec = 1;
  10387. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10388. bool listen_thread_ok = false;
  10389. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. t.join();
  10393. ASSERT_FALSE(svr.is_running());
  10394. EXPECT_TRUE(listen_thread_ok);
  10395. });
  10396. svr.wait_until_ready();
  10397. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10398. }
  10399. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10400. // A certain header line causes an exception if the header property is parsed
  10401. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10402. test_raw_request(
  10403. "GET /hi HTTP/1.1\r\n"
  10404. " : "
  10405. " "
  10406. " ");
  10407. }
  10408. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10409. // A certain header line causes an exception if the header property *name* is
  10410. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10411. // greedy matcher and requires backtracking when there are a lot of ":"
  10412. // characters.
  10413. // This occurs with libc++ but not libstdc++.
  10414. test_raw_request(
  10415. "GET /hi HTTP/1.1\r\n"
  10416. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10417. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10418. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10419. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10420. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10421. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10422. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10423. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10424. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10425. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10426. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10427. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10428. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10429. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10430. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10431. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10432. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10433. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10434. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10435. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10436. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10437. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10438. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10439. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10440. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10441. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10442. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10443. "&&&%%%");
  10444. }
  10445. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10446. // Make sure this doesn't crash the server.
  10447. // In a previous version of the header line regex, the "\r" rendered the line
  10448. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10449. // a new position where the leading white space ended and the field value
  10450. // began.
  10451. // The crash occurs with libc++ but not libstdc++.
  10452. test_raw_request("GET /hi HTTP/1.1\r\n"
  10453. "a:" +
  10454. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10455. "\r\n"
  10456. "\r\n");
  10457. }
  10458. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10459. const char *rejected[] = {
  10460. // RFC 9112 §3: one SP between the parts, and nothing else
  10461. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10462. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10463. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10464. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10465. // A request-target has no fragment
  10466. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10467. // An HTTP/1.1 request needs a Host
  10468. "GET /hi HTTP/1.1\r\n\r\n",
  10469. };
  10470. for (auto request : rejected) {
  10471. std::string out;
  10472. test_raw_request(request, &out);
  10473. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10474. }
  10475. std::string out;
  10476. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10477. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10478. }
  10479. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10480. // RFC 9112 §6.1
  10481. const char *requests[] = {
  10482. "PUT /put_hi HTTP/1.1\r\n"
  10483. "Host: localhost\r\n"
  10484. "Content-Length: 0\r\n"
  10485. "Transfer-Encoding: chunked\r\n"
  10486. "\r\n"
  10487. "0\r\n\r\n",
  10488. "PUT /put_hi HTTP/1.0\r\n"
  10489. "Connection: keep-alive\r\n"
  10490. "Transfer-Encoding: chunked\r\n"
  10491. "\r\n"
  10492. "0\r\n\r\n",
  10493. };
  10494. for (auto request : requests) {
  10495. std::string out;
  10496. test_raw_request(request, &out);
  10497. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10498. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10499. }
  10500. }
  10501. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10502. std::string out;
  10503. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10504. "Content-Type: text/plain\r\n"
  10505. "Transfer-Encoding: chunked\r\n"
  10506. "\r\n"
  10507. "nothex\r\n",
  10508. &out);
  10509. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10510. }
  10511. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10512. std::string out;
  10513. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10514. "Content-Type: text/plain\r\n"
  10515. "Transfer-Encoding: chunked\r\n"
  10516. "\r\n"
  10517. "3\r\n"
  10518. "xyz\r\n"
  10519. "NaN\r\n",
  10520. &out);
  10521. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10522. }
  10523. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10524. std::string out;
  10525. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10526. "Content-Type: text/plain\r\n"
  10527. "Transfer-Encoding: chunked\r\n"
  10528. "\r\n"
  10529. // Length is too large for 64 bits.
  10530. "1ffffffffffffffff\r\n"
  10531. "xyz\r\n",
  10532. &out);
  10533. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10534. }
  10535. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10536. test_raw_request("GET /hi HTTP/1.1\r\n"
  10537. "Content-Type: text/plain\r\n\r");
  10538. }
  10539. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10540. std::string out;
  10541. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10542. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10543. }
  10544. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10545. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10546. std::string out;
  10547. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10548. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10549. }
  10550. }
  10551. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10552. std::string out;
  10553. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10554. "Host: localhost\r\n"
  10555. "Connection: close\r\n\r\n",
  10556. &out);
  10557. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10558. }
  10559. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10560. Server svr;
  10561. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10562. EXPECT_TRUE(!req.remote_addr.empty());
  10563. });
  10564. thread t = thread([&] { svr.listen(HOST, PORT); });
  10565. auto se = detail::scope_exit([&] {
  10566. svr.stop();
  10567. t.join();
  10568. ASSERT_FALSE(svr.is_running());
  10569. });
  10570. svr.wait_until_ready();
  10571. // Send an invalid request line to trigger Bad Request
  10572. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10573. std::string out;
  10574. ASSERT_TRUE(send_request(5, bad_req, &out));
  10575. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10576. }
  10577. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10578. // answered right away rather than blocking on a read that waits for EOF.
  10579. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10580. std::string out;
  10581. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10582. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10583. }
  10584. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10585. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10586. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10587. for (const auto *method : methods) {
  10588. Server svr;
  10589. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10590. EXPECT_FALSE(svr.is_valid()) << method;
  10591. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10592. }
  10593. }
  10594. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10595. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10596. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10597. for (const auto *method : methods) {
  10598. Server svr;
  10599. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10600. EXPECT_FALSE(svr.is_valid()) << method;
  10601. }
  10602. }
  10603. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10604. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10605. "COPY", "MOVE", "LOCK",
  10606. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10607. Server svr;
  10608. for (const auto *method : methods) {
  10609. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10610. }
  10611. EXPECT_TRUE(svr.is_valid());
  10612. }
  10613. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10614. Server svr;
  10615. svr.CustomRoute("POST", "/x",
  10616. [](const Request &, Response &, const ContentReader &) {});
  10617. EXPECT_FALSE(svr.is_valid());
  10618. }
  10619. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10620. Server svr;
  10621. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10622. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10623. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10624. EXPECT_FALSE(svr.is_valid());
  10625. }
  10626. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10627. Server svr;
  10628. auto captured = Error::Success;
  10629. svr.set_error_logger(
  10630. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10631. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10632. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10633. }
  10634. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10635. std::string out;
  10636. std::string request(
  10637. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10638. test_raw_request(request, &out);
  10639. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10640. }
  10641. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10642. std::string out;
  10643. std::string request(
  10644. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10645. test_raw_request(request, &out);
  10646. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10647. }
  10648. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10649. std::string out;
  10650. std::string request(
  10651. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10652. test_raw_request(request, &out);
  10653. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10654. }
  10655. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10656. std::string out;
  10657. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10658. "Host: localhost\r\n"
  10659. "Test: \r\n\r\n",
  10660. &out);
  10661. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10662. }
  10663. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10664. Server svr;
  10665. std::string x_custom;
  10666. std::string cookie;
  10667. std::string xff;
  10668. std::string x_unicode;
  10669. std::string x_iis;
  10670. svr.Get("/check", [&](const Request &req, Response &res) {
  10671. x_custom = req.get_header_value("X-Custom");
  10672. cookie = req.get_header_value("Cookie");
  10673. xff = req.get_header_value("X-Forwarded-For");
  10674. x_unicode = req.get_header_value("X-Unicode");
  10675. x_iis = req.get_header_value("X-IIS");
  10676. res.set_content("ok", "text/plain");
  10677. });
  10678. thread t = thread([&] { svr.listen(HOST, PORT); });
  10679. auto se = detail::scope_exit([&] {
  10680. svr.stop();
  10681. t.join();
  10682. ASSERT_FALSE(svr.is_running());
  10683. });
  10684. svr.wait_until_ready();
  10685. const std::string req = "GET /check HTTP/1.1\r\n"
  10686. "Host: localhost\r\n"
  10687. "X-Custom: a%0D%0AInjected: b\r\n"
  10688. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10689. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10690. "X-Unicode: %E3%81%82\r\n"
  10691. "X-IIS: %u00E9\r\n"
  10692. "Connection: close\r\n"
  10693. "\r\n";
  10694. std::string res;
  10695. ASSERT_TRUE(send_request(5, req, &res));
  10696. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10697. // Every value must be returned verbatim (wire form), with no decoding.
  10698. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10699. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10700. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10701. EXPECT_EQ("%E3%81%82", x_unicode);
  10702. EXPECT_EQ("%u00E9", x_iis);
  10703. }
  10704. // Applications that previously relied on automatic percent-decoding can
  10705. // reproduce the old behavior by explicitly calling decode_path_component()
  10706. // or, for RFC 3986 conformance, decode_uri_component().
  10707. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10708. Server svr;
  10709. std::string decoded;
  10710. svr.Get("/check", [&](const Request &req, Response &res) {
  10711. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10712. res.set_content("ok", "text/plain");
  10713. });
  10714. thread t = thread([&] { svr.listen(HOST, PORT); });
  10715. auto se = detail::scope_exit([&] {
  10716. svr.stop();
  10717. t.join();
  10718. ASSERT_FALSE(svr.is_running());
  10719. });
  10720. svr.wait_until_ready();
  10721. const std::string req = "GET /check HTTP/1.1\r\n"
  10722. "Host: localhost\r\n"
  10723. "X-Custom: hello%20world\r\n"
  10724. "Connection: close\r\n"
  10725. "\r\n";
  10726. std::string res;
  10727. ASSERT_TRUE(send_request(5, req, &res));
  10728. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10729. EXPECT_EQ("hello world", decoded);
  10730. }
  10731. // Regression test for #2033. Browsers send Referer values that include
  10732. // percent-encoded characters such as %0A inside the URL. Decoding the
  10733. // header value would either trip the post-decode CR/LF/NUL guard (the
  10734. // original bug, returning 400) or, after that guard was relaxed, silently
  10735. // store a literal LF — both unacceptable. The wire form must round-trip.
  10736. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10737. Server svr;
  10738. std::string referer;
  10739. svr.Get("/check", [&](const Request &req, Response &res) {
  10740. referer = req.get_header_value("Referer");
  10741. res.set_content("ok", "text/plain");
  10742. });
  10743. thread t = thread([&] { svr.listen(HOST, PORT); });
  10744. auto se = detail::scope_exit([&] {
  10745. svr.stop();
  10746. t.join();
  10747. ASSERT_FALSE(svr.is_running());
  10748. });
  10749. svr.wait_until_ready();
  10750. const std::string req = "GET /check HTTP/1.1\r\n"
  10751. "Host: localhost\r\n"
  10752. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10753. "Connection: close\r\n"
  10754. "\r\n";
  10755. std::string res;
  10756. ASSERT_TRUE(send_request(5, req, &res));
  10757. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10758. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10759. }
  10760. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10761. Server svr;
  10762. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10763. res.set_header("Cache-Control", "no-cache");
  10764. res.set_chunked_content_provider(
  10765. "text/event-stream", [](size_t offset, DataSink &sink) {
  10766. std::string s = "data:";
  10767. s += std::to_string(offset);
  10768. s += "\n\n";
  10769. auto ret = sink.write(s.data(), s.size());
  10770. EXPECT_TRUE(ret);
  10771. std::this_thread::sleep_for(std::chrono::seconds(1));
  10772. return true;
  10773. });
  10774. });
  10775. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10776. svr.wait_until_ready();
  10777. Client client(HOST, PORT);
  10778. const Headers headers = {{"Accept", "text/event-stream"}};
  10779. auto get_thread = std::thread([&client, &headers]() {
  10780. auto res = client.Get(
  10781. "/events", headers,
  10782. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10783. });
  10784. auto se = detail::scope_exit([&] {
  10785. svr.stop();
  10786. get_thread.join();
  10787. listen_thread.join();
  10788. ASSERT_FALSE(svr.is_running());
  10789. });
  10790. // Give GET time to get a few messages.
  10791. std::this_thread::sleep_for(std::chrono::seconds(2));
  10792. }
  10793. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10794. httplib::Server svr;
  10795. svr.Post("/hi",
  10796. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10797. res.status = StatusCode::OK_200;
  10798. });
  10799. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10800. svr.wait_until_ready();
  10801. Client cli(HOST, PORT);
  10802. auto res = cli.Post("/hi", "data", "text/plain");
  10803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10804. EXPECT_EQ(StatusCode::OK_200, res->status);
  10805. svr.stop();
  10806. thread.join();
  10807. ASSERT_FALSE(svr.is_running());
  10808. res = cli.Post("/hi", "data", "text/plain");
  10809. ASSERT_FALSE(res);
  10810. }
  10811. TEST(ServerStopTest, ListenFailure) {
  10812. Server svr;
  10813. auto t = thread([&]() {
  10814. auto ret = svr.listen("????", PORT);
  10815. EXPECT_FALSE(ret);
  10816. });
  10817. svr.wait_until_ready();
  10818. svr.stop();
  10819. t.join();
  10820. }
  10821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10822. TEST(ServerStopTest, Decommision) {
  10823. Server svr;
  10824. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10825. for (int i = 0; i < 4; i++) {
  10826. auto is_even = !(i % 2);
  10827. std::thread t{[&] {
  10828. try {
  10829. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10830. if (is_even) {
  10831. throw std::runtime_error("Some thing that happens to go wrong.");
  10832. }
  10833. svr.listen(HOST, PORT);
  10834. } catch (...) { svr.decommission(); }
  10835. }};
  10836. svr.wait_until_ready();
  10837. // Server is up
  10838. {
  10839. Client cli(HOST, PORT);
  10840. auto res = cli.Get("/hi");
  10841. if (is_even) {
  10842. EXPECT_FALSE(res);
  10843. } else {
  10844. EXPECT_TRUE(res);
  10845. EXPECT_EQ("hi...", res->body);
  10846. }
  10847. }
  10848. svr.stop();
  10849. t.join();
  10850. // Server is down...
  10851. {
  10852. Client cli(HOST, PORT);
  10853. auto res = cli.Get("/hi");
  10854. EXPECT_FALSE(res);
  10855. }
  10856. }
  10857. }
  10858. #endif
  10859. // Helper function for string body upload progress tests
  10860. template <typename SetupHandler, typename ClientCall>
  10861. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10862. ClientCall &&client_call,
  10863. const string &body) {
  10864. Server svr;
  10865. setup_handler(svr);
  10866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10867. auto se = detail::scope_exit([&] {
  10868. svr.stop();
  10869. t.join();
  10870. });
  10871. svr.wait_until_ready();
  10872. Client cli(HOST, PORT);
  10873. vector<uint64_t> progress_values;
  10874. bool progress_called = false;
  10875. auto res =
  10876. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10877. progress_values.push_back(current);
  10878. progress_called = true;
  10879. return true;
  10880. });
  10881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10882. EXPECT_EQ(200, res->status);
  10883. EXPECT_TRUE(progress_called);
  10884. }
  10885. TEST(UploadProgressTest, PostStringBodyBasic) {
  10886. TestStringBodyUploadProgress(
  10887. [](Server &svr) {
  10888. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10889. res.set_content("received", "text/plain");
  10890. });
  10891. },
  10892. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10893. return cli.Post("/test", body, "text/plain", progress_callback);
  10894. },
  10895. "test data for upload progress");
  10896. }
  10897. TEST(UploadProgressTest, PutStringBodyBasic) {
  10898. TestStringBodyUploadProgress(
  10899. [](Server &svr) {
  10900. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10901. res.set_content("put received", "text/plain");
  10902. });
  10903. },
  10904. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10905. return cli.Put("/test", body, "text/plain", progress_callback);
  10906. },
  10907. "put test data for upload progress");
  10908. }
  10909. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10910. TestStringBodyUploadProgress(
  10911. [](Server &svr) {
  10912. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10913. res.set_content("patch received", "text/plain");
  10914. });
  10915. },
  10916. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10917. return cli.Patch("/test", body, "text/plain", progress_callback);
  10918. },
  10919. "patch test data for upload progress");
  10920. }
  10921. // Helper function for content provider upload progress tests
  10922. template <typename SetupHandler, typename ClientCall>
  10923. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10924. ClientCall &&client_call) {
  10925. Server svr;
  10926. setup_handler(svr);
  10927. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10928. auto se = detail::scope_exit([&] {
  10929. svr.stop();
  10930. t.join();
  10931. });
  10932. svr.wait_until_ready();
  10933. Client cli(HOST, PORT);
  10934. vector<uint64_t> progress_values;
  10935. auto res =
  10936. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10937. progress_values.push_back(current);
  10938. return true;
  10939. });
  10940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10941. EXPECT_EQ(200, res->status);
  10942. EXPECT_FALSE(progress_values.empty());
  10943. }
  10944. TEST(UploadProgressTest, PostContentProviderProgress) {
  10945. TestContentProviderUploadProgress(
  10946. [](Server &svr) {
  10947. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10948. res.set_content("provider received", "text/plain");
  10949. });
  10950. },
  10951. [](Client &cli, UploadProgress progress_callback) {
  10952. return cli.Post(
  10953. "/test", 9,
  10954. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10955. sink.os << "test data";
  10956. return true;
  10957. },
  10958. "text/plain", progress_callback);
  10959. });
  10960. }
  10961. // Helper function for multipart upload progress tests
  10962. template <typename SetupHandler, typename ClientCall>
  10963. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10964. ClientCall &&client_call,
  10965. const string &endpoint) {
  10966. Server svr;
  10967. setup_handler(svr);
  10968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10969. auto se = detail::scope_exit([&] {
  10970. svr.stop();
  10971. t.join();
  10972. });
  10973. svr.wait_until_ready();
  10974. Client cli(HOST, PORT);
  10975. vector<uint64_t> progress_values;
  10976. UploadFormDataItems items = {
  10977. {"field1", "value1", "", ""},
  10978. {"field2", "longer value for progress tracking test", "", ""},
  10979. {"file1", "file content data for upload progress", "test.txt",
  10980. "text/plain"}};
  10981. auto res = client_call(cli, endpoint, items,
  10982. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10983. progress_values.push_back(current);
  10984. return true;
  10985. });
  10986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10987. EXPECT_EQ(200, res->status);
  10988. EXPECT_FALSE(progress_values.empty());
  10989. }
  10990. TEST(UploadProgressTest, PostMultipartProgress) {
  10991. TestMultipartUploadProgress(
  10992. [](Server &svr) {
  10993. svr.Post("/multipart", [](const Request &req, Response &res) {
  10994. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10995. res.set_content("multipart received", "text/plain");
  10996. });
  10997. },
  10998. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10999. UploadProgress progress_callback) {
  11000. return cli.Post(endpoint, items, progress_callback);
  11001. },
  11002. "/multipart");
  11003. }
  11004. // Helper function for basic download progress tests
  11005. template <typename SetupHandler, typename ClientCall>
  11006. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11007. ClientCall &&client_call, const string &endpoint,
  11008. size_t expected_content_size) {
  11009. Server svr;
  11010. setup_handler(svr);
  11011. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11012. auto se = detail::scope_exit([&] {
  11013. svr.stop();
  11014. t.join();
  11015. });
  11016. svr.wait_until_ready();
  11017. Client cli(HOST, PORT);
  11018. vector<uint64_t> progress_values;
  11019. auto res = client_call(cli, endpoint,
  11020. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11021. progress_values.push_back(current);
  11022. return true;
  11023. });
  11024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11025. EXPECT_EQ(200, res->status);
  11026. EXPECT_FALSE(progress_values.empty());
  11027. EXPECT_EQ(expected_content_size, res->body.size());
  11028. }
  11029. TEST(DownloadProgressTest, GetBasic) {
  11030. TestBasicDownloadProgress(
  11031. [](Server &svr) {
  11032. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11033. string content(1000, 'D');
  11034. res.set_content(content, "text/plain");
  11035. });
  11036. },
  11037. [](Client &cli, const string &endpoint,
  11038. DownloadProgress progress_callback) {
  11039. return cli.Get(endpoint, progress_callback);
  11040. },
  11041. "/download", 1000u);
  11042. }
  11043. // Helper function for content receiver download progress tests
  11044. template <typename SetupHandler, typename ClientCall>
  11045. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11046. ClientCall &&client_call,
  11047. const string &endpoint,
  11048. size_t expected_content_size) {
  11049. Server svr;
  11050. setup_handler(svr);
  11051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11052. auto se = detail::scope_exit([&] {
  11053. svr.stop();
  11054. t.join();
  11055. });
  11056. svr.wait_until_ready();
  11057. Client cli(HOST, PORT);
  11058. vector<uint64_t> progress_values;
  11059. string received_body;
  11060. auto res = client_call(
  11061. cli, endpoint,
  11062. [&](const char *data, size_t data_length) -> bool {
  11063. received_body.append(data, data_length);
  11064. return true;
  11065. },
  11066. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11067. progress_values.push_back(current);
  11068. return true;
  11069. });
  11070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11071. EXPECT_EQ(200, res->status);
  11072. EXPECT_FALSE(progress_values.empty());
  11073. EXPECT_EQ(expected_content_size, received_body.size());
  11074. EXPECT_TRUE(res->body.empty());
  11075. }
  11076. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11077. TestContentReceiverDownloadProgress(
  11078. [](Server &svr) {
  11079. svr.Get("/download-receiver",
  11080. [](const Request & /*req*/, Response &res) {
  11081. string content(2000, 'R');
  11082. res.set_content(content, "text/plain");
  11083. });
  11084. },
  11085. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11086. DownloadProgress progress_callback) {
  11087. return cli.Get(endpoint, content_receiver, progress_callback);
  11088. },
  11089. "/download-receiver", 2000u);
  11090. }
  11091. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11092. // A provider reaching a pass with nothing to hand over - an empty buffer
  11093. // popped off a queue, say - must not be taken to mean the body is finished.
  11094. // It used to end the loop with the terminating chunk unwritten while the
  11095. // server still considered the response complete, so the peer waited for an
  11096. // end that never arrived.
  11097. Server svr;
  11098. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11099. auto step = std::make_shared<int>(0);
  11100. res.set_chunked_content_provider("text/plain",
  11101. [step](size_t /*offset*/, DataSink &sink) {
  11102. switch ((*step)++) {
  11103. case 0: sink.write("", 0); break;
  11104. case 1: sink.write("hello", 5); break;
  11105. default: sink.done(); break;
  11106. }
  11107. return true;
  11108. });
  11109. });
  11110. auto port = svr.bind_to_any_port(HOST);
  11111. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11112. auto listen_se = detail::scope_exit([&] {
  11113. svr.stop();
  11114. listen_thread.join();
  11115. ASSERT_FALSE(svr.is_running());
  11116. });
  11117. svr.wait_until_ready();
  11118. Client cli(HOST, port);
  11119. // Without the fix the body is never terminated, so bound the wait rather
  11120. // than letting the test hang on the default read timeout.
  11121. cli.set_read_timeout(5, 0);
  11122. auto res = cli.Get("/stream");
  11123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11124. EXPECT_EQ(StatusCode::OK_200, res->status);
  11125. EXPECT_EQ("hello", res->body);
  11126. }
  11127. TEST(StreamingTest, NoContentLengthStreaming) {
  11128. Server svr;
  11129. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11130. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11131. if (offset < 6) {
  11132. sink.os << (offset < 3 ? "a" : "b");
  11133. } else {
  11134. sink.done();
  11135. }
  11136. return true;
  11137. });
  11138. });
  11139. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11140. auto listen_se = detail::scope_exit([&] {
  11141. svr.stop();
  11142. listen_thread.join();
  11143. ASSERT_FALSE(svr.is_running());
  11144. });
  11145. svr.wait_until_ready();
  11146. Client client(HOST, PORT);
  11147. auto get_thread = std::thread([&client]() {
  11148. std::string s;
  11149. auto res =
  11150. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11151. s += std::string(data, len);
  11152. return true;
  11153. });
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::OK_200, res->status);
  11156. EXPECT_EQ("aaabbb", s);
  11157. });
  11158. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11159. // Give GET time to get a few messages.
  11160. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11161. }
  11162. TEST(MountTest, Unmount) {
  11163. Server svr;
  11164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. listen_thread.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. });
  11170. svr.wait_until_ready();
  11171. Client cli("localhost", PORT);
  11172. svr.set_mount_point("/mount2", "./www2");
  11173. auto res = cli.Get("/");
  11174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11175. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11176. res = cli.Get("/mount2/dir/test.html");
  11177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11178. EXPECT_EQ(StatusCode::OK_200, res->status);
  11179. svr.set_mount_point("/", "./www");
  11180. res = cli.Get("/dir/");
  11181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11182. EXPECT_EQ(StatusCode::OK_200, res->status);
  11183. svr.remove_mount_point("/");
  11184. res = cli.Get("/dir/");
  11185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11187. svr.remove_mount_point("/mount2");
  11188. res = cli.Get("/mount2/dir/test.html");
  11189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11190. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11191. }
  11192. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11193. Server svr;
  11194. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11195. svr.Get("/api/hello", [](const Request &, Response &res) {
  11196. res.set_content("api", "text/plain");
  11197. });
  11198. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11199. auto se = detail::scope_exit([&] {
  11200. svr.stop();
  11201. listen_thread.join();
  11202. ASSERT_FALSE(svr.is_running());
  11203. });
  11204. svr.wait_until_ready();
  11205. Client cli(HOST, PORT);
  11206. auto res = cli.Get("/dir/test.html");
  11207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11208. EXPECT_EQ(StatusCode::OK_200, res->status);
  11209. res = cli.Get("/api/hello");
  11210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11211. EXPECT_EQ(StatusCode::OK_200, res->status);
  11212. EXPECT_EQ("api", res->body);
  11213. }
  11214. TEST(MountTest, PathSegmentBoundary) {
  11215. Server svr;
  11216. svr.set_mount_point("/mount2", "./www2");
  11217. svr.set_mount_point("/", "./www");
  11218. auto port = svr.bind_to_any_port(HOST);
  11219. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11220. auto se = detail::scope_exit([&] {
  11221. svr.stop();
  11222. listen_thread.join();
  11223. ASSERT_FALSE(svr.is_running());
  11224. });
  11225. svr.wait_until_ready();
  11226. Client cli(HOST, port);
  11227. auto res = cli.Get("/mount2/dir/test.html");
  11228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11229. EXPECT_EQ(StatusCode::OK_200, res->status);
  11230. // "/mount2" must not match part-way through a path segment.
  11231. res = cli.Get("/mount2dir/test.html");
  11232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11234. // A mount point ending in '/' keeps matching every path below it.
  11235. res = cli.Get("/dir/test.html");
  11236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11237. EXPECT_EQ(StatusCode::OK_200, res->status);
  11238. }
  11239. TEST(MountTest, Redicect) {
  11240. Server svr;
  11241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.set_mount_point("/", "./www");
  11248. svr.wait_until_ready();
  11249. Client cli("localhost", PORT);
  11250. auto res = cli.Get("/dir/");
  11251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11252. EXPECT_EQ(StatusCode::OK_200, res->status);
  11253. res = cli.Get("/dir");
  11254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11255. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11256. res = cli.Get("/file");
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. EXPECT_EQ(StatusCode::OK_200, res->status);
  11259. res = cli.Get("/file/");
  11260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11262. cli.set_follow_location(true);
  11263. res = cli.Get("/dir");
  11264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11265. EXPECT_EQ(StatusCode::OK_200, res->status);
  11266. }
  11267. TEST(MountTest, MultibytesPathName) {
  11268. Server svr;
  11269. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11270. auto se = detail::scope_exit([&] {
  11271. svr.stop();
  11272. listen_thread.join();
  11273. ASSERT_FALSE(svr.is_running());
  11274. });
  11275. svr.set_mount_point("/", "./www");
  11276. svr.wait_until_ready();
  11277. Client cli("localhost", PORT);
  11278. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11280. EXPECT_EQ(StatusCode::OK_200, res->status);
  11281. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11282. }
  11283. // A mount point serves no path with an empty segment or one ending in '.' or
  11284. // a space, so a guard in the pre-routing handler sees the path of every file
  11285. // that is served
  11286. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11287. Server svr;
  11288. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11289. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11290. if (req.path == "/dir/test.html") {
  11291. res.status = StatusCode::Unauthorized_401;
  11292. return Server::HandlerResponse::Handled;
  11293. }
  11294. return Server::HandlerResponse::Unhandled;
  11295. });
  11296. auto port = svr.bind_to_any_port(HOST);
  11297. ASSERT_LT(0, port);
  11298. thread t = thread([&] { svr.listen_after_bind(); });
  11299. auto se = detail::scope_exit([&] {
  11300. svr.stop();
  11301. t.join();
  11302. ASSERT_FALSE(svr.is_running());
  11303. });
  11304. svr.wait_until_ready();
  11305. Client cli(HOST, port);
  11306. for (auto path :
  11307. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11308. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11309. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11310. "/dir/test.html%3A%3A$DATA"}) {
  11311. SCOPED_TRACE(path);
  11312. auto res = cli.Get(path);
  11313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11315. }
  11316. }
  11317. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11318. Server svr;
  11319. svr.set_mount_point("/", "./www");
  11320. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11321. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11322. auto port = svr.bind_to_any_port(HOST);
  11323. ASSERT_GT(port, 0);
  11324. thread t = thread([&] { svr.listen_after_bind(); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. t.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. });
  11330. svr.wait_until_ready();
  11331. Client cli(HOST, port);
  11332. auto res = cli.Get("/dir/test.abcde");
  11333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11334. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11335. res = cli.Get("/dir/test.html");
  11336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11337. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11338. }
  11339. #ifdef _WIN32
  11340. // Issue #2435: mmap::open() must succeed even when another handle holds
  11341. // the file open for writing (e.g. an active log file).
  11342. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11343. const char *path = "mmap_concurrent_writer_test.txt";
  11344. const char *content = "hello";
  11345. {
  11346. std::ofstream f(path, std::ios::binary);
  11347. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11348. }
  11349. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11350. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11351. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11352. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11353. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11354. detail::mmap m(path);
  11355. ASSERT_TRUE(m.is_open());
  11356. EXPECT_EQ(strlen(content), m.size());
  11357. char buf[8];
  11358. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11359. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11360. }
  11361. #endif
  11362. #ifndef _WIN32
  11363. // A directory or a device has no size to serve.
  11364. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11365. const char *path = "./mmap_not_regular_test_dir";
  11366. ASSERT_EQ(0, ::mkdir(path, 0755));
  11367. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11368. for (auto p : {path, "/dev/null"}) {
  11369. detail::mmap m(p);
  11370. EXPECT_FALSE(m.is_open()) << p;
  11371. EXPECT_EQ(0U, m.size()) << p;
  11372. }
  11373. Server svr;
  11374. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11375. res.set_file_content("/dev/null");
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. thread t = thread([&] { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. svr.stop();
  11381. t.join();
  11382. });
  11383. svr.wait_until_ready();
  11384. auto res = Client(HOST, port).Get("/null");
  11385. ASSERT_TRUE(res);
  11386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11387. }
  11388. #endif
  11389. #ifdef __linux__
  11390. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11391. TEST(MmapTest, FileIsNotMapped) {
  11392. const char *path = "mmap_not_mapped_test.txt";
  11393. {
  11394. std::ofstream f(path, std::ios::binary);
  11395. f << "hello";
  11396. }
  11397. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11398. detail::mmap m(path);
  11399. ASSERT_TRUE(m.is_open());
  11400. std::ifstream maps("/proc/self/maps");
  11401. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11402. std::istreambuf_iterator<char>());
  11403. EXPECT_EQ(std::string::npos, mappings.find(path));
  11404. }
  11405. #endif
  11406. TEST(KeepAliveTest, ReadTimeout) {
  11407. Server svr;
  11408. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11409. std::this_thread::sleep_for(std::chrono::seconds(2));
  11410. res.set_content("a", "text/plain");
  11411. });
  11412. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11413. res.set_content("b", "text/plain");
  11414. });
  11415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. listen_thread.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. });
  11421. svr.wait_until_ready();
  11422. Client cli("localhost", PORT);
  11423. cli.set_keep_alive(true);
  11424. cli.set_read_timeout(std::chrono::seconds(1));
  11425. auto resa = cli.Get("/a");
  11426. ASSERT_FALSE(resa);
  11427. EXPECT_EQ(Error::Read, resa.error());
  11428. auto resb = cli.Get("/b");
  11429. ASSERT_TRUE(resb);
  11430. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11431. EXPECT_EQ("b", resb->body);
  11432. }
  11433. TEST(KeepAliveTest, MaxCount) {
  11434. size_t keep_alive_max_count = 3;
  11435. Server svr;
  11436. svr.set_keep_alive_max_count(keep_alive_max_count);
  11437. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11438. res.set_content("Hello World!", "text/plain");
  11439. });
  11440. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11441. auto se = detail::scope_exit([&] {
  11442. svr.stop();
  11443. listen_thread.join();
  11444. ASSERT_FALSE(svr.is_running());
  11445. });
  11446. svr.wait_until_ready();
  11447. Client cli(HOST, PORT);
  11448. cli.set_keep_alive(true);
  11449. for (size_t i = 0; i < 5; i++) {
  11450. auto result = cli.Get("/hi");
  11451. ASSERT_TRUE(result);
  11452. EXPECT_EQ(StatusCode::OK_200, result->status);
  11453. if (i == keep_alive_max_count - 1) {
  11454. EXPECT_EQ("close", result->get_header_value("Connection"));
  11455. } else {
  11456. EXPECT_FALSE(result->has_header("Connection"));
  11457. }
  11458. }
  11459. }
  11460. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11461. // can pull the next one into the server's buffer. The server must serve it
  11462. // without waiting for the socket to become readable again. The keep-alive
  11463. // timeout outlasts the client's read timeout, so a request left waiting for it
  11464. // shows up as a missing response.
  11465. static void serve_pipelining_routes(Server &svr,
  11466. const std::function<void(int)> &client) {
  11467. svr.set_keep_alive_timeout(5);
  11468. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11469. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11470. });
  11471. svr.Post("/echo", [](const Request &req, Response &res) {
  11472. res.set_content("echo " + req.body, "text/plain");
  11473. });
  11474. auto port = svr.bind_to_any_port(HOST);
  11475. thread t = thread([&] { svr.listen_after_bind(); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. });
  11480. svr.wait_until_ready();
  11481. client(port);
  11482. }
  11483. static std::string
  11484. send_pipelined_requests(const std::vector<std::string> &parts) {
  11485. Server svr;
  11486. std::string res;
  11487. serve_pipelining_routes(svr, [&](int port) {
  11488. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11489. });
  11490. return res;
  11491. }
  11492. static void expect_in_order(const std::string &res,
  11493. const std::vector<std::string> &bodies) {
  11494. size_t pos = 0;
  11495. for (const auto &body : bodies) {
  11496. pos = res.find(body, pos);
  11497. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11498. pos += body.size();
  11499. }
  11500. }
  11501. TEST(KeepAliveTest, PipelinedRequests) {
  11502. auto res = send_pipelined_requests(
  11503. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11504. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11505. "Content-Length: 4\r\n\r\nbody"
  11506. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11507. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11508. }
  11509. // The second request starts in the server's buffer and ends on the socket.
  11510. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11511. auto res =
  11512. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11513. "GET /hi/2 HTTP/1.1\r\nHo",
  11514. "st: localhost\r\nConnection: close\r\n\r\n"});
  11515. expect_in_order(res, {"hi 1", "hi 2"});
  11516. }
  11517. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11518. // CRLF after a body does not turn into a 400 for the next request.
  11519. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11520. auto res = send_pipelined_requests(
  11521. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11522. "Content-Length: 4\r\n\r\nbody\r\n"
  11523. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11524. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11525. expect_in_order(res, {"echo body", "hi 2"});
  11526. }
  11527. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11528. // must not be served as the next request.
  11529. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11530. auto res = send_pipelined_requests(
  11531. {"INVALID REQUEST LINE\r\n\r\n"
  11532. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11533. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11534. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11535. }
  11536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11537. // Over TLS, the next request is held by the TLS library as already decrypted
  11538. // data rather than on the socket.
  11539. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11541. std::string res;
  11542. serve_pipelining_routes(svr, [&](int port) {
  11543. // One part, so all three requests arrive in one TLS record
  11544. EXPECT_TRUE(send_ssl_request_in_parts(
  11545. 2,
  11546. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11547. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11548. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11549. &res, port));
  11550. });
  11551. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11552. }
  11553. #endif
  11554. TEST(KeepAliveTest, Issue1041) {
  11555. Server svr;
  11556. svr.set_keep_alive_timeout(3);
  11557. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11558. res.set_content("Hello World!", "text/plain");
  11559. });
  11560. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11561. auto se = detail::scope_exit([&] {
  11562. svr.stop();
  11563. listen_thread.join();
  11564. ASSERT_FALSE(svr.is_running());
  11565. });
  11566. svr.wait_until_ready();
  11567. Client cli(HOST, PORT);
  11568. cli.set_keep_alive(true);
  11569. auto result = cli.Get("/hi");
  11570. ASSERT_TRUE(result);
  11571. EXPECT_EQ(StatusCode::OK_200, result->status);
  11572. std::this_thread::sleep_for(std::chrono::seconds(5));
  11573. result = cli.Get("/hi");
  11574. ASSERT_TRUE(result);
  11575. EXPECT_EQ(StatusCode::OK_200, result->status);
  11576. }
  11577. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11578. Server svr;
  11579. svr.set_keep_alive_max_count(0);
  11580. std::set<int> remote_ports;
  11581. svr.Get("/hi", [&](const Request &req, Response &res) {
  11582. remote_ports.insert(req.remote_port);
  11583. res.set_content("hi", "text/plain");
  11584. });
  11585. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11586. auto se = detail::scope_exit([&] {
  11587. svr.stop();
  11588. listen_thread.join();
  11589. ASSERT_FALSE(svr.is_running());
  11590. });
  11591. svr.wait_until_ready();
  11592. Client cli(HOST, PORT);
  11593. cli.set_keep_alive(true);
  11594. for (int i = 0; i < 3; i++) {
  11595. auto res = cli.Get("/hi");
  11596. ASSERT_TRUE(res);
  11597. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11598. }
  11599. // All three over one connection
  11600. EXPECT_EQ(1u, remote_ports.size());
  11601. }
  11602. // Forward declaration (see the base64_encode note).
  11603. namespace httplib {
  11604. namespace detail {
  11605. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11606. } // namespace detail
  11607. } // namespace httplib
  11608. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11609. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11610. #ifndef _WIN32
  11611. signal(SIGPIPE, SIG_IGN);
  11612. #endif
  11613. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11614. ASSERT_NE(INVALID_SOCKET, srv);
  11615. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11616. default_socket_options(srv);
  11617. sockaddr_in addr{};
  11618. addr.sin_family = AF_INET;
  11619. addr.sin_port = 0;
  11620. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11621. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11622. ASSERT_EQ(0, ::listen(srv, 2));
  11623. socklen_t addr_len = sizeof(addr);
  11624. ASSERT_EQ(0,
  11625. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11626. auto port = ntohs(addr.sin_port);
  11627. struct Peer {
  11628. socket_t sock = INVALID_SOCKET;
  11629. #ifdef CPPHTTPLIB_SSL_ENABLED
  11630. tls::session_t session = nullptr;
  11631. #endif
  11632. };
  11633. #ifdef CPPHTTPLIB_SSL_ENABLED
  11634. tls::ctx_t ctx = nullptr;
  11635. if (use_tls) {
  11636. ctx = tls::create_server_context();
  11637. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11638. nullptr);
  11639. }
  11640. auto ctx_se = detail::scope_exit([&] {
  11641. if (ctx) { tls::free_context(ctx); }
  11642. });
  11643. #endif
  11644. auto close_peer = [](Peer &peer) {
  11645. #ifdef CPPHTTPLIB_SSL_ENABLED
  11646. if (peer.session) { tls::free_session(peer.session); }
  11647. #endif
  11648. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11649. };
  11650. auto accept_peer = [&]() {
  11651. Peer peer;
  11652. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11653. peer.sock = ::accept(srv, nullptr, nullptr);
  11654. if (peer.sock == INVALID_SOCKET) { return peer; }
  11655. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11656. #ifdef CPPHTTPLIB_SSL_ENABLED
  11657. if (use_tls) {
  11658. peer.session = tls::create_session(ctx, peer.sock);
  11659. tls::TlsError err;
  11660. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11661. close_peer(peer);
  11662. return Peer();
  11663. }
  11664. }
  11665. #endif
  11666. return peer;
  11667. };
  11668. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11669. #ifdef CPPHTTPLIB_SSL_ENABLED
  11670. tls::TlsError err;
  11671. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11672. #endif
  11673. return detail::read_socket(peer.sock, buf, len, 0);
  11674. };
  11675. auto read_head = [&](const Peer &peer) {
  11676. std::string head;
  11677. char buf[1024];
  11678. while (head.find("\r\n\r\n") == std::string::npos) {
  11679. auto n = read_some(peer, buf, sizeof(buf));
  11680. if (n <= 0) { break; }
  11681. head.append(buf, static_cast<size_t>(n));
  11682. }
  11683. };
  11684. auto send_text = [](const Peer &peer, const std::string &text) {
  11685. #ifdef CPPHTTPLIB_SSL_ENABLED
  11686. tls::TlsError err;
  11687. if (peer.session) {
  11688. tls::write(peer.session, text.data(), text.size(), err);
  11689. return;
  11690. }
  11691. #endif
  11692. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11693. };
  11694. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11695. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11696. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11697. // Sent once the first response is read, so that it lands on an idle socket
  11698. std::promise<void> first_response_read;
  11699. auto first_response_read_future = first_response_read.get_future();
  11700. auto server_thread = std::thread([&] {
  11701. auto peer1 = accept_peer();
  11702. if (peer1.sock == INVALID_SOCKET) { return; }
  11703. read_head(peer1);
  11704. if (same_write) {
  11705. send_text(peer1, first + stray);
  11706. } else {
  11707. send_text(peer1, first);
  11708. first_response_read_future.wait_for(std::chrono::seconds(5));
  11709. send_text(peer1, stray);
  11710. }
  11711. // peer1 stays open, so only the unread data can tell the client
  11712. auto peer2 = accept_peer();
  11713. if (peer2.sock != INVALID_SOCKET) {
  11714. read_head(peer2);
  11715. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11716. "Connection: close\r\n\r\nsecond");
  11717. close_peer(peer2);
  11718. }
  11719. close_peer(peer1);
  11720. });
  11721. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11722. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11723. std::to_string(port));
  11724. #ifdef CPPHTTPLIB_SSL_ENABLED
  11725. cli.enable_server_certificate_verification(false);
  11726. #endif
  11727. cli.set_keep_alive(true);
  11728. cli.set_read_timeout(5, 0);
  11729. auto res = cli.Get("/1");
  11730. first_response_read.set_value();
  11731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11732. EXPECT_EQ("first", res->body);
  11733. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11734. res = cli.Get("/2");
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. EXPECT_EQ(StatusCode::OK_200, res->status);
  11737. EXPECT_EQ("second", res->body);
  11738. }
  11739. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11740. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11741. }
  11742. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11743. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11744. }
  11745. #ifdef CPPHTTPLIB_SSL_ENABLED
  11746. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11747. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11748. }
  11749. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11750. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11751. }
  11752. #endif
  11753. TEST(KeepAliveTest, Issue1959) {
  11754. Server svr;
  11755. svr.set_keep_alive_timeout(5);
  11756. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11757. res.set_content("a", "text/plain");
  11758. });
  11759. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11760. auto se = detail::scope_exit([&] {
  11761. if (!svr.is_running()) return;
  11762. svr.stop();
  11763. listen_thread.join();
  11764. ASSERT_FALSE(svr.is_running());
  11765. });
  11766. svr.wait_until_ready();
  11767. Client cli("localhost", PORT);
  11768. cli.set_keep_alive(true);
  11769. using namespace std::chrono;
  11770. auto start = steady_clock::now();
  11771. cli.Get("/a");
  11772. svr.stop();
  11773. listen_thread.join();
  11774. auto end = steady_clock::now();
  11775. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11776. EXPECT_LT(elapsed, 5000);
  11777. }
  11778. #ifdef CPPHTTPLIB_SSL_ENABLED
  11779. TEST(KeepAliveTest, SSLClientReconnection) {
  11780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11781. ASSERT_TRUE(svr.is_valid());
  11782. svr.set_keep_alive_timeout(1);
  11783. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11784. res.set_content("Hello World!", "text/plain");
  11785. });
  11786. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11787. auto se = detail::scope_exit([&] {
  11788. svr.stop();
  11789. listen_thread.join();
  11790. ASSERT_FALSE(svr.is_running());
  11791. });
  11792. svr.wait_until_ready();
  11793. SSLClient cli(HOST, PORT);
  11794. cli.enable_server_certificate_verification(false);
  11795. cli.set_keep_alive(true);
  11796. auto result = cli.Get("/hi");
  11797. ASSERT_TRUE(result);
  11798. EXPECT_EQ(StatusCode::OK_200, result->status);
  11799. result = cli.Get("/hi");
  11800. ASSERT_TRUE(result);
  11801. EXPECT_EQ(StatusCode::OK_200, result->status);
  11802. std::this_thread::sleep_for(std::chrono::seconds(2));
  11803. // Recoonect
  11804. result = cli.Get("/hi");
  11805. ASSERT_TRUE(result);
  11806. EXPECT_EQ(StatusCode::OK_200, result->status);
  11807. result = cli.Get("/hi");
  11808. ASSERT_TRUE(result);
  11809. EXPECT_EQ(StatusCode::OK_200, result->status);
  11810. }
  11811. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11813. ASSERT_TRUE(svr.is_valid());
  11814. svr.set_keep_alive_timeout(1);
  11815. std::string content = "reconnect";
  11816. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11817. res.set_content("Hello World!", "text/plain");
  11818. });
  11819. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11820. auto se = detail::scope_exit([&] {
  11821. svr.stop();
  11822. listen_thread.join();
  11823. ASSERT_FALSE(svr.is_running());
  11824. });
  11825. svr.wait_until_ready();
  11826. SSLClient cli(HOST, PORT);
  11827. cli.enable_server_certificate_verification(false);
  11828. cli.set_keep_alive(true);
  11829. auto result = cli.Post(
  11830. "/hi", content.size(),
  11831. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11832. sink.write(content.c_str(), content.size());
  11833. return true;
  11834. },
  11835. "text/plain");
  11836. ASSERT_TRUE(result);
  11837. EXPECT_EQ(200, result->status);
  11838. std::this_thread::sleep_for(std::chrono::seconds(2));
  11839. // Recoonect
  11840. result = cli.Post(
  11841. "/hi", content.size(),
  11842. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11843. sink.write(content.c_str(), content.size());
  11844. return true;
  11845. },
  11846. "text/plain");
  11847. ASSERT_TRUE(result);
  11848. EXPECT_EQ(200, result->status);
  11849. result = cli.Post(
  11850. "/hi", content.size(),
  11851. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11852. sink.write(content.c_str(), content.size());
  11853. return true;
  11854. },
  11855. "text/plain");
  11856. ASSERT_TRUE(result);
  11857. EXPECT_EQ(200, result->status);
  11858. }
  11859. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11860. using namespace httplib::tls;
  11861. {
  11862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11863. ASSERT_TRUE(svr.is_valid());
  11864. svr.Get("/sni", [&](const Request &req, Response &res) {
  11865. std::string expected = req.sni();
  11866. EXPECT_EQ(expected, req.get_param_value("expected"));
  11867. res.set_content("ok", "text/plain");
  11868. });
  11869. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11870. auto se = detail::scope_exit([&] {
  11871. svr.stop();
  11872. listen_thread.join();
  11873. ASSERT_FALSE(svr.is_running());
  11874. });
  11875. svr.wait_until_ready();
  11876. {
  11877. SSLClient cli("localhost", PORT);
  11878. cli.enable_server_certificate_verification(false);
  11879. auto res = cli.Get("/sni?expected=localhost");
  11880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11881. }
  11882. {
  11883. SSLClient cli("::1", PORT);
  11884. cli.enable_server_certificate_verification(false);
  11885. auto res = cli.Get("/sni?expected=");
  11886. // NOTE: This may fail if the server is listening on IPv4 only
  11887. // (e.g., when localhost resolves to 127.0.0.1 only)
  11888. if (res) {
  11889. EXPECT_EQ(StatusCode::OK_200, res->status);
  11890. } else {
  11891. EXPECT_EQ(Error::Connection, res.error());
  11892. }
  11893. }
  11894. }
  11895. }
  11896. // The SNI of a failed handshake does not reach the next connection that the
  11897. // same worker thread serves
  11898. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11900. ASSERT_TRUE(svr.is_valid());
  11901. svr.new_task_queue = [] { return new ThreadPool(1); };
  11902. svr.Get("/sni", [](const Request &req, Response &res) {
  11903. res.set_content(req.sni(), "text/plain");
  11904. });
  11905. auto port = svr.bind_to_any_port("127.0.0.1");
  11906. ASSERT_LT(0, port);
  11907. thread t = thread([&] { svr.listen_after_bind(); });
  11908. auto se = detail::scope_exit([&] {
  11909. svr.stop();
  11910. t.join();
  11911. ASSERT_FALSE(svr.is_running());
  11912. });
  11913. svr.wait_until_ready();
  11914. {
  11915. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11916. SSLClient cli("localhost", port);
  11917. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11918. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11919. auto res = cli.Get("/sni");
  11920. ASSERT_FALSE(res);
  11921. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11922. }
  11923. // An IP host sends no SNI (RFC 6066)
  11924. SSLClient cli("127.0.0.1", port);
  11925. cli.enable_server_certificate_verification(false);
  11926. auto res = cli.Get("/sni");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. EXPECT_EQ("", res->body);
  11929. }
  11930. #endif
  11931. TEST(ClientProblemDetectionTest, ContentProvider) {
  11932. Server svr;
  11933. size_t content_length = 1024 * 1024;
  11934. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11935. res.set_content_provider(
  11936. content_length, "text/plain",
  11937. [&](size_t offset, size_t length, DataSink &sink) {
  11938. auto out_len = std::min(length, static_cast<size_t>(1024));
  11939. std::string out(out_len, '@');
  11940. sink.write(out.data(), out_len);
  11941. return offset < 4096;
  11942. },
  11943. [](bool success) { ASSERT_FALSE(success); });
  11944. });
  11945. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11946. res.set_content_provider(
  11947. 0, "text/plain",
  11948. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11949. EXPECT_TRUE(false);
  11950. return true;
  11951. },
  11952. [](bool success) { ASSERT_FALSE(success); });
  11953. });
  11954. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11955. auto se = detail::scope_exit([&] {
  11956. svr.stop();
  11957. listen_thread.join();
  11958. ASSERT_FALSE(svr.is_running());
  11959. });
  11960. svr.wait_until_ready();
  11961. Client cli("localhost", PORT);
  11962. {
  11963. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11964. size_t /*data_length*/) { return false; });
  11965. ASSERT_FALSE(res);
  11966. }
  11967. {
  11968. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11969. size_t /*data_length*/) { return false; });
  11970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11971. }
  11972. }
  11973. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11974. // A provider that reports success without writing anything and without
  11975. // calling done() used to be handed the same offset and length again on every
  11976. // pass, so it spun for as long as the peer stayed connected.
  11977. Server svr;
  11978. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11979. res.set_content("ok", "text/plain");
  11980. });
  11981. auto port = svr.bind_to_any_port(HOST);
  11982. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11983. auto se = detail::scope_exit([&] {
  11984. svr.stop();
  11985. listen_thread.join();
  11986. ASSERT_FALSE(svr.is_running());
  11987. });
  11988. svr.wait_until_ready();
  11989. std::atomic<int> call_count{0};
  11990. Client cli(HOST, port);
  11991. auto res = cli.Post(
  11992. "/", 1024,
  11993. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11994. // Give up after enough passes to show the spin, so that losing the
  11995. // check below fails this test instead of hanging it.
  11996. return ++call_count < 100;
  11997. },
  11998. "text/plain");
  11999. ASSERT_FALSE(res);
  12000. EXPECT_EQ(Error::Write, res.error());
  12001. EXPECT_EQ(1, call_count.load());
  12002. }
  12003. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12004. // A writer only has to assign `write`. The other three used to be left as
  12005. // empty std::functions, so a provider calling one threw
  12006. // std::bad_function_call out of the thread running it and took the whole
  12007. // process down.
  12008. DataSink sink;
  12009. std::string written;
  12010. sink.write = [&](const char *data, size_t data_len) {
  12011. written.append(data, data_len);
  12012. return true;
  12013. };
  12014. EXPECT_TRUE(sink.is_writable());
  12015. sink.done();
  12016. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12017. EXPECT_TRUE(written.empty());
  12018. }
  12019. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12020. // A sink that cannot carry trailers still has to finish.
  12021. DataSink sink;
  12022. auto done_count = 0;
  12023. sink.done = [&]() { done_count++; };
  12024. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12025. EXPECT_EQ(1, done_count);
  12026. }
  12027. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12028. Server svr;
  12029. const std::string body(4096, 'x');
  12030. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12031. res.set_content_provider(body.size(), "text/plain",
  12032. [&](size_t offset, size_t length, DataSink &sink) {
  12033. sink.write(body.data() + offset, length);
  12034. sink.done();
  12035. return true;
  12036. });
  12037. });
  12038. auto port = svr.bind_to_any_port(HOST);
  12039. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12040. auto se = detail::scope_exit([&] {
  12041. svr.stop();
  12042. listen_thread.join();
  12043. ASSERT_FALSE(svr.is_running());
  12044. });
  12045. svr.wait_until_ready();
  12046. Client cli(HOST, port);
  12047. auto res = cli.Get("/");
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. EXPECT_EQ(StatusCode::OK_200, res->status);
  12050. EXPECT_EQ(body, res->body);
  12051. }
  12052. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12053. Server svr;
  12054. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12055. res.set_content_provider(
  12056. 1024, "text/plain",
  12057. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12058. sink.write("hello", 5);
  12059. sink.done(); // short of the 1024 bytes the response promised
  12060. return true;
  12061. });
  12062. });
  12063. auto port = svr.bind_to_any_port(HOST);
  12064. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12065. auto se = detail::scope_exit([&] {
  12066. svr.stop();
  12067. listen_thread.join();
  12068. ASSERT_FALSE(svr.is_running());
  12069. });
  12070. svr.wait_until_ready();
  12071. Client cli(HOST, port);
  12072. cli.set_read_timeout(5, 0);
  12073. // The response is short of its Content-Length, so the client cannot read a
  12074. // complete body. What matters is that this returns at all: a no-op done()
  12075. // would leave the writer looping over a provider that never makes progress.
  12076. auto res = cli.Get("/");
  12077. EXPECT_FALSE(res);
  12078. }
  12079. // Read as the next response by a peer that sees it after a framed body.
  12080. static const std::string smuggled_response =
  12081. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12082. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12083. Server svr;
  12084. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12085. res.set_content_provider(
  12086. 5, "text/plain",
  12087. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12088. auto data = "AAAAA" + smuggled_response;
  12089. sink.write(data.data(), data.size());
  12090. return true;
  12091. });
  12092. });
  12093. thread t = thread([&] { svr.listen(HOST, PORT); });
  12094. auto se = detail::scope_exit([&] {
  12095. svr.stop();
  12096. t.join();
  12097. ASSERT_FALSE(svr.is_running());
  12098. });
  12099. svr.wait_until_ready();
  12100. std::string resp;
  12101. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12102. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12103. resp.clear();
  12104. ASSERT_TRUE(send_request(
  12105. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12106. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12107. }
  12108. TEST(NoContentTest, BodyIsNotSent) {
  12109. Server svr;
  12110. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12111. res.status = StatusCode::NoContent_204;
  12112. res.set_content(smuggled_response, "text/plain");
  12113. });
  12114. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12115. res.status = StatusCode::NotModified_304;
  12116. res.set_chunked_content_provider(
  12117. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12118. sink.write(smuggled_response.data(), smuggled_response.size());
  12119. sink.done();
  12120. return true;
  12121. });
  12122. });
  12123. thread t = thread([&] { svr.listen(HOST, PORT); });
  12124. auto se = detail::scope_exit([&] {
  12125. svr.stop();
  12126. t.join();
  12127. ASSERT_FALSE(svr.is_running());
  12128. });
  12129. svr.wait_until_ready();
  12130. for (auto path : {"/204", "/304"}) {
  12131. std::string resp;
  12132. ASSERT_TRUE(send_request(
  12133. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12134. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12135. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12136. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12137. }
  12138. }
  12139. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12140. Server svr;
  12141. std::atomic<bool> smuggled(false);
  12142. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12143. res.set_content("ok", "text/plain");
  12144. });
  12145. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12146. smuggled = true;
  12147. });
  12148. auto port = svr.bind_to_any_port(HOST);
  12149. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12150. auto se = detail::scope_exit([&] {
  12151. svr.stop();
  12152. listen_thread.join();
  12153. ASSERT_FALSE(svr.is_running());
  12154. });
  12155. svr.wait_until_ready();
  12156. // What follows the body would be read as the next request.
  12157. Client cli(HOST, port);
  12158. auto res = cli.Post(
  12159. "/", 5,
  12160. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12161. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12162. sink.write(data.data(), data.size());
  12163. return true;
  12164. },
  12165. "text/plain");
  12166. ASSERT_FALSE(res);
  12167. EXPECT_EQ(Error::Write, res.error());
  12168. EXPECT_FALSE(smuggled);
  12169. }
  12170. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12171. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12172. // The compressed path builds the whole body before connecting, so this
  12173. // fails client-side and never reaches a server.
  12174. Client cli(HOST, PORT);
  12175. cli.set_compress(true);
  12176. auto res = cli.Post(
  12177. "/", 1024,
  12178. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12179. sink.write("hello", 5);
  12180. sink.done(); // short of the 1024 bytes the request announced
  12181. return true;
  12182. },
  12183. "text/plain");
  12184. ASSERT_FALSE(res);
  12185. EXPECT_EQ(Error::Write, res.error());
  12186. }
  12187. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12188. Server svr;
  12189. std::string received;
  12190. size_t content_length_count = 0;
  12191. bool has_transfer_encoding = true;
  12192. svr.Post("/echo", [&](const Request &req, Response &res) {
  12193. received = req.body;
  12194. content_length_count = req.get_header_value_count("Content-Length");
  12195. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12196. res.set_content("ok", "text/plain");
  12197. });
  12198. svr.Get("/next", [](const Request &, Response &res) {
  12199. res.set_content("next", "text/plain");
  12200. });
  12201. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12202. auto se = detail::scope_exit([&] {
  12203. svr.stop();
  12204. listen_thread.join();
  12205. ASSERT_FALSE(svr.is_running());
  12206. });
  12207. svr.wait_until_ready();
  12208. Client cli(HOST, PORT);
  12209. cli.set_keep_alive(true);
  12210. cli.set_compress(true);
  12211. const std::string body = "hello world";
  12212. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12213. auto res = cli.Post("/echo", headers, body, "text/plain");
  12214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12215. EXPECT_EQ(StatusCode::OK_200, res->status);
  12216. EXPECT_EQ(body, received);
  12217. EXPECT_EQ(1u, content_length_count);
  12218. EXPECT_FALSE(has_transfer_encoding);
  12219. // The rest of a truncated body would be read as this request
  12220. auto res2 = cli.Get("/next");
  12221. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12222. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12223. EXPECT_EQ("next", res2->body);
  12224. }
  12225. #endif
  12226. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12227. Server svr;
  12228. std::string received;
  12229. size_t content_length_count = 1;
  12230. bool has_transfer_encoding = false;
  12231. svr.Post("/echo", [&](const Request &req, Response &res) {
  12232. received = req.body;
  12233. content_length_count = req.get_header_value_count("Content-Length");
  12234. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12235. res.set_content("ok", "text/plain");
  12236. });
  12237. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. listen_thread.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. Client cli(HOST, PORT);
  12245. cli.set_keep_alive(true);
  12246. const std::string body = "hello world";
  12247. Headers headers = {{"Content-Length", "5"}};
  12248. auto res = cli.Post(
  12249. "/echo", headers,
  12250. [&](size_t /*offset*/, DataSink &sink) {
  12251. sink.write(body.data(), body.size());
  12252. sink.done();
  12253. return true;
  12254. },
  12255. "text/plain");
  12256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12257. EXPECT_EQ(StatusCode::OK_200, res->status);
  12258. EXPECT_EQ(body, received);
  12259. EXPECT_EQ(0u, content_length_count);
  12260. EXPECT_TRUE(has_transfer_encoding);
  12261. }
  12262. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12263. Server svr;
  12264. svr.set_error_handler([](Request const &, Response &res) -> void {
  12265. res.set_chunked_content_provider(
  12266. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12267. sink.os << "hello";
  12268. sink.os << "world";
  12269. sink.done();
  12270. return true;
  12271. });
  12272. });
  12273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. listen_thread.join();
  12277. ASSERT_FALSE(svr.is_running());
  12278. });
  12279. svr.wait_until_ready();
  12280. Client cli("localhost", PORT);
  12281. auto res = cli.Get("/");
  12282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12283. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12284. EXPECT_EQ("helloworld", res->body);
  12285. }
  12286. // A body set after a content provider must replace it, not be sent through it.
  12287. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12288. Server svr;
  12289. svr.set_mount_point("/", "./www");
  12290. svr.set_file_request_handler([](const Request &req, Response &res) {
  12291. if (req.path == "/dir/test.html") {
  12292. res.status = StatusCode::Forbidden_403;
  12293. res.set_content(std::string(5000, 'D'), "text/plain");
  12294. } else if (req.path == "/file") {
  12295. res.status = StatusCode::Forbidden_403;
  12296. res.body = "Denied";
  12297. }
  12298. });
  12299. auto port = svr.bind_to_any_port(HOST);
  12300. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12301. auto se = detail::scope_exit([&] {
  12302. svr.stop();
  12303. t.join();
  12304. ASSERT_FALSE(svr.is_running());
  12305. });
  12306. svr.wait_until_ready();
  12307. Client cli(HOST, port);
  12308. {
  12309. auto res = cli.Get("/dir/test.html");
  12310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12311. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12312. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12313. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12314. }
  12315. {
  12316. auto res = cli.Get("/file");
  12317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12318. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12319. EXPECT_EQ("Denied", res->body);
  12320. }
  12321. {
  12322. auto res = cli.Get("/dir/index.html");
  12323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12324. EXPECT_EQ(StatusCode::OK_200, res->status);
  12325. EXPECT_EQ(0U, res->body.find("<html>"));
  12326. }
  12327. }
  12328. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12329. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12330. Server svr;
  12331. std::vector<bool> released;
  12332. std::mutex released_mutex;
  12333. auto releaser = [&](bool success) {
  12334. std::lock_guard<std::mutex> guard(released_mutex);
  12335. released.push_back(success);
  12336. };
  12337. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12338. return sink.write(&"hello"[offset], length);
  12339. };
  12340. svr.Get("/sized", [&](const Request &, Response &res) {
  12341. res.status = StatusCode::NotFound_404;
  12342. res.set_content_provider(5, "text/plain", provider, releaser);
  12343. });
  12344. svr.Get("/chunked", [&](const Request &, Response &res) {
  12345. res.status = StatusCode::ServiceUnavailable_503;
  12346. res.set_chunked_content_provider(
  12347. "text/plain",
  12348. [](size_t, DataSink &sink) {
  12349. sink.os << "chunk";
  12350. sink.done();
  12351. return true;
  12352. },
  12353. releaser);
  12354. });
  12355. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12356. res.set_content_provider(5, "text/plain", provider, releaser);
  12357. throw std::runtime_error("after the provider");
  12358. });
  12359. svr.set_error_handler([](const Request &req, Response &res) {
  12360. // Leave the exception handler's content to it.
  12361. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12362. res.set_content(std::string(1000, 'E'), "text/html");
  12363. return Server::HandlerResponse::Handled;
  12364. });
  12365. svr.set_exception_handler(
  12366. [](const Request &, Response &res, std::exception_ptr) {
  12367. res.status = StatusCode::InternalServerError_500;
  12368. res.set_content(std::string(1000, 'X'), "text/html");
  12369. });
  12370. auto port = svr.bind_to_any_port(HOST);
  12371. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12372. auto se = detail::scope_exit([&] {
  12373. svr.stop();
  12374. t.join();
  12375. ASSERT_FALSE(svr.is_running());
  12376. });
  12377. svr.wait_until_ready();
  12378. Client cli(HOST, port);
  12379. {
  12380. auto res = cli.Get("/sized");
  12381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12383. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12384. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12385. }
  12386. {
  12387. auto res = cli.Get("/chunked");
  12388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12389. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12390. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12391. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12392. }
  12393. {
  12394. auto res = cli.Get("/throw");
  12395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12396. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12397. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12398. }
  12399. std::lock_guard<std::mutex> guard(released_mutex);
  12400. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12401. }
  12402. #endif
  12403. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12404. Server svr;
  12405. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12406. return sink.write(&"abc"[offset], length);
  12407. };
  12408. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12409. res.set_file_content("./www/dir/test.html");
  12410. res.set_content("body", "text/plain");
  12411. });
  12412. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12413. res.set_content(std::string(100, 'B'), "text/plain");
  12414. res.set_file_content("./www/dir/test.html");
  12415. });
  12416. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12417. res.set_content(std::string(100, 'B'), "text/plain");
  12418. res.set_content_provider(3, "text/x-provider", abc);
  12419. });
  12420. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12421. res.set_content_provider(3, "text/x-provider", abc);
  12422. res.set_content(std::string(100, 'B'), "text/plain");
  12423. });
  12424. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12425. res.set_content_provider(3, "text/x-provider", abc);
  12426. res.set_file_content("./www/dir/test.html", "text/x-file");
  12427. });
  12428. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12429. res.set_file_content("./www/dir/test.html");
  12430. res.set_header("Content-Type", "text/x-handler");
  12431. });
  12432. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12433. res.set_content_provider(3, "text/plain", abc);
  12434. res.body = "direct";
  12435. });
  12436. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12437. res.set_file_content("./www/dir/test.html");
  12438. res.body = "direct";
  12439. });
  12440. auto port = svr.bind_to_any_port(HOST);
  12441. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. });
  12447. svr.wait_until_ready();
  12448. Client cli(HOST, port);
  12449. auto expect_body = [&](const char *path, const std::string &body,
  12450. const std::string &type) {
  12451. // Uncompressed, so Content-Length can be compared with the body.
  12452. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12453. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12454. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12455. EXPECT_EQ(body, res->body) << path;
  12456. EXPECT_EQ(std::to_string(body.size()),
  12457. res->get_header_value("Content-Length"))
  12458. << path;
  12459. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12460. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12461. };
  12462. expect_body("/file-then-body", "body", "text/plain");
  12463. expect_body("/body-then-file", "test.html", "text/html");
  12464. expect_body("/body-then-provider", "abc", "text/x-provider");
  12465. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12466. expect_body("/provider-then-file", "test.html", "text/x-file");
  12467. expect_body("/file-then-header", "test.html", "text/x-handler");
  12468. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12469. expect_body("/file-then-direct-body", "direct", "text/plain");
  12470. // Ranges are checked against the body, not the dropped provider.
  12471. {
  12472. auto res = cli.Get("/provider-then-direct-body",
  12473. Headers{{make_range_header({{1, 2}})}});
  12474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12476. EXPECT_EQ("ir", res->body);
  12477. }
  12478. {
  12479. auto res = cli.Get("/file-then-direct-body",
  12480. Headers{{make_range_header({{7, 8}})}});
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12483. }
  12484. }
  12485. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12486. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12487. const char *path = "./truncated_while_served.txt";
  12488. const size_t size = 32 * 1024 * 1024;
  12489. {
  12490. std::ofstream f(path, std::ios::binary);
  12491. f << std::string(size, 'x');
  12492. }
  12493. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12494. // Over TLS, where the bytes are encrypted in this process rather than
  12495. // copied by send().
  12496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12497. svr.Get("/file", [&](const Request &, Response &res) {
  12498. res.set_file_content(path, "text/plain");
  12499. });
  12500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. thread.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. });
  12506. svr.wait_until_ready();
  12507. // The file shrinks once the first bytes are in, as a rewrite in place
  12508. // would, and reading the mapping past its new end used to raise SIGBUS.
  12509. SSLClient cli(HOST, PORT);
  12510. cli.enable_server_certificate_verification(false);
  12511. size_t received = 0;
  12512. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12513. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12514. received += len;
  12515. return true;
  12516. });
  12517. EXPECT_FALSE(res);
  12518. EXPECT_LT(received, size);
  12519. }
  12520. #endif
  12521. // Forward declaration (see the base64_encode note).
  12522. namespace httplib {
  12523. namespace detail {
  12524. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12525. const std::string &content_type,
  12526. EncodingType encoding);
  12527. } // namespace detail
  12528. } // namespace httplib
  12529. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12530. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12531. ASSERT_TRUE(mm->is_open());
  12532. Response res;
  12533. detail::set_file_content_provider(res, mm, "text/html",
  12534. detail::EncodingType::None);
  12535. std::string out;
  12536. DataSink sink;
  12537. sink.write = [&](const char *d, size_t l) {
  12538. out.append(d, l);
  12539. return true;
  12540. };
  12541. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12542. EXPECT_EQ("test.html", out);
  12543. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12544. EXPECT_EQ("test.html", out);
  12545. }
  12546. TEST(LongPollingTest, ClientCloseDetection) {
  12547. Server svr;
  12548. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12549. res.set_chunked_content_provider(
  12550. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12551. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12552. sink.os << "hello";
  12553. auto count = 10;
  12554. while (count > 0 && sink.is_writable()) {
  12555. this_thread::sleep_for(chrono::milliseconds(10));
  12556. count--;
  12557. }
  12558. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12559. return true;
  12560. });
  12561. });
  12562. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12563. auto se = detail::scope_exit([&] {
  12564. svr.stop();
  12565. listen_thread.join();
  12566. ASSERT_FALSE(svr.is_running());
  12567. });
  12568. svr.wait_until_ready();
  12569. Client cli("localhost", PORT);
  12570. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12571. EXPECT_EQ("hello", string(data, data_length));
  12572. return false; // close the socket immediately.
  12573. });
  12574. ASSERT_FALSE(res);
  12575. }
  12576. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12577. Server svr;
  12578. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12579. res.set_chunked_content_provider(
  12580. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12581. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12582. sink.os << "hello";
  12583. EXPECT_TRUE(sink.os.good());
  12584. // Wait for the client to close the connection
  12585. auto count = 10;
  12586. while (count > 0 && sink.is_writable()) {
  12587. this_thread::sleep_for(chrono::milliseconds(10));
  12588. count--;
  12589. }
  12590. // After client disconnect, write repeatedly until the socket
  12591. // write actually fails (small writes may be absorbed by the
  12592. // kernel buffer)
  12593. std::string chunk(1024, 'x');
  12594. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12595. sink.os << chunk;
  12596. }
  12597. EXPECT_TRUE(sink.os.fail());
  12598. return true;
  12599. });
  12600. });
  12601. auto port = svr.bind_to_any_port("localhost");
  12602. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. listen_thread.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. });
  12608. svr.wait_until_ready();
  12609. Client cli("localhost", port);
  12610. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12611. EXPECT_EQ("hello", string(data, data_length));
  12612. return false; // close the socket immediately.
  12613. });
  12614. ASSERT_FALSE(res);
  12615. }
  12616. TEST(GetWithParametersTest, GetWithParameters) {
  12617. Server svr;
  12618. svr.Get("/", [&](const Request &req, Response &) {
  12619. EXPECT_EQ("world", req.get_param_value("hello"));
  12620. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12621. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12622. });
  12623. svr.Get("/params", [&](const Request &req, Response &) {
  12624. EXPECT_EQ("world", req.get_param_value("hello"));
  12625. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12626. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12627. });
  12628. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12629. EXPECT_EQ("resource-id", req.matches[1]);
  12630. EXPECT_EQ("foo", req.get_param_value("param1"));
  12631. EXPECT_EQ("bar", req.get_param_value("param2"));
  12632. });
  12633. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12634. EXPECT_EQ("user-id", req.path_params.at("id"));
  12635. EXPECT_EQ("foo", req.get_param_value("param1"));
  12636. EXPECT_EQ("bar", req.get_param_value("param2"));
  12637. });
  12638. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12639. auto se = detail::scope_exit([&] {
  12640. svr.stop();
  12641. listen_thread.join();
  12642. ASSERT_FALSE(svr.is_running());
  12643. });
  12644. svr.wait_until_ready();
  12645. {
  12646. Client cli(HOST, PORT);
  12647. Params params;
  12648. params.emplace("hello", "world");
  12649. params.emplace("hello2", "world2");
  12650. params.emplace("hello3", "world3");
  12651. auto res = cli.Get("/", params, Headers{});
  12652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12653. EXPECT_EQ(StatusCode::OK_200, res->status);
  12654. }
  12655. {
  12656. Client cli(HOST, PORT);
  12657. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(StatusCode::OK_200, res->status);
  12660. }
  12661. {
  12662. Client cli(HOST, PORT);
  12663. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12665. EXPECT_EQ(StatusCode::OK_200, res->status);
  12666. }
  12667. {
  12668. Client cli(HOST, PORT);
  12669. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12671. EXPECT_EQ(StatusCode::OK_200, res->status);
  12672. }
  12673. }
  12674. TEST(GetWithParametersTest, GetWithParameters2) {
  12675. Server svr;
  12676. svr.Get("/", [&](const Request &req, Response &res) {
  12677. auto text = req.get_param_value("hello");
  12678. res.set_content(text, "text/plain");
  12679. });
  12680. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12681. auto se = detail::scope_exit([&] {
  12682. svr.stop();
  12683. listen_thread.join();
  12684. ASSERT_FALSE(svr.is_running());
  12685. });
  12686. svr.wait_until_ready();
  12687. Client cli("localhost", PORT);
  12688. Params params;
  12689. params.emplace("hello", "world");
  12690. std::string body;
  12691. auto res = cli.Get("/", params, Headers{},
  12692. [&](const char *data, size_t data_length) {
  12693. body.append(data, data_length);
  12694. return true;
  12695. });
  12696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12697. EXPECT_EQ(StatusCode::OK_200, res->status);
  12698. EXPECT_EQ("world", body);
  12699. }
  12700. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12701. Server svr;
  12702. svr.Get("/search", [&](const Request &req, Response &res) {
  12703. auto q = req.get_param_value("q");
  12704. res.set_content(q, "text/plain");
  12705. });
  12706. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12707. auto se = detail::scope_exit([&] {
  12708. svr.stop();
  12709. listen_thread.join();
  12710. ASSERT_FALSE(svr.is_running());
  12711. });
  12712. svr.wait_until_ready();
  12713. Client cli("localhost", PORT);
  12714. // Verify that Get(path, params) works without requiring Headers argument
  12715. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12717. EXPECT_EQ(StatusCode::OK_200, res->status);
  12718. EXPECT_EQ("cpp-httplib", res->body);
  12719. }
  12720. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12721. auto host = "httpbingo.org";
  12722. auto path = std::string{"/range/32"};
  12723. #ifdef CPPHTTPLIB_SSL_ENABLED
  12724. SSLClient cli(host);
  12725. #else
  12726. Client cli(host);
  12727. #endif
  12728. cli.set_default_headers({make_range_header({{1, 10}})});
  12729. cli.set_connection_timeout(5);
  12730. {
  12731. auto res = cli.Get(path);
  12732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12733. EXPECT_EQ("bcdefghijk", res->body);
  12734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12735. }
  12736. {
  12737. auto res = cli.Get(path);
  12738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12739. EXPECT_EQ("bcdefghijk", res->body);
  12740. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12741. }
  12742. }
  12743. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12744. Server svr;
  12745. svr.set_default_headers({{"Hello", "World"}});
  12746. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12747. res.set_content("ok", "text/plain");
  12748. });
  12749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12750. auto se = detail::scope_exit([&] {
  12751. svr.stop();
  12752. listen_thread.join();
  12753. ASSERT_FALSE(svr.is_running());
  12754. });
  12755. svr.wait_until_ready();
  12756. Client cli("localhost", PORT);
  12757. auto res = cli.Get("/");
  12758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12759. EXPECT_EQ(StatusCode::OK_200, res->status);
  12760. EXPECT_EQ("ok", res->body);
  12761. EXPECT_EQ("World", res->get_header_value("Hello"));
  12762. }
  12763. #ifdef CPPHTTPLIB_SSL_ENABLED
  12764. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. ASSERT_TRUE(svr.is_valid());
  12767. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12768. std::this_thread::sleep_for(std::chrono::seconds(2));
  12769. res.set_content("a", "text/plain");
  12770. });
  12771. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12772. res.set_content("b", "text/plain");
  12773. });
  12774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12775. auto se = detail::scope_exit([&] {
  12776. svr.stop();
  12777. listen_thread.join();
  12778. ASSERT_FALSE(svr.is_running());
  12779. });
  12780. svr.wait_until_ready();
  12781. SSLClient cli("localhost", PORT);
  12782. cli.enable_server_certificate_verification(false);
  12783. cli.set_keep_alive(true);
  12784. cli.set_read_timeout(std::chrono::seconds(1));
  12785. auto resa = cli.Get("/a");
  12786. ASSERT_TRUE(!resa);
  12787. EXPECT_EQ(Error::Read, resa.error());
  12788. auto resb = cli.Get("/b");
  12789. ASSERT_TRUE(resb);
  12790. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12791. EXPECT_EQ("b", resb->body);
  12792. }
  12793. // Closing an idle keep-alive connection sends close_notify and returns. The
  12794. // server must not wait for the client's close_notify: an idle client never
  12795. // sends one, so the worker would be held until the read timeout expires, and
  12796. // stop() would wait for it.
  12797. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12799. ASSERT_TRUE(svr.is_valid());
  12800. svr.set_keep_alive_timeout(1);
  12801. svr.set_read_timeout(10, 0);
  12802. svr.Get("/", [](const Request &, Response &res) {
  12803. res.set_content("ok", "text/plain");
  12804. });
  12805. auto port = svr.bind_to_any_port(HOST);
  12806. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12807. auto se = detail::scope_exit([&] {
  12808. if (listen_thread.joinable()) {
  12809. svr.stop();
  12810. listen_thread.join();
  12811. }
  12812. });
  12813. svr.wait_until_ready();
  12814. SSLClient cli(HOST, port);
  12815. cli.enable_server_certificate_verification(false);
  12816. cli.set_keep_alive(true);
  12817. auto res = cli.Get("/");
  12818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12819. EXPECT_EQ(StatusCode::OK_200, res->status);
  12820. // Stay idle past the keep-alive timeout so the server closes the connection.
  12821. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12822. auto start = std::chrono::steady_clock::now();
  12823. svr.stop();
  12824. listen_thread.join();
  12825. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12826. std::chrono::steady_clock::now() - start)
  12827. .count();
  12828. EXPECT_LT(elapsed, 3000);
  12829. }
  12830. #endif
  12831. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12832. protected:
  12833. ServerTestWithAI_PASSIVE()
  12834. : cli_(HOST, PORT)
  12835. #ifdef CPPHTTPLIB_SSL_ENABLED
  12836. ,
  12837. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12838. #endif
  12839. {
  12840. #ifdef CPPHTTPLIB_SSL_ENABLED
  12841. cli_.enable_server_certificate_verification(false);
  12842. #endif
  12843. }
  12844. virtual void SetUp() {
  12845. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12846. res.set_content("Hello World!", "text/plain");
  12847. });
  12848. t_ = thread(
  12849. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12850. svr_.wait_until_ready();
  12851. }
  12852. virtual void TearDown() {
  12853. svr_.stop();
  12854. t_.join();
  12855. }
  12856. #ifdef CPPHTTPLIB_SSL_ENABLED
  12857. SSLClient cli_;
  12858. SSLServer svr_;
  12859. #else
  12860. Client cli_;
  12861. Server svr_;
  12862. #endif
  12863. thread t_;
  12864. };
  12865. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12866. auto res = cli_.Get("/hi");
  12867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12868. EXPECT_EQ(StatusCode::OK_200, res->status);
  12869. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12870. EXPECT_EQ("Hello World!", res->body);
  12871. }
  12872. class ServerUpDownTest : public ::testing::Test {
  12873. protected:
  12874. ServerUpDownTest() : cli_(HOST, PORT) {}
  12875. virtual void SetUp() {
  12876. t_ = thread([&]() {
  12877. svr_.bind_to_any_port(HOST);
  12878. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12879. ASSERT_TRUE(svr_.listen_after_bind());
  12880. });
  12881. svr_.wait_until_ready();
  12882. }
  12883. virtual void TearDown() {
  12884. svr_.stop();
  12885. t_.join();
  12886. }
  12887. Client cli_;
  12888. Server svr_;
  12889. thread t_;
  12890. };
  12891. TEST_F(ServerUpDownTest, QuickStartStop) {
  12892. // Should not crash, especially when run with
  12893. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12894. }
  12895. class PayloadMaxLengthTest : public ::testing::Test {
  12896. protected:
  12897. PayloadMaxLengthTest()
  12898. : cli_(HOST, PORT)
  12899. #ifdef CPPHTTPLIB_SSL_ENABLED
  12900. ,
  12901. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12902. #endif
  12903. {
  12904. #ifdef CPPHTTPLIB_SSL_ENABLED
  12905. cli_.enable_server_certificate_verification(false);
  12906. #endif
  12907. }
  12908. virtual void SetUp() {
  12909. svr_.set_payload_max_length(8);
  12910. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12911. res.set_content("test", "text/plain");
  12912. });
  12913. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12914. svr_.wait_until_ready();
  12915. }
  12916. virtual void TearDown() {
  12917. svr_.stop();
  12918. t_.join();
  12919. }
  12920. #ifdef CPPHTTPLIB_SSL_ENABLED
  12921. SSLClient cli_;
  12922. SSLServer svr_;
  12923. #else
  12924. Client cli_;
  12925. Server svr_;
  12926. #endif
  12927. thread t_;
  12928. };
  12929. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12930. auto res = cli_.Post("/test", "123456789", "text/plain");
  12931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12932. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12933. res = cli_.Post("/test", "12345678", "text/plain");
  12934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12935. EXPECT_EQ(StatusCode::OK_200, res->status);
  12936. }
  12937. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12938. // Test chunked encoding with payload exceeding the 8-byte limit
  12939. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12940. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12942. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12943. }
  12944. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12945. // Test chunked encoding with payload within the 8-byte limit
  12946. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12947. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12949. EXPECT_EQ(StatusCode::OK_200, res->status);
  12950. }
  12951. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12952. // Test using send_request to send chunked data exceeding payload limit
  12953. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12954. "Host: " +
  12955. std::string(HOST) + ":" + std::to_string(PORT) +
  12956. "\r\n"
  12957. "Transfer-Encoding: chunked\r\n"
  12958. "Connection: close\r\n"
  12959. "\r\n"
  12960. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12961. "0123456789\r\n"
  12962. "0\r\n" // End chunk
  12963. "\r\n";
  12964. std::string response;
  12965. bool result = send_request(1, chunked_request, &response);
  12966. if (!result) {
  12967. // If send_request fails, it might be because the server closed the
  12968. // connection due to payload limit enforcement, which is acceptable
  12969. SUCCEED()
  12970. << "Server rejected oversized chunked request (connection closed)";
  12971. } else {
  12972. // If we got a response, check if it's an error response or connection was
  12973. // closed early Short response length indicates connection was closed due to
  12974. // payload limit
  12975. if (response.length() <= 10) {
  12976. SUCCEED() << "Server closed connection for oversized chunked request";
  12977. } else {
  12978. // Check for error status codes
  12979. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12980. response.find("Payload Too Large") != std::string::npos ||
  12981. response.find("400") != std::string::npos);
  12982. }
  12983. }
  12984. }
  12985. class LargePayloadMaxLengthTest : public ::testing::Test {
  12986. protected:
  12987. LargePayloadMaxLengthTest()
  12988. : cli_(HOST, PORT)
  12989. #ifdef CPPHTTPLIB_SSL_ENABLED
  12990. ,
  12991. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12992. #endif
  12993. {
  12994. #ifdef CPPHTTPLIB_SSL_ENABLED
  12995. cli_.enable_server_certificate_verification(false);
  12996. #endif
  12997. }
  12998. virtual void SetUp() {
  12999. // Set 10MB payload limit
  13000. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13001. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13002. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13003. res.set_content("Large payload test", "text/plain");
  13004. });
  13005. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13006. svr_.wait_until_ready();
  13007. }
  13008. virtual void TearDown() {
  13009. svr_.stop();
  13010. t_.join();
  13011. }
  13012. #ifdef CPPHTTPLIB_SSL_ENABLED
  13013. SSLClient cli_;
  13014. SSLServer svr_;
  13015. #else
  13016. Client cli_;
  13017. Server svr_;
  13018. #endif
  13019. thread t_;
  13020. };
  13021. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13022. // Test chunked encoding with payload within 10MB limit
  13023. std::string medium_payload(5 * 1024 * 1024,
  13024. 'A'); // 5MB payload, within 10MB limit
  13025. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13027. EXPECT_EQ(StatusCode::OK_200, res->status);
  13028. }
  13029. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13030. // Test chunked encoding with payload exceeding 10MB limit
  13031. std::string large_payload(12 * 1024 * 1024,
  13032. 'B'); // 12MB payload, exceeds 10MB limit
  13033. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13034. // Server may either return 413 or close the connection
  13035. if (res) {
  13036. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13037. } else {
  13038. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13039. }
  13040. }
  13041. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13042. Server svr;
  13043. svr.Get("/", [](const Request &, Response &res) {
  13044. // Claims the most the client accepts, far more than it sends, then drops
  13045. // the connection.
  13046. res.set_content_provider(std::string().max_size(), "text/plain",
  13047. [](size_t, size_t, DataSink &sink) {
  13048. sink.write("abc", 3);
  13049. return false;
  13050. });
  13051. });
  13052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13053. auto se = detail::scope_exit([&] {
  13054. svr.stop();
  13055. thread.join();
  13056. ASSERT_FALSE(svr.is_running());
  13057. });
  13058. svr.wait_until_ready();
  13059. Client cli(HOST, PORT);
  13060. cli.set_payload_max_length(0);
  13061. EXPECT_FALSE(cli.Get("/"));
  13062. }
  13063. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13064. // Stream API does, not as a plain read failure
  13065. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13066. Server svr;
  13067. svr.Get("/big", [](const Request &, Response &res) {
  13068. res.set_content(std::string(100000, 'b'), "text/plain");
  13069. });
  13070. auto port = svr.bind_to_any_port(HOST);
  13071. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13072. auto se = detail::scope_exit([&] {
  13073. svr.stop();
  13074. thread.join();
  13075. });
  13076. svr.wait_until_ready();
  13077. Client cli(HOST, port);
  13078. cli.set_payload_max_length(1000);
  13079. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13080. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13081. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13082. [](const char *, size_t) { return true; });
  13083. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13084. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13085. // Small on the wire, over the limit once decompressed
  13086. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13087. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13088. #endif
  13089. }
  13090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13091. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13092. // path.
  13093. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13094. Server svr;
  13095. const size_t LIMIT = 64 * 1024; // 64KB
  13096. svr.set_payload_max_length(LIMIT);
  13097. size_t total = 0;
  13098. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13099. const ContentReader &content_reader) {
  13100. content_reader([&](const char * /*data*/, size_t len) {
  13101. total += len;
  13102. return true;
  13103. });
  13104. res.status = 200;
  13105. res.set_content("stream_ok", "text/plain");
  13106. });
  13107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13108. auto se = detail::scope_exit([&] {
  13109. svr.stop();
  13110. thread.join();
  13111. ASSERT_FALSE(svr.is_running());
  13112. });
  13113. svr.wait_until_ready();
  13114. // Prepare 256KB raw data and gzip-compress it
  13115. std::string raw(256 * 1024, 'A');
  13116. std::string gz;
  13117. {
  13118. z_stream zs{};
  13119. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13120. Z_DEFAULT_STRATEGY);
  13121. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13122. zs.avail_in = static_cast<uInt>(raw.size());
  13123. char outbuf[4096];
  13124. int ret;
  13125. do {
  13126. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13127. zs.avail_out = sizeof(outbuf);
  13128. ret = deflate(&zs, Z_FINISH);
  13129. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13130. } while (ret != Z_STREAM_END);
  13131. deflateEnd(&zs);
  13132. }
  13133. Client cli(HOST, PORT);
  13134. cli.set_connection_timeout(std::chrono::seconds(5));
  13135. Headers headers = {{"Content-Encoding", "gzip"}};
  13136. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13137. "application/octet-stream");
  13138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13139. // Server must reject oversized decompressed payloads with 413.
  13140. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13141. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13142. EXPECT_LE(total, LIMIT);
  13143. }
  13144. #endif
  13145. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13146. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13147. // the payload must be passed through untouched instead of being rejected.
  13148. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13149. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13150. Server svr;
  13151. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13152. res.set_content(body, "image/jpeg");
  13153. res.set_header("Content-Encoding", "UTF-8");
  13154. });
  13155. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13156. res.set_content(body, "image/jpeg");
  13157. res.set_header("Content-Encoding", "identity");
  13158. });
  13159. svr.Post("/echo", [](const Request &req, Response &res) {
  13160. res.set_content(req.body, "image/jpeg");
  13161. });
  13162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13163. auto se = detail::scope_exit([&] {
  13164. svr.stop();
  13165. t.join();
  13166. ASSERT_FALSE(svr.is_running());
  13167. });
  13168. svr.wait_until_ready();
  13169. Client cli(HOST, PORT);
  13170. {
  13171. auto res = cli.Get("/image");
  13172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13173. EXPECT_EQ(StatusCode::OK_200, res->status);
  13174. EXPECT_EQ(body, res->body);
  13175. }
  13176. {
  13177. auto res = cli.Get("/identity");
  13178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13179. EXPECT_EQ(StatusCode::OK_200, res->status);
  13180. EXPECT_EQ(body, res->body);
  13181. }
  13182. {
  13183. // The same applies to a request body reaching the server.
  13184. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13185. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_EQ(StatusCode::OK_200, res->status);
  13188. EXPECT_EQ(body, res->body);
  13189. }
  13190. }
  13191. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13192. // gzip-encoded response even when the build has no zlib support.
  13193. static const char GZIPPED_HELLO_WORLD[] = {
  13194. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13195. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13196. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13197. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13198. // A content coding is a whole token, not something the field value merely
  13199. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13200. // as "fibre" look like Brotli, and turned a multi-coding value like
  13201. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13202. // it was never meant to see.
  13203. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13204. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13205. Server svr;
  13206. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13207. res.set_content(body, "image/jpeg");
  13208. res.set_header("Content-Encoding", "fibre");
  13209. });
  13210. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13211. res.set_content(body, "image/jpeg");
  13212. res.set_header("Content-Encoding", "gzip, br");
  13213. });
  13214. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13215. res.set_content(body, "image/jpeg");
  13216. res.set_header("Content-Encoding", "x-zstd-ish");
  13217. });
  13218. auto port = svr.bind_to_any_port(HOST);
  13219. thread t = thread([&]() { svr.listen_after_bind(); });
  13220. auto se = detail::scope_exit([&] {
  13221. svr.stop();
  13222. t.join();
  13223. ASSERT_FALSE(svr.is_running());
  13224. });
  13225. svr.wait_until_ready();
  13226. Client cli(HOST, port);
  13227. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13228. auto res = cli.Get(path);
  13229. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13230. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13231. // Not a coding we recognize, so the payload comes back untouched
  13232. EXPECT_EQ(body, res->body) << path;
  13233. }
  13234. }
  13235. // A content coding cpp-httplib recognizes but was not built with must be
  13236. // reported as such. Handing the still-compressed payload back to the caller
  13237. // would silently corrupt it.
  13238. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13239. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13240. Server svr;
  13241. // "image/jpeg" keeps the server from applying a content coding of its own,
  13242. // so the hand-crafted Content-Encoding below survives.
  13243. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13244. res.set_content(gzipped, "image/jpeg");
  13245. res.set_header("Content-Encoding", "gzip");
  13246. });
  13247. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13248. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13249. res.set_content(gzipped, "image/jpeg");
  13250. res.set_header("Content-Encoding", "GZIP");
  13251. });
  13252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13253. auto se = detail::scope_exit([&] {
  13254. svr.stop();
  13255. t.join();
  13256. ASSERT_FALSE(svr.is_running());
  13257. });
  13258. svr.wait_until_ready();
  13259. Client cli(HOST, PORT);
  13260. {
  13261. auto res = cli.Get("/gzipped");
  13262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13264. EXPECT_EQ("Hello World!", res->body);
  13265. #else
  13266. ASSERT_FALSE(res);
  13267. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13268. #endif
  13269. }
  13270. {
  13271. // open_stream() must behave the same way.
  13272. auto handle = cli.open_stream("GET", "/gzipped");
  13273. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13274. ASSERT_TRUE(handle.is_valid());
  13275. std::string received;
  13276. char buf[256];
  13277. ssize_t n;
  13278. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13279. received.append(buf, static_cast<size_t>(n));
  13280. }
  13281. EXPECT_EQ("Hello World!", received);
  13282. #else
  13283. EXPECT_FALSE(handle.is_valid());
  13284. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13285. #endif
  13286. }
  13287. {
  13288. // A differently-cased coding must not be mistaken for an unknown one, or
  13289. // the body would be handed back still compressed.
  13290. auto res = cli.Get("/gzipped-uppercase");
  13291. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13293. EXPECT_EQ("Hello World!", res->body);
  13294. #else
  13295. ASSERT_FALSE(res);
  13296. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13297. #endif
  13298. }
  13299. }
  13300. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13301. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13302. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13303. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13304. // body a second time and appending a second Content-Encoding field line, so
  13305. // clients that decode one coding per listed value handed back raw gzip bytes.
  13306. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13307. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13308. Server svr;
  13309. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13310. // keeps the server from applying a coding of its own.
  13311. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13312. res.set_content(gzipped, "text/plain");
  13313. res.set_header("Content-Encoding", "gzip");
  13314. });
  13315. auto port = svr.bind_to_any_port(HOST);
  13316. thread t = thread([&]() { svr.listen_after_bind(); });
  13317. auto se = detail::scope_exit([&] {
  13318. svr.stop();
  13319. t.join();
  13320. ASSERT_FALSE(svr.is_running());
  13321. });
  13322. svr.wait_until_ready();
  13323. Client cli(HOST, port);
  13324. Headers headers = {{"Accept-Encoding", "gzip"}};
  13325. auto res = cli.Get("/pre-gzipped", headers);
  13326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13327. EXPECT_EQ(StatusCode::OK_200, res->status);
  13328. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13329. EXPECT_EQ("Hello World!", res->body);
  13330. }
  13331. // set_compress(false) sends every handler response as it is, buffered or
  13332. // streamed
  13333. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13334. const std::string text(1000, 'a');
  13335. Server svr;
  13336. svr.set_compress(false);
  13337. svr.Get("/buffered", [&](const Request &, Response &res) {
  13338. res.set_content(text, "text/plain");
  13339. });
  13340. svr.Get("/streamed", [&](const Request &, Response &res) {
  13341. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13342. sink.write(text.data(), text.size());
  13343. sink.done();
  13344. return true;
  13345. });
  13346. });
  13347. auto port = svr.bind_to_any_port(HOST);
  13348. ASSERT_LT(0, port);
  13349. thread t = thread([&] { svr.listen_after_bind(); });
  13350. auto se = detail::scope_exit([&] {
  13351. svr.stop();
  13352. t.join();
  13353. ASSERT_FALSE(svr.is_running());
  13354. });
  13355. svr.wait_until_ready();
  13356. Client cli(HOST, port);
  13357. cli.set_decompress(false);
  13358. for (auto path : {"/buffered", "/streamed"}) {
  13359. SCOPED_TRACE(path);
  13360. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13362. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13363. EXPECT_EQ(text, res->body);
  13364. }
  13365. }
  13366. // A chunked provider settles its coding where the headers are written and
  13367. // reuses it at write time. Both ends of that have to hold: a handler's own
  13368. // Content-Encoding suppresses the coding, and a response without one is still
  13369. // compressed as it always was.
  13370. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13371. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13372. const std::string plain = "Hello World! Hello World! Hello World!";
  13373. Server svr;
  13374. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13375. res.set_header("Content-Encoding", "gzip");
  13376. res.set_chunked_content_provider(
  13377. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13378. sink.write(gzipped.data(), gzipped.size());
  13379. sink.done();
  13380. return true;
  13381. });
  13382. });
  13383. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13384. res.set_chunked_content_provider(
  13385. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13386. sink.write(plain.data(), plain.size());
  13387. sink.done();
  13388. return true;
  13389. });
  13390. });
  13391. auto port = svr.bind_to_any_port(HOST);
  13392. thread t = thread([&]() { svr.listen_after_bind(); });
  13393. auto se = detail::scope_exit([&] {
  13394. svr.stop();
  13395. t.join();
  13396. ASSERT_FALSE(svr.is_running());
  13397. });
  13398. svr.wait_until_ready();
  13399. Client cli(HOST, port);
  13400. Headers headers = {{"Accept-Encoding", "gzip"}};
  13401. {
  13402. auto res = cli.Get("/pre-gzipped", headers);
  13403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13404. EXPECT_EQ(StatusCode::OK_200, res->status);
  13405. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13406. EXPECT_EQ("Hello World!", res->body);
  13407. }
  13408. {
  13409. auto res = cli.Get("/negotiated", headers);
  13410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13411. EXPECT_EQ(StatusCode::OK_200, res->status);
  13412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13413. EXPECT_EQ(plain, res->body);
  13414. }
  13415. }
  13416. #endif
  13417. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13418. // the same message as the comma-joined one, so both have to be read the same
  13419. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13420. // single gzip coding, and a body the sender says was encoded twice was handed
  13421. // back after one pass, still compressed but presented as decoded.
  13422. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13423. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13424. Server svr;
  13425. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13426. res.set_content(body, "image/jpeg");
  13427. res.headers.emplace("Content-Encoding", "gzip");
  13428. res.headers.emplace("Content-Encoding", "gzip");
  13429. });
  13430. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13431. res.set_content(body, "image/jpeg");
  13432. res.set_header("Content-Encoding", "gzip, gzip");
  13433. });
  13434. auto port = svr.bind_to_any_port(HOST);
  13435. thread t = thread([&]() { svr.listen_after_bind(); });
  13436. auto se = detail::scope_exit([&] {
  13437. svr.stop();
  13438. t.join();
  13439. ASSERT_FALSE(svr.is_running());
  13440. });
  13441. svr.wait_until_ready();
  13442. Client cli(HOST, port);
  13443. // Two codings is not something cpp-httplib decodes, so both representations
  13444. // take the pass-through path rather than one of them being gunzipped once.
  13445. for (const char *path : {"/split", "/joined"}) {
  13446. auto res = cli.Get(path);
  13447. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13448. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13449. EXPECT_EQ(body, res->body) << path;
  13450. }
  13451. }
  13452. // Regression test for DoS vulnerability: a malicious server sending a response
  13453. // without Content-Length header must not cause unbounded memory consumption on
  13454. // the client side. The client should stop reading after a reasonable limit,
  13455. // similar to the server-side set_payload_max_length protection.
  13456. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13457. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13458. #ifndef _WIN32
  13459. signal(SIGPIPE, SIG_IGN);
  13460. #endif
  13461. auto server_thread = std::thread([] {
  13462. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13463. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13464. default_socket_options(srv);
  13465. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13466. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13467. sockaddr_in addr{};
  13468. addr.sin_family = AF_INET;
  13469. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13470. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13471. int opt = 1;
  13472. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13473. #ifdef _WIN32
  13474. reinterpret_cast<const char *>(&opt),
  13475. #else
  13476. &opt,
  13477. #endif
  13478. sizeof(opt));
  13479. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13480. ::listen(srv, 1);
  13481. sockaddr_in cli_addr{};
  13482. socklen_t cli_len = sizeof(cli_addr);
  13483. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13484. if (cli != INVALID_SOCKET) {
  13485. char buf[4096];
  13486. ::recv(cli, buf, sizeof(buf), 0);
  13487. // Malicious response: no Content-Length, no chunked encoding
  13488. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13489. "Connection: close\r\n"
  13490. "\r\n";
  13491. ::send(cli,
  13492. #ifdef _WIN32
  13493. static_cast<const char *>(response_header.c_str()),
  13494. static_cast<int>(response_header.size()),
  13495. #else
  13496. response_header.c_str(), response_header.size(),
  13497. #endif
  13498. 0);
  13499. // Send 10MB of data
  13500. std::string chunk(64 * 1024, 'A');
  13501. size_t total_sent = 0;
  13502. while (total_sent < MALICIOUS_DATA_SIZE) {
  13503. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13504. auto sent = ::send(cli,
  13505. #ifdef _WIN32
  13506. static_cast<const char *>(chunk.c_str()),
  13507. static_cast<int>(to_send),
  13508. #else
  13509. chunk.c_str(), to_send,
  13510. #endif
  13511. 0);
  13512. if (sent <= 0) break;
  13513. total_sent += static_cast<size_t>(sent);
  13514. }
  13515. detail::close_socket(cli);
  13516. }
  13517. detail::close_socket(srv);
  13518. });
  13519. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13520. size_t total_read = 0;
  13521. {
  13522. Client cli("127.0.0.1", PORT + 2);
  13523. cli.set_read_timeout(5, 0);
  13524. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13525. auto stream = cli.open_stream("GET", "/malicious");
  13526. ASSERT_TRUE(stream.is_valid());
  13527. char buffer[64 * 1024];
  13528. ssize_t n;
  13529. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13530. total_read += static_cast<size_t>(n);
  13531. }
  13532. } // StreamHandle and Client destroyed here, closing the socket
  13533. server_thread.join();
  13534. // With set_payload_max_length, the client must stop reading before consuming
  13535. // all 10MB. The read loop should be cut off at or near the configured limit.
  13536. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13537. << "Client read " << total_read << " bytes, exceeding the configured "
  13538. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13539. }
  13540. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13541. // the entire response body without truncation.
  13542. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13543. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13544. #ifndef _WIN32
  13545. signal(SIGPIPE, SIG_IGN);
  13546. #endif
  13547. auto server_thread = std::thread([] {
  13548. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13549. default_socket_options(srv);
  13550. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13551. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13552. sockaddr_in addr{};
  13553. addr.sin_family = AF_INET;
  13554. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13555. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13556. int opt = 1;
  13557. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13558. #ifdef _WIN32
  13559. reinterpret_cast<const char *>(&opt),
  13560. #else
  13561. &opt,
  13562. #endif
  13563. sizeof(opt));
  13564. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13565. ::listen(srv, 1);
  13566. sockaddr_in cli_addr{};
  13567. socklen_t cli_len = sizeof(cli_addr);
  13568. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13569. if (cli != INVALID_SOCKET) {
  13570. char buf[4096];
  13571. ::recv(cli, buf, sizeof(buf), 0);
  13572. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13573. "Connection: close\r\n"
  13574. "\r\n";
  13575. ::send(cli,
  13576. #ifdef _WIN32
  13577. static_cast<const char *>(response_header.c_str()),
  13578. static_cast<int>(response_header.size()),
  13579. #else
  13580. response_header.c_str(), response_header.size(),
  13581. #endif
  13582. 0);
  13583. std::string chunk(64 * 1024, 'A');
  13584. size_t total_sent = 0;
  13585. while (total_sent < DATA_SIZE) {
  13586. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13587. auto sent = ::send(cli,
  13588. #ifdef _WIN32
  13589. static_cast<const char *>(chunk.c_str()),
  13590. static_cast<int>(to_send),
  13591. #else
  13592. chunk.c_str(), to_send,
  13593. #endif
  13594. 0);
  13595. if (sent <= 0) break;
  13596. total_sent += static_cast<size_t>(sent);
  13597. }
  13598. #ifdef _WIN32
  13599. ::shutdown(cli, SD_SEND);
  13600. #else
  13601. ::shutdown(cli, SHUT_WR);
  13602. #endif
  13603. // Drain until the client closes its end, ensuring all data is delivered
  13604. char drain[1024];
  13605. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13606. detail::close_socket(cli);
  13607. }
  13608. detail::close_socket(srv);
  13609. });
  13610. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13611. size_t total_read = 0;
  13612. {
  13613. Client cli("127.0.0.1", PORT + 2);
  13614. cli.set_read_timeout(5, 0);
  13615. cli.set_payload_max_length(0); // 0 means no limit
  13616. auto stream = cli.open_stream("GET", "/data");
  13617. ASSERT_TRUE(stream.is_valid());
  13618. char buffer[64 * 1024];
  13619. ssize_t n;
  13620. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13621. total_read += static_cast<size_t>(n);
  13622. }
  13623. }
  13624. server_thread.join();
  13625. EXPECT_EQ(total_read, DATA_SIZE)
  13626. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13627. << " bytes without truncation, but only read " << total_read << " bytes.";
  13628. }
  13629. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13630. // enormous Content-Length must not cause the client to pre-allocate a huge
  13631. // response body buffer. The reservation is capped at payload_max_length_, and
  13632. // the read itself fails when the body exceeds the limit.
  13633. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13634. #ifndef _WIN32
  13635. signal(SIGPIPE, SIG_IGN);
  13636. #endif
  13637. auto server_thread = std::thread([] {
  13638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13639. default_socket_options(srv);
  13640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13642. sockaddr_in addr{};
  13643. addr.sin_family = AF_INET;
  13644. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13645. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13646. int opt = 1;
  13647. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13648. #ifdef _WIN32
  13649. reinterpret_cast<const char *>(&opt),
  13650. #else
  13651. &opt,
  13652. #endif
  13653. sizeof(opt));
  13654. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13655. ::listen(srv, 1);
  13656. sockaddr_in cli_addr{};
  13657. socklen_t cli_len = sizeof(cli_addr);
  13658. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13659. if (cli != INVALID_SOCKET) {
  13660. char buf[4096];
  13661. ::recv(cli, buf, sizeof(buf), 0);
  13662. // Malicious response: claim a 20GB body but send only a tiny payload.
  13663. std::string response = "HTTP/1.1 200 OK\r\n"
  13664. "Content-Length: 20000000000\r\n"
  13665. "\r\n"
  13666. "abc";
  13667. ::send(cli,
  13668. #ifdef _WIN32
  13669. static_cast<const char *>(response.c_str()),
  13670. static_cast<int>(response.size()),
  13671. #else
  13672. response.c_str(), response.size(),
  13673. #endif
  13674. 0);
  13675. detail::close_socket(cli);
  13676. }
  13677. detail::close_socket(srv);
  13678. });
  13679. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13680. {
  13681. Client cli("127.0.0.1", PORT + 2);
  13682. cli.set_read_timeout(5, 0);
  13683. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13684. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13685. // (server claims more bytes than payload_max_length permits), but it must
  13686. // not exhaust memory before getting there.
  13687. auto res = cli.Get("/malicious");
  13688. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13689. }
  13690. server_thread.join();
  13691. }
  13692. // Verify that content_receiver bypasses the default payload_max_length,
  13693. // allowing streaming downloads larger than 100MB without requiring an explicit
  13694. // set_payload_max_length call.
  13695. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13696. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13697. #ifndef _WIN32
  13698. signal(SIGPIPE, SIG_IGN);
  13699. #endif
  13700. auto server_thread = std::thread([] {
  13701. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13702. default_socket_options(srv);
  13703. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13704. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13705. sockaddr_in addr{};
  13706. addr.sin_family = AF_INET;
  13707. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13708. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13709. int opt = 1;
  13710. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13711. #ifdef _WIN32
  13712. reinterpret_cast<const char *>(&opt),
  13713. #else
  13714. &opt,
  13715. #endif
  13716. sizeof(opt));
  13717. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13718. ::listen(srv, 1);
  13719. sockaddr_in cli_addr{};
  13720. socklen_t cli_len = sizeof(cli_addr);
  13721. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13722. if (cli != INVALID_SOCKET) {
  13723. char buf[4096];
  13724. ::recv(cli, buf, sizeof(buf), 0);
  13725. // Response with Content-Length larger than default 100MB limit
  13726. auto content_length = std::to_string(DATA_SIZE);
  13727. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13728. "Content-Length: " +
  13729. content_length +
  13730. "\r\n"
  13731. "Connection: close\r\n"
  13732. "\r\n";
  13733. ::send(cli,
  13734. #ifdef _WIN32
  13735. static_cast<const char *>(response_header.c_str()),
  13736. static_cast<int>(response_header.size()),
  13737. #else
  13738. response_header.c_str(), response_header.size(),
  13739. #endif
  13740. 0);
  13741. std::string chunk(64 * 1024, 'A');
  13742. size_t total_sent = 0;
  13743. while (total_sent < DATA_SIZE) {
  13744. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13745. auto sent = ::send(cli,
  13746. #ifdef _WIN32
  13747. static_cast<const char *>(chunk.c_str()),
  13748. static_cast<int>(to_send),
  13749. #else
  13750. chunk.c_str(), to_send,
  13751. #endif
  13752. 0);
  13753. if (sent <= 0) break;
  13754. total_sent += static_cast<size_t>(sent);
  13755. }
  13756. detail::close_socket(cli);
  13757. }
  13758. detail::close_socket(srv);
  13759. });
  13760. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13761. size_t total_received = 0;
  13762. {
  13763. Client cli("127.0.0.1", PORT + 2);
  13764. cli.set_read_timeout(10, 0);
  13765. // Do NOT call set_payload_max_length — use the default 100MB limit
  13766. auto res =
  13767. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13768. total_received += data_length;
  13769. return true;
  13770. });
  13771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13772. EXPECT_EQ(StatusCode::OK_200, res->status);
  13773. }
  13774. server_thread.join();
  13775. EXPECT_EQ(total_received, DATA_SIZE)
  13776. << "With content_receiver, the client should read all " << DATA_SIZE
  13777. << " bytes despite the default 100MB payload_max_length, but only read "
  13778. << total_received << " bytes.";
  13779. }
  13780. // Verify that an explicit set_payload_max_length smaller than the response is
  13781. // enforced even when a content_receiver is used.
  13782. TEST(ClientVulnerabilityTest,
  13783. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13784. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13785. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13786. #ifndef _WIN32
  13787. signal(SIGPIPE, SIG_IGN);
  13788. #endif
  13789. auto server_thread = std::thread([] {
  13790. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13791. default_socket_options(srv);
  13792. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13793. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13794. sockaddr_in addr{};
  13795. addr.sin_family = AF_INET;
  13796. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13797. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13798. int opt = 1;
  13799. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13800. #ifdef _WIN32
  13801. reinterpret_cast<const char *>(&opt),
  13802. #else
  13803. &opt,
  13804. #endif
  13805. sizeof(opt));
  13806. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13807. ::listen(srv, 1);
  13808. sockaddr_in cli_addr{};
  13809. socklen_t cli_len = sizeof(cli_addr);
  13810. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13811. if (cli != INVALID_SOCKET) {
  13812. char buf[4096];
  13813. ::recv(cli, buf, sizeof(buf), 0);
  13814. auto content_length = std::to_string(DATA_SIZE);
  13815. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13816. "Content-Length: " +
  13817. content_length +
  13818. "\r\n"
  13819. "Connection: close\r\n"
  13820. "\r\n";
  13821. ::send(cli,
  13822. #ifdef _WIN32
  13823. static_cast<const char *>(response_header.c_str()),
  13824. static_cast<int>(response_header.size()),
  13825. #else
  13826. response_header.c_str(), response_header.size(),
  13827. #endif
  13828. 0);
  13829. std::string chunk(64 * 1024, 'A');
  13830. size_t total_sent = 0;
  13831. while (total_sent < DATA_SIZE) {
  13832. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13833. auto sent = ::send(cli,
  13834. #ifdef _WIN32
  13835. static_cast<const char *>(chunk.c_str()),
  13836. static_cast<int>(to_send),
  13837. #else
  13838. chunk.c_str(), to_send,
  13839. #endif
  13840. 0);
  13841. if (sent <= 0) break;
  13842. total_sent += static_cast<size_t>(sent);
  13843. }
  13844. detail::close_socket(cli);
  13845. }
  13846. detail::close_socket(srv);
  13847. });
  13848. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13849. size_t total_received = 0;
  13850. {
  13851. Client cli("127.0.0.1", PORT + 2);
  13852. cli.set_read_timeout(10, 0);
  13853. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13854. auto res =
  13855. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13856. total_received += data_length;
  13857. return true;
  13858. });
  13859. // Should fail because 200MB exceeds the explicit 150MB limit
  13860. EXPECT_FALSE(res);
  13861. }
  13862. server_thread.join();
  13863. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13864. << "Client with content_receiver should respect the explicit "
  13865. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13866. << total_received << " bytes.";
  13867. }
  13868. // Verify that an explicit set_payload_max_length larger than the response
  13869. // allows the content_receiver to read all data successfully.
  13870. TEST(ClientVulnerabilityTest,
  13871. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13872. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13873. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13874. #ifndef _WIN32
  13875. signal(SIGPIPE, SIG_IGN);
  13876. #endif
  13877. auto server_thread = std::thread([] {
  13878. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13879. default_socket_options(srv);
  13880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13882. sockaddr_in addr{};
  13883. addr.sin_family = AF_INET;
  13884. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13885. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13886. int opt = 1;
  13887. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13888. #ifdef _WIN32
  13889. reinterpret_cast<const char *>(&opt),
  13890. #else
  13891. &opt,
  13892. #endif
  13893. sizeof(opt));
  13894. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13895. ::listen(srv, 1);
  13896. sockaddr_in cli_addr{};
  13897. socklen_t cli_len = sizeof(cli_addr);
  13898. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13899. if (cli != INVALID_SOCKET) {
  13900. char buf[4096];
  13901. ::recv(cli, buf, sizeof(buf), 0);
  13902. auto content_length = std::to_string(DATA_SIZE);
  13903. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13904. "Content-Length: " +
  13905. content_length +
  13906. "\r\n"
  13907. "Connection: close\r\n"
  13908. "\r\n";
  13909. ::send(cli,
  13910. #ifdef _WIN32
  13911. static_cast<const char *>(response_header.c_str()),
  13912. static_cast<int>(response_header.size()),
  13913. #else
  13914. response_header.c_str(), response_header.size(),
  13915. #endif
  13916. 0);
  13917. std::string chunk(64 * 1024, 'A');
  13918. size_t total_sent = 0;
  13919. while (total_sent < DATA_SIZE) {
  13920. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13921. auto sent = ::send(cli,
  13922. #ifdef _WIN32
  13923. static_cast<const char *>(chunk.c_str()),
  13924. static_cast<int>(to_send),
  13925. #else
  13926. chunk.c_str(), to_send,
  13927. #endif
  13928. 0);
  13929. if (sent <= 0) break;
  13930. total_sent += static_cast<size_t>(sent);
  13931. }
  13932. #ifdef _WIN32
  13933. ::shutdown(cli, SD_SEND);
  13934. #else
  13935. ::shutdown(cli, SHUT_WR);
  13936. #endif
  13937. char drain[1024];
  13938. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13939. detail::close_socket(cli);
  13940. }
  13941. detail::close_socket(srv);
  13942. });
  13943. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13944. size_t total_received = 0;
  13945. {
  13946. Client cli("127.0.0.1", PORT + 2);
  13947. cli.set_read_timeout(10, 0);
  13948. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13949. auto res =
  13950. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13951. total_received += data_length;
  13952. return true;
  13953. });
  13954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13955. EXPECT_EQ(StatusCode::OK_200, res->status);
  13956. }
  13957. server_thread.join();
  13958. EXPECT_EQ(total_received, DATA_SIZE)
  13959. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13960. << " bytes (larger than " << DATA_SIZE
  13961. << " bytes response), content_receiver should read all data, but only "
  13962. "read "
  13963. << total_received << " bytes.";
  13964. }
  13965. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13966. // Regression test for "zip bomb" attack on the client side: a malicious server
  13967. // sends a small gzip-compressed response that decompresses to a huge payload.
  13968. // The client must enforce payload_max_length on the decompressed size.
  13969. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13970. constexpr size_t DECOMPRESSED_SIZE =
  13971. 10 * 1024 * 1024; // 10MB after decompression
  13972. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13973. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13974. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13975. std::string compressed;
  13976. {
  13977. httplib::detail::gzip_compressor compressor;
  13978. bool ok =
  13979. compressor.compress(uncompressed.data(), uncompressed.size(),
  13980. /*last=*/true, [&](const char *buf, size_t len) {
  13981. compressed.append(buf, len);
  13982. return true;
  13983. });
  13984. ASSERT_TRUE(ok);
  13985. }
  13986. // Sanity: compressed data should be much smaller than the decompressed size
  13987. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13988. #ifndef _WIN32
  13989. signal(SIGPIPE, SIG_IGN);
  13990. #endif
  13991. // Set up the listening socket in the main thread so the server is guaranteed
  13992. // to be ready before the client connects (eliminates race condition).
  13993. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13994. default_socket_options(srv);
  13995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13997. sockaddr_in addr{};
  13998. addr.sin_family = AF_INET;
  13999. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14000. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14001. int opt = 1;
  14002. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14003. #ifdef _WIN32
  14004. reinterpret_cast<const char *>(&opt),
  14005. #else
  14006. &opt,
  14007. #endif
  14008. sizeof(opt));
  14009. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14010. ASSERT_EQ(0, ::listen(srv, 1));
  14011. auto server_thread = std::thread([&compressed, srv] {
  14012. sockaddr_in cli_addr{};
  14013. socklen_t cli_len = sizeof(cli_addr);
  14014. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14015. if (cli != INVALID_SOCKET) {
  14016. // Read the full HTTP request (until \r\n\r\n)
  14017. char buf[4096];
  14018. size_t total = 0;
  14019. while (total < sizeof(buf)) {
  14020. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14021. if (n <= 0) break;
  14022. total += static_cast<size_t>(n);
  14023. // Check for end of headers
  14024. if (total >= 4) {
  14025. std::string req(buf, total);
  14026. if (req.find("\r\n\r\n") != std::string::npos) break;
  14027. }
  14028. }
  14029. // Malicious response: gzip-compressed body, no Content-Length
  14030. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14031. "Content-Encoding: gzip\r\n"
  14032. "Connection: close\r\n"
  14033. "\r\n";
  14034. ::send(cli,
  14035. #ifdef _WIN32
  14036. static_cast<const char *>(response_header.c_str()),
  14037. static_cast<int>(response_header.size()),
  14038. #else
  14039. response_header.c_str(), response_header.size(),
  14040. #endif
  14041. 0);
  14042. // Send the compressed payload (small on the wire, huge when decompressed)
  14043. size_t total_sent = 0;
  14044. while (total_sent < compressed.size()) {
  14045. auto to_send = std::min(compressed.size() - total_sent,
  14046. static_cast<size_t>(64 * 1024));
  14047. auto sent =
  14048. ::send(cli,
  14049. #ifdef _WIN32
  14050. static_cast<const char *>(compressed.c_str() + total_sent),
  14051. static_cast<int>(to_send),
  14052. #else
  14053. compressed.c_str() + total_sent, to_send,
  14054. #endif
  14055. 0);
  14056. if (sent <= 0) break;
  14057. total_sent += static_cast<size_t>(sent);
  14058. }
  14059. detail::close_socket(cli);
  14060. }
  14061. });
  14062. auto se = detail::scope_exit([&] {
  14063. detail::close_socket(srv);
  14064. server_thread.join();
  14065. });
  14066. size_t total_decompressed = 0;
  14067. {
  14068. Client cli("127.0.0.1", PORT + 3);
  14069. cli.set_read_timeout(5, 0);
  14070. cli.set_decompress(true);
  14071. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14072. auto stream = cli.open_stream("GET", "/zipbomb");
  14073. ASSERT_TRUE(stream.is_valid());
  14074. char buffer[64 * 1024];
  14075. ssize_t n;
  14076. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14077. total_decompressed += static_cast<size_t>(n);
  14078. }
  14079. }
  14080. // The decompressed size must be capped by payload_max_length. Without
  14081. // protection, the client would decompress the full 10MB from a tiny
  14082. // compressed payload, enabling a zip bomb DoS attack.
  14083. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14084. << "Client decompressed " << total_decompressed
  14085. << " bytes from a gzip response. The decompressed size should be "
  14086. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14087. }
  14088. #endif
  14089. TEST(HostAndPortPropertiesTest, NoSSL) {
  14090. httplib::Client cli("www.google.com", 1234);
  14091. ASSERT_EQ("www.google.com", cli.host());
  14092. ASSERT_EQ(1234, cli.port());
  14093. }
  14094. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14095. httplib::Client cli("www.google.com:1234");
  14096. ASSERT_EQ("www.google.com", cli.host());
  14097. ASSERT_EQ(1234, cli.port());
  14098. }
  14099. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14100. // Port number that overflows int — should not crash, client becomes invalid
  14101. httplib::Client cli("http://www.google.com:99999999999999999999");
  14102. ASSERT_FALSE(cli.is_valid());
  14103. }
  14104. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14105. // Port 99999 exceeds valid range (1-65535) — should not crash
  14106. httplib::Client cli("http://www.google.com:99999");
  14107. ASSERT_FALSE(cli.is_valid());
  14108. auto res = cli.Get("/");
  14109. EXPECT_FALSE(res);
  14110. EXPECT_EQ(Error::Connection, res.error());
  14111. }
  14112. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14113. httplib::Client cli("http://user:pass@localhost:1234");
  14114. ASSERT_FALSE(cli.is_valid());
  14115. EXPECT_FALSE(cli.Get("/"));
  14116. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14117. }
  14118. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14119. httplib::Client cli("http://www.google.com:80abc");
  14120. ASSERT_FALSE(cli.is_valid());
  14121. }
  14122. #ifdef CPPHTTPLIB_SSL_ENABLED
  14123. TEST(HostAndPortPropertiesTest, SSL) {
  14124. httplib::SSLClient cli("www.google.com");
  14125. ASSERT_EQ("www.google.com", cli.host());
  14126. ASSERT_EQ(443, cli.port());
  14127. }
  14128. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14129. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14130. std::string cert;
  14131. read_file(CA_CERT_FILE, cert);
  14132. httplib::SSLClient httplib_client("www.google.com");
  14133. // Load CA store first time
  14134. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14135. // Load CA store second time (update)
  14136. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14137. // Verify client is still valid and can make connections
  14138. httplib_client.enable_server_certificate_verification(true);
  14139. auto res = httplib_client.Get("/");
  14140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14141. // Google may return 200 or 301 depending on various factors
  14142. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14143. res->status == StatusCode::MovedPermanently_301);
  14144. }
  14145. TEST(SSLClientTest, ServerNameIndication_Online) {
  14146. auto host = "httpbingo.org";
  14147. auto path = std::string{"/get"};
  14148. SSLClient cli(host, 443);
  14149. auto res = cli.Get(path);
  14150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14151. ASSERT_EQ(StatusCode::OK_200, res->status);
  14152. }
  14153. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14154. // Use a site that will cause SSL verification failure due to self-signed cert
  14155. SSLClient cli("self-signed.badssl.com", 443);
  14156. cli.enable_server_certificate_verification(true);
  14157. auto res = cli.Get("/");
  14158. ASSERT_TRUE(!res);
  14159. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14160. // Verify backend error is captured for SSLServerVerification
  14161. // This occurs when certificate verification fails
  14162. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14163. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14164. EXPECT_NE(0UL, res.ssl_backend_error());
  14165. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14166. res.ssl_error());
  14167. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14168. #if !defined(_WIN32) || \
  14169. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14170. // On non-Windows or when Windows Schannel is disabled, the error comes
  14171. // from OpenSSL's verification
  14172. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14173. res.ssl_backend_error());
  14174. #endif
  14175. #endif
  14176. }
  14177. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14178. // Use a site where hostname doesn't match the certificate
  14179. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14180. SSLClient cli("wrong.host.badssl.com", 443);
  14181. cli.enable_server_certificate_verification(true);
  14182. cli.enable_server_hostname_verification(true);
  14183. auto res = cli.Get("/");
  14184. ASSERT_TRUE(!res);
  14185. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14186. // Verify backend error is captured for hostname verification failure
  14187. EXPECT_NE(0UL, res.ssl_backend_error());
  14188. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14189. res.ssl_error());
  14190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14191. #if !defined(_WIN32) || \
  14192. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14193. // On non-Windows or when Windows Schannel is disabled, the error comes
  14194. // from OpenSSL's hostname verification
  14195. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14196. res.ssl_backend_error());
  14197. #endif
  14198. #endif
  14199. }
  14200. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14201. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14202. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14203. SSLClient cli("www.google.com", 443);
  14204. cli.enable_server_certificate_verification(true);
  14205. auto res = cli.Get("/");
  14206. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14207. }
  14208. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14209. SSLClient cli("www.google.com", 443);
  14210. cli.enable_server_certificate_verification(true);
  14211. cli.enable_windows_certificate_verification(false);
  14212. auto res = cli.Get("/");
  14213. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14214. }
  14215. // The server sends an intermediate cross-signed by a root Windows trusts,
  14216. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14217. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14218. SSLClient cli("accounts.spotify.com", 443);
  14219. auto res = cli.Get("/");
  14220. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14221. << " ssl_backend_error=" << res.ssl_backend_error();
  14222. }
  14223. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14224. // policy status, which no backend reports for a self-signed certificate.
  14225. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14226. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14227. ASSERT_TRUE(svr.is_valid());
  14228. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14229. auto se = detail::scope_exit([&] {
  14230. svr.stop();
  14231. t.join();
  14232. ASSERT_FALSE(svr.is_running());
  14233. });
  14234. svr.wait_until_ready();
  14235. SSLClient cli("127.0.0.1", PORT);
  14236. cli.set_connection_timeout(30);
  14237. auto res = cli.Get("/");
  14238. ASSERT_FALSE(res);
  14239. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14240. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14241. }
  14242. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14243. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14244. ASSERT_TRUE(svr.is_valid());
  14245. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14246. auto se = detail::scope_exit([&] {
  14247. svr.stop();
  14248. t.join();
  14249. ASSERT_FALSE(svr.is_running());
  14250. });
  14251. svr.wait_until_ready();
  14252. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14253. {
  14254. ws::WebSocketClient client(url);
  14255. auto res = client.connect();
  14256. ASSERT_FALSE(res);
  14257. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14258. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14259. res.ssl_backend_error());
  14260. }
  14261. {
  14262. ws::WebSocketClient client(url);
  14263. client.enable_windows_certificate_verification(false);
  14264. auto res = client.connect();
  14265. ASSERT_FALSE(res);
  14266. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14267. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14268. res.ssl_backend_error());
  14269. }
  14270. }
  14271. #endif
  14272. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14273. Client cli("https://google.com");
  14274. auto res = cli.Get("/");
  14275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14276. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14277. }
  14278. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14279. SSLClient cli("google.com");
  14280. cli.set_ca_cert_path(CA_CERT_FILE);
  14281. auto res = cli.Get("/");
  14282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14283. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14284. }
  14285. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14286. SSLClient cli("google.com");
  14287. cli.enable_server_certificate_verification(true);
  14288. cli.set_ca_cert_path("hello");
  14289. auto res = cli.Get("/");
  14290. ASSERT_TRUE(!res);
  14291. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14292. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14293. // should be set
  14294. EXPECT_EQ(0, res.ssl_error());
  14295. // Verify backend error is captured for SSLLoadingCerts
  14296. // This error occurs when loading CA certificates fails
  14297. EXPECT_NE(0UL, res.ssl_backend_error());
  14298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14299. // OpenSSL specific error codes:
  14300. // > openssl errstr 0x80000002
  14301. // error:80000002:system library::No such file or directory
  14302. // > openssl errstr 0xA000126
  14303. // error:0A000126:SSL routines::unexpected eof while reading
  14304. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14305. res.ssl_backend_error() == 0xA000126);
  14306. #endif
  14307. }
  14308. TEST(SSLClientTest, ServerCertificateVerification4) {
  14309. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14310. ASSERT_TRUE(svr.is_valid());
  14311. svr.Get("/test", [&](const Request &, Response &res) {
  14312. res.set_content("test", "text/plain");
  14313. svr.stop();
  14314. ASSERT_TRUE(true);
  14315. });
  14316. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14317. auto se = detail::scope_exit([&] {
  14318. t.join();
  14319. ASSERT_FALSE(svr.is_running());
  14320. });
  14321. svr.wait_until_ready();
  14322. SSLClient cli("127.0.0.1", PORT);
  14323. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14324. cli.enable_server_certificate_verification(true);
  14325. cli.set_connection_timeout(30);
  14326. auto res = cli.Get("/test");
  14327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14328. ASSERT_EQ(StatusCode::OK_200, res->status);
  14329. }
  14330. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14331. std::string cert;
  14332. read_file(CA_CERT_FILE, cert);
  14333. SSLClient cli("google.com");
  14334. cli.load_ca_cert_store(cert.data(), cert.size());
  14335. const auto res = cli.Get("/");
  14336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14337. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14338. }
  14339. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14340. // clang-format off
  14341. static constexpr char cert[] =
  14342. "GlobalSign Root CA\n"
  14343. "==================\n"
  14344. "-----BEGIN CERTIFICATE-----\n"
  14345. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14346. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14347. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14348. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14349. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14350. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14351. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14352. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14353. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14354. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14355. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14356. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14357. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14358. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14359. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14360. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14361. "-----END CERTIFICATE-----\n";
  14362. // clang-format on
  14363. SSLClient cli("google.com");
  14364. cli.load_ca_cert_store(cert, sizeof(cert));
  14365. const auto res = cli.Get("/");
  14366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14367. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14368. }
  14369. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14370. SSLClient cli("www.youtube.com");
  14371. cli.set_ca_cert_path(CA_CERT_FILE);
  14372. cli.enable_server_certificate_verification(true);
  14373. cli.set_follow_location(true);
  14374. auto res = cli.Get("/");
  14375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14376. ASSERT_EQ(StatusCode::OK_200, res->status);
  14377. }
  14378. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14379. SSLClient cli("wWw.YouTube.Com");
  14380. cli.set_ca_cert_path(CA_CERT_FILE);
  14381. cli.enable_server_certificate_verification(true);
  14382. cli.enable_server_hostname_verification(true);
  14383. cli.set_follow_location(true);
  14384. auto res = cli.Get("/");
  14385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14386. ASSERT_EQ(StatusCode::OK_200, res->status);
  14387. }
  14388. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14389. SSLClient cli("gOoGlE.COm");
  14390. cli.enable_server_certificate_verification(true);
  14391. cli.enable_server_hostname_verification(true);
  14392. cli.set_follow_location(true);
  14393. auto res = cli.Get("/");
  14394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14395. ASSERT_EQ(StatusCode::OK_200, res->status);
  14396. }
  14397. TEST(SSLClientTest, Issue2004_Online) {
  14398. Client client("https://google.com");
  14399. client.set_follow_location(true);
  14400. auto res = client.Get("/");
  14401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14402. ASSERT_EQ(StatusCode::OK_200, res->status);
  14403. auto body = res->body;
  14404. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14405. }
  14406. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14407. // Create SSLClient with invalid cert/key to make is_valid() return false
  14408. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14409. "nonexistent_key.pem");
  14410. // is_valid() should be false due to cert loading failure
  14411. ASSERT_FALSE(cli.is_valid());
  14412. auto res = cli.Get("/");
  14413. ASSERT_FALSE(res);
  14414. EXPECT_EQ(Error::SSLConnection, res.error());
  14415. }
  14416. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14417. // Test for Issue #2251: SSL error not properly reported when client cert
  14418. // and key paths are swapped or mismatched
  14419. // This simulates the scenario where user accidentally swaps the cert and key
  14420. // files
  14421. // Using client cert file as private key and vice versa (completely wrong)
  14422. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14423. // Should fail validation due to cert/key mismatch
  14424. ASSERT_FALSE(cli.is_valid());
  14425. // Attempt to make a request should fail with proper error
  14426. auto res = cli.Get("/");
  14427. ASSERT_FALSE(res);
  14428. EXPECT_EQ(Error::SSLConnection, res.error());
  14429. // SSL error should be recorded in the Result object (this is the key fix for
  14430. // Issue #2251)
  14431. auto backend_error = res.ssl_backend_error();
  14432. EXPECT_NE(0u, backend_error);
  14433. }
  14434. // Tests cert/key mismatch detection at the TLS context level
  14435. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14436. // Test that using mismatched cert/key causes connection failure.
  14437. // We verify this at the SSLClient level rather than through internal
  14438. // TLS API functions.
  14439. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14440. cli.enable_server_certificate_verification(false);
  14441. cli.set_connection_timeout(2);
  14442. // The mismatch should cause a connection or handshake error
  14443. auto res = cli.Get("/test");
  14444. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14445. // Either way, the request should fail
  14446. EXPECT_FALSE(res);
  14447. }
  14448. #endif
  14449. #if 0
  14450. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14451. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14452. ASSERT_TRUE(cli != nullptr);
  14453. cli->set_address_family(AF_INET6);
  14454. cli->set_interface("en0");
  14455. auto res = cli->Get("/get");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::OK_200, res->status);
  14458. }
  14459. #endif
  14460. // Client certificate tests - work with all TLS backends
  14461. #ifdef CPPHTTPLIB_SSL_ENABLED
  14462. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14463. void ClientCertPresent(
  14464. const std::string &client_cert_file,
  14465. const std::string &client_private_key_file,
  14466. const std::string &client_encrypted_private_key_pass = std::string(),
  14467. const ClientCertServerSetup &setup = nullptr) {
  14468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14469. ASSERT_TRUE(svr.is_valid());
  14470. if (setup) { setup(svr); }
  14471. svr.Get("/test", [&](const Request &req, Response &res) {
  14472. res.set_content("test", "text/plain");
  14473. auto cert = req.peer_cert();
  14474. ASSERT_TRUE(static_cast<bool>(cert));
  14475. std::string common_name = cert.subject_cn();
  14476. EXPECT_EQ("Common Name", common_name);
  14477. });
  14478. auto port = svr.bind_to_any_port(HOST);
  14479. ASSERT_LT(0, port);
  14480. thread t = thread([&]() { svr.listen_after_bind(); });
  14481. auto se = detail::scope_exit([&] {
  14482. svr.stop();
  14483. t.join();
  14484. ASSERT_FALSE(svr.is_running());
  14485. });
  14486. svr.wait_until_ready();
  14487. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14488. client_encrypted_private_key_pass);
  14489. cli.enable_server_certificate_verification(false);
  14490. cli.set_connection_timeout(30);
  14491. auto res = cli.Get("/test");
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. ASSERT_EQ(StatusCode::OK_200, res->status);
  14494. }
  14495. TEST(SSLClientServerTest, ClientCertPresent) {
  14496. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14497. }
  14498. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14499. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14500. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14501. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14502. }
  14503. // Expects svr, which must require client certificates, to reject a client
  14504. // that has none
  14505. void RejectsClientWithoutCert(SSLServer &svr) {
  14506. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14507. auto port = svr.bind_to_any_port(HOST);
  14508. ASSERT_LT(0, port);
  14509. thread t = thread([&]() { svr.listen_after_bind(); });
  14510. auto se = detail::scope_exit([&] {
  14511. svr.stop();
  14512. t.join();
  14513. ASSERT_FALSE(svr.is_running());
  14514. });
  14515. svr.wait_until_ready();
  14516. SSLClient cli(HOST, port);
  14517. cli.set_connection_timeout(30);
  14518. // Skip the server certificate check, so that the request fails because the
  14519. // client certificate is missing rather than because cert.pem is not trusted
  14520. cli.enable_server_certificate_verification(false);
  14521. auto res = cli.Get("/test");
  14522. ASSERT_FALSE(res);
  14523. // The server rejects the client during the handshake, or on TLS 1.3 right
  14524. // after it, which the client notices on its first write or read
  14525. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14526. res.error() == Error::Write || res.error() == Error::Read)
  14527. << to_string(res.error());
  14528. if (res.error() == Error::SSLConnection) {
  14529. EXPECT_NE(0UL, res.ssl_backend_error());
  14530. }
  14531. // A rejection noticed on the write keeps the TLS error the write hit
  14532. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14533. }
  14534. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14536. ASSERT_TRUE(svr.is_valid());
  14537. if (setup) { setup(svr); }
  14538. RejectsClientWithoutCert(svr);
  14539. }
  14540. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14541. // A server that requires client certificates must keep requiring them after
  14542. // setup changes it, and keep accepting a client that has one
  14543. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14544. ClientCertMissing(setup);
  14545. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14546. setup);
  14547. }
  14548. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14549. ClientCertStillRequired([](SSLServer &svr) {
  14550. ASSERT_TRUE(tls::set_verify_callback(
  14551. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14552. });
  14553. }
  14554. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14555. ClientCertStillRequired([](SSLServer &svr) {
  14556. ASSERT_TRUE(tls::set_verify_callback(
  14557. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14558. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14559. });
  14560. }
  14561. // The client verifies the server certificate during the handshake, so a
  14562. // server that fails the check never gets the client certificate, even when a
  14563. // verifier of the client's own accepts it
  14564. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14565. struct Case {
  14566. const char *trusted_ca;
  14567. const char *host;
  14568. Error error;
  14569. };
  14570. // cert2.pem names localhost: the first client does not trust it, and the
  14571. // second trusts it but asks for another name
  14572. for (const auto &c :
  14573. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14574. Case{SERVER_CERT2_FILE, "example.com",
  14575. Error::SSLServerHostnameVerification}}) {
  14576. for (auto with_verifier : {false, true}) {
  14577. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14578. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14579. CLIENT_CA_CERT_FILE);
  14580. ASSERT_TRUE(svr.is_valid());
  14581. std::atomic<bool> got_client_cert{false};
  14582. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14583. [&](const tls::VerifyContext &) {
  14584. got_client_cert = true;
  14585. return true;
  14586. }));
  14587. auto port = svr.bind_to_any_port("127.0.0.1");
  14588. ASSERT_LT(0, port);
  14589. thread t = thread([&] { svr.listen_after_bind(); });
  14590. svr.wait_until_ready();
  14591. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14592. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14593. cli.set_ca_cert_path(c.trusted_ca);
  14594. if (with_verifier) {
  14595. cli.set_server_certificate_verifier(
  14596. [](const tls::VerifyContext &) { return true; });
  14597. }
  14598. auto res = cli.Get("/");
  14599. EXPECT_FALSE(res);
  14600. EXPECT_EQ(c.error, res.error());
  14601. svr.stop();
  14602. t.join();
  14603. EXPECT_FALSE(got_client_cert);
  14604. }
  14605. }
  14606. }
  14607. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14608. std::string cert_pem, key_pem, ca_pem;
  14609. read_file(SERVER_CERT_FILE, cert_pem);
  14610. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14611. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14612. ASSERT_TRUE(
  14613. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14614. }
  14615. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14617. ASSERT_TRUE(svr.is_valid());
  14618. UpdateCertsPemWithClientCA(svr);
  14619. RejectsClientWithoutCert(svr);
  14620. }
  14621. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14622. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14623. }
  14624. // A TLS error from one request must not show up in a later request's Result
  14625. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14627. ASSERT_TRUE(svr.is_valid());
  14628. svr.Get("/test", [](const Request &, Response &res) {
  14629. res.set_content("test", "text/plain");
  14630. });
  14631. auto port = svr.bind_to_any_port(HOST);
  14632. ASSERT_LT(0, port);
  14633. thread t = thread([&]() { svr.listen_after_bind(); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. ASSERT_FALSE(svr.is_running());
  14638. });
  14639. svr.wait_until_ready();
  14640. SSLClient cli(HOST, port);
  14641. cli.set_connection_timeout(30);
  14642. cli.enable_server_hostname_verification(false);
  14643. // cert.pem is not trusted, so the handshake fails
  14644. ASSERT_FALSE(cli.Get("/test"));
  14645. cli.enable_server_certificate_verification(false);
  14646. auto res = cli.Get("/test");
  14647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14648. EXPECT_EQ(0, res.ssl_error());
  14649. EXPECT_EQ(0UL, res.ssl_backend_error());
  14650. }
  14651. // PEM memory-based constructor tests (works with all TLS backends).
  14652. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14653. // terminator after it.
  14654. void PemMemoryClientCertPresent(
  14655. const std::string &client_cert_file,
  14656. const std::string &client_private_key_file,
  14657. const std::string &client_encrypted_private_key_pass = std::string(),
  14658. bool exact_size = false) {
  14659. // Read PEM files into memory
  14660. std::string server_cert_pem, server_key_pem;
  14661. std::string client_ca_pem;
  14662. std::string client_cert_pem, client_key_pem;
  14663. read_file(SERVER_CERT_FILE, server_cert_pem);
  14664. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14665. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14666. read_file(client_cert_file, client_cert_pem);
  14667. read_file(client_private_key_file, client_key_pem);
  14668. std::list<std::vector<char>> exact_copies;
  14669. auto data = [&](const std::string &pem) -> const char * {
  14670. if (!exact_size) { return pem.c_str(); }
  14671. exact_copies.emplace_back(pem.begin(), pem.end());
  14672. return exact_copies.back().data();
  14673. };
  14674. // Create server with PEM memory
  14675. SSLServer::PemMemory server_pem = {
  14676. data(server_cert_pem),
  14677. server_cert_pem.size(),
  14678. data(server_key_pem),
  14679. server_key_pem.size(),
  14680. data(client_ca_pem),
  14681. client_ca_pem.size(),
  14682. nullptr // no password for server key
  14683. };
  14684. SSLServer svr(server_pem);
  14685. ASSERT_TRUE(svr.is_valid());
  14686. svr.Get("/test", [&](const Request &req, Response &res) {
  14687. res.set_content("test", "text/plain");
  14688. auto cert = req.peer_cert();
  14689. ASSERT_TRUE(static_cast<bool>(cert));
  14690. EXPECT_EQ("Common Name", cert.subject_cn());
  14691. });
  14692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14693. auto se = detail::scope_exit([&] {
  14694. svr.stop();
  14695. t.join();
  14696. ASSERT_FALSE(svr.is_running());
  14697. });
  14698. svr.wait_until_ready();
  14699. // Create client with PEM memory
  14700. const char *password = client_encrypted_private_key_pass.empty()
  14701. ? nullptr
  14702. : client_encrypted_private_key_pass.c_str();
  14703. SSLClient::PemMemory client_pem = {
  14704. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14705. client_key_pem.size(), password};
  14706. SSLClient cli(HOST, PORT, client_pem);
  14707. cli.enable_server_certificate_verification(false);
  14708. cli.set_connection_timeout(30);
  14709. auto res = cli.Get("/test");
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. ASSERT_EQ(StatusCode::OK_200, res->status);
  14712. }
  14713. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14714. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14715. }
  14716. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14717. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14718. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14719. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14720. }
  14721. // A server built from PEM memory with a client CA requires client certificates,
  14722. // also when the CA is a NUL-terminated string passed with a length of 0
  14723. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14724. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14725. read_file(SERVER_CERT_FILE, server_cert_pem);
  14726. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14727. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14728. SSLServer::PemMemory server_pem = {
  14729. server_cert_pem.c_str(),
  14730. server_cert_pem.size(),
  14731. server_key_pem.c_str(),
  14732. server_key_pem.size(),
  14733. client_ca_pem.c_str(),
  14734. client_ca_pem.size(),
  14735. nullptr // no password for server key
  14736. };
  14737. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14738. SCOPED_TRACE(client_ca_pem_len);
  14739. server_pem.client_ca_pem_len = client_ca_pem_len;
  14740. SSLServer svr(server_pem);
  14741. ASSERT_TRUE(svr.is_valid());
  14742. RejectsClientWithoutCert(svr);
  14743. }
  14744. // An empty CA fails to load instead of turning the check off
  14745. server_pem.client_ca_pem = "";
  14746. server_pem.client_ca_pem_len = 0;
  14747. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14748. }
  14749. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14750. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14751. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14752. true);
  14753. }
  14754. // A length shorter than the PEM cuts it short, so it no longer loads
  14755. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14756. std::string cert, key;
  14757. read_file(SERVER_CERT_FILE, cert);
  14758. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14759. for (auto cut_cert : {true, false}) {
  14760. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14761. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14762. SSLServer::PemMemory server_pem = {
  14763. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14764. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14765. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14766. key_len, nullptr};
  14767. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14768. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14769. key.c_str(), key_len, nullptr};
  14770. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14771. }
  14772. }
  14773. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14774. class NoListenSSLServer : public SSLServer {
  14775. public:
  14776. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14777. const char *client_ca_cert_file_path,
  14778. const char *client_ca_cert_dir_path = nullptr)
  14779. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14780. client_ca_cert_dir_path),
  14781. stop_(false) {}
  14782. std::atomic_bool stop_;
  14783. private:
  14784. bool process_and_close_socket(socket_t /*sock*/) override {
  14785. // Don't create SSL context
  14786. while (!stop_.load()) {
  14787. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14788. }
  14789. return true;
  14790. }
  14791. };
  14792. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14793. CLIENT_CA_CERT_FILE);
  14794. ASSERT_TRUE(svr.is_valid());
  14795. // Keep-alive parking would bypass the override.
  14796. svr.set_keep_alive_parking(false);
  14797. svr.Get("/test", [&](const Request &, Response &res) {
  14798. res.set_content("test", "text/plain");
  14799. });
  14800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14801. auto se = detail::scope_exit([&] {
  14802. svr.stop_ = true;
  14803. svr.stop();
  14804. t.join();
  14805. ASSERT_FALSE(svr.is_running());
  14806. });
  14807. svr.wait_until_ready();
  14808. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14809. cli.enable_server_certificate_verification(false);
  14810. cli.set_connection_timeout(1);
  14811. auto res = cli.Get("/test");
  14812. ASSERT_TRUE(!res);
  14813. EXPECT_EQ(Error::SSLConnection, res.error());
  14814. // Timeout results in WantRead error code (maps to backend-specific value)
  14815. EXPECT_NE(0, res.ssl_error());
  14816. }
  14817. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14818. // Test SSLServer with client certificate verification using the standard
  14819. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14821. CLIENT_CA_CERT_DIR);
  14822. ASSERT_TRUE(svr.is_valid());
  14823. svr.Get("/test", [&](const Request &req, Response &res) {
  14824. res.set_content("test", "text/plain");
  14825. auto cert = req.peer_cert();
  14826. ASSERT_TRUE(static_cast<bool>(cert));
  14827. auto common_name = cert.subject_cn();
  14828. EXPECT_EQ("Common Name", common_name);
  14829. });
  14830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14831. auto se = detail::scope_exit([&] {
  14832. svr.stop();
  14833. t.join();
  14834. ASSERT_FALSE(svr.is_running());
  14835. });
  14836. svr.wait_until_ready();
  14837. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14838. cli.enable_server_certificate_verification(false);
  14839. cli.set_connection_timeout(30);
  14840. auto res = cli.Get("/test");
  14841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14842. ASSERT_EQ(StatusCode::OK_200, res->status);
  14843. }
  14844. // Test verify_hostname on every backend: a host is named by a SAN only
  14845. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14846. using namespace httplib::tls;
  14847. // We need a running server to test against
  14848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14849. ASSERT_TRUE(svr.is_valid());
  14850. svr.Get("/test", [](const Request &, Response &res) {
  14851. res.set_content("ok", "text/plain");
  14852. });
  14853. thread t([&]() { svr.listen(HOST, PORT); });
  14854. auto se = detail::scope_exit([&] {
  14855. svr.stop();
  14856. t.join();
  14857. });
  14858. svr.wait_until_ready();
  14859. bool verify_callback_called = false;
  14860. bool verify_result_wrong = false;
  14861. SSLClient cli(HOST, PORT);
  14862. cli.enable_server_certificate_verification(true);
  14863. cli.set_ca_cert_path(CA_CERT_FILE);
  14864. cli.set_connection_timeout(5);
  14865. // Note: Test certificate has CN="Common Name", not "localhost"
  14866. bool verify_result_cn = false;
  14867. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14868. verify_callback_called = true;
  14869. if (!ctx.cert) return false;
  14870. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14871. verify_result_cn = ctx.check_hostname("Common Name");
  14872. // Test 2: wrong hostname should not match
  14873. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14874. return true; // Accept for the purpose of this test
  14875. });
  14876. auto res = cli.Get("/test");
  14877. // The request may succeed or fail depending on cert configuration
  14878. // but the callback should have been called
  14879. ASSERT_TRUE(verify_callback_called)
  14880. << "Verify callback should have been called";
  14881. EXPECT_FALSE(verify_result_cn)
  14882. << "verify_hostname must not match the certificate CN (no SAN)";
  14883. // Wrong hostname should not match
  14884. EXPECT_FALSE(verify_result_wrong)
  14885. << "verify_hostname should not match 'wronghost.example.com'";
  14886. }
  14887. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14888. // backend verifies it.
  14889. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14890. // Certificate CN is "localhost" and it carries no SAN.
  14891. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14892. ASSERT_TRUE(svr.is_valid());
  14893. svr.Get("/test", [](const Request &, Response &res) {
  14894. res.set_content("ok", "text/plain");
  14895. });
  14896. auto port = svr.bind_to_any_port(HOST);
  14897. thread t([&]() { svr.listen_after_bind(); });
  14898. auto se = detail::scope_exit([&] {
  14899. svr.stop();
  14900. t.join();
  14901. });
  14902. svr.wait_until_ready();
  14903. SSLClient cli("localhost", port);
  14904. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14905. cli.enable_server_certificate_verification(true);
  14906. cli.set_connection_timeout(5);
  14907. auto res = cli.Get("/test");
  14908. ASSERT_FALSE(res);
  14909. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14910. // The same certificate is accepted once host name verification is off, so the
  14911. // failure above is the host name and not the chain.
  14912. cli.enable_server_hostname_verification(false);
  14913. res = cli.Get("/test");
  14914. ASSERT_TRUE(res) << to_string(res.error());
  14915. EXPECT_EQ(StatusCode::OK_200, res->status);
  14916. }
  14917. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14918. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14919. // X509_check_ip behavior and must hold for every backend.
  14920. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14921. using namespace httplib::tls;
  14922. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14923. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14924. ASSERT_TRUE(svr.is_valid());
  14925. svr.Get("/test", [](const Request &, Response &res) {
  14926. res.set_content("ok", "text/plain");
  14927. });
  14928. thread t([&]() { svr.listen(HOST, PORT); });
  14929. auto se = detail::scope_exit([&] {
  14930. svr.stop();
  14931. t.join();
  14932. });
  14933. svr.wait_until_ready();
  14934. bool verify_callback_called = false;
  14935. bool ip_matched_via_cn = true;
  14936. SSLClient cli(HOST, PORT);
  14937. cli.enable_server_certificate_verification(true);
  14938. cli.set_ca_cert_path(CA_CERT_FILE);
  14939. cli.set_connection_timeout(5);
  14940. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14941. verify_callback_called = true;
  14942. if (!ctx.cert) return false;
  14943. // The IP appears only in the CN, so it must NOT be accepted.
  14944. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14945. return true; // Accept for the purpose of this test
  14946. });
  14947. cli.Get("/test");
  14948. ASSERT_TRUE(verify_callback_called)
  14949. << "Verify callback should have been called";
  14950. EXPECT_FALSE(ip_matched_via_cn)
  14951. << "An IP host must not be authenticated via the certificate CN";
  14952. }
  14953. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14954. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14955. using namespace httplib::tls;
  14956. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14957. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14958. ASSERT_TRUE(svr.is_valid());
  14959. svr.Get("/test", [](const Request &, Response &res) {
  14960. res.set_content("ok", "text/plain");
  14961. });
  14962. thread t([&]() { svr.listen(HOST, PORT); });
  14963. auto se = detail::scope_exit([&] {
  14964. svr.stop();
  14965. t.join();
  14966. });
  14967. svr.wait_until_ready();
  14968. bool verify_callback_called = false;
  14969. bool san_matched = false;
  14970. bool wrong_ipv6_matched = true;
  14971. bool cn_ipv6_matched = true;
  14972. SSLClient cli(HOST, PORT);
  14973. cli.enable_server_certificate_verification(true);
  14974. cli.set_ca_cert_path(CA_CERT_FILE);
  14975. cli.set_connection_timeout(5);
  14976. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14977. verify_callback_called = true;
  14978. if (!ctx.cert) return false;
  14979. // Matches the IPv6 iPAddress SAN.
  14980. san_matched = ctx.check_hostname("2001:db8::1");
  14981. // A different IPv6 address must not match.
  14982. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14983. // "::1" lives only in the CN, so it must not be accepted.
  14984. cn_ipv6_matched = ctx.check_hostname("::1");
  14985. return true; // Accept for the purpose of this test
  14986. });
  14987. cli.Get("/test");
  14988. ASSERT_TRUE(verify_callback_called)
  14989. << "Verify callback should have been called";
  14990. EXPECT_TRUE(san_matched)
  14991. << "verify_hostname should match an IPv6 iPAddress SAN";
  14992. EXPECT_FALSE(wrong_ipv6_matched)
  14993. << "verify_hostname should not match a non-matching IPv6 address";
  14994. EXPECT_FALSE(cn_ipv6_matched)
  14995. << "An IPv6 host must not be authenticated via the certificate CN";
  14996. }
  14997. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14998. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14999. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15000. using namespace httplib::tls;
  15001. // SANs: DNS:a.zz, IP:42.46.122.122
  15002. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15003. ASSERT_TRUE(svr.is_valid());
  15004. svr.Get("/test", [](const Request &, Response &res) {
  15005. res.set_content("ok", "text/plain");
  15006. });
  15007. auto port = svr.bind_to_any_port(HOST);
  15008. thread t([&]() { svr.listen_after_bind(); });
  15009. auto se = detail::scope_exit([&] {
  15010. svr.stop();
  15011. t.join();
  15012. });
  15013. svr.wait_until_ready();
  15014. bool verify_callback_called = false;
  15015. bool dns_san_matched = false;
  15016. bool ip_san_matched = false;
  15017. bool ip_matched_via_dns_san = true;
  15018. bool dns_matched_via_ip_san = true;
  15019. bool cn_matched_next_to_dns_san = true;
  15020. SSLClient cli(HOST, port);
  15021. cli.enable_server_certificate_verification(true);
  15022. cli.set_ca_cert_path(CA_CERT_FILE);
  15023. cli.set_connection_timeout(5);
  15024. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15025. verify_callback_called = true;
  15026. if (!ctx.cert) return false;
  15027. dns_san_matched = ctx.check_hostname("a.zz");
  15028. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15029. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15030. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15031. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15032. return true; // Accept for the purpose of this test
  15033. });
  15034. cli.Get("/test");
  15035. ASSERT_TRUE(verify_callback_called)
  15036. << "Verify callback should have been called";
  15037. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15038. EXPECT_TRUE(ip_san_matched)
  15039. << "verify_hostname should match an iPAddress SAN";
  15040. EXPECT_FALSE(ip_matched_via_dns_san)
  15041. << "An IP host must not be authenticated via a dNSName SAN";
  15042. EXPECT_FALSE(dns_matched_via_ip_san)
  15043. << "A DNS host must not be authenticated via an iPAddress SAN";
  15044. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15045. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15046. }
  15047. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15048. // "www.*.example.test" names one host and not every host under example.test.
  15049. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15050. using namespace httplib::tls;
  15051. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15052. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15053. ASSERT_TRUE(svr.is_valid());
  15054. svr.Get("/test", [](const Request &, Response &res) {
  15055. res.set_content("ok", "text/plain");
  15056. });
  15057. auto port = svr.bind_to_any_port(HOST);
  15058. thread t([&]() { svr.listen_after_bind(); });
  15059. auto se = detail::scope_exit([&] {
  15060. svr.stop();
  15061. t.join();
  15062. });
  15063. svr.wait_until_ready();
  15064. bool verify_callback_called = false;
  15065. bool leftmost_wildcard_matched = false;
  15066. bool wildcard_spanned_labels = true;
  15067. bool inner_wildcard_matched = true;
  15068. SSLClient cli(HOST, port);
  15069. cli.enable_server_certificate_verification(true);
  15070. cli.set_ca_cert_path(CA_CERT_FILE);
  15071. cli.set_connection_timeout(5);
  15072. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15073. verify_callback_called = true;
  15074. if (!ctx.cert) return false;
  15075. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15076. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15077. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15078. return true; // Accept for the purpose of this test
  15079. });
  15080. cli.Get("/test");
  15081. ASSERT_TRUE(verify_callback_called)
  15082. << "Verify callback should have been called";
  15083. EXPECT_TRUE(leftmost_wildcard_matched)
  15084. << "A leftmost wildcard should match a single label";
  15085. EXPECT_FALSE(wildcard_spanned_labels)
  15086. << "A wildcard label must not match more than one label";
  15087. EXPECT_FALSE(inner_wildcard_matched)
  15088. << "A wildcard outside the leftmost label must not be honoured";
  15089. }
  15090. // sans() must report each SAN entry under its own type.
  15091. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15092. using namespace httplib::tls;
  15093. // SANs: DNS:a.zz, IP:42.46.122.122
  15094. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15095. ASSERT_TRUE(svr.is_valid());
  15096. svr.Get("/test", [](const Request &, Response &res) {
  15097. res.set_content("ok", "text/plain");
  15098. });
  15099. auto port = svr.bind_to_any_port(HOST);
  15100. thread t([&]() { svr.listen_after_bind(); });
  15101. auto se = detail::scope_exit([&] {
  15102. svr.stop();
  15103. t.join();
  15104. });
  15105. svr.wait_until_ready();
  15106. bool verify_callback_called = false;
  15107. std::vector<SanEntry> sans;
  15108. SSLClient cli(HOST, port);
  15109. cli.enable_server_certificate_verification(true);
  15110. cli.set_ca_cert_path(CA_CERT_FILE);
  15111. cli.set_connection_timeout(5);
  15112. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15113. verify_callback_called = true;
  15114. if (!ctx.cert) return false;
  15115. sans = ctx.sans();
  15116. return true; // Accept for the purpose of this test
  15117. });
  15118. cli.Get("/test");
  15119. ASSERT_TRUE(verify_callback_called)
  15120. << "Verify callback should have been called";
  15121. auto has_san = [&](SanType type, const std::string &value) {
  15122. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15123. return san.type == type && san.value == value;
  15124. });
  15125. };
  15126. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15127. << "sans() should report the dNSName SAN";
  15128. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15129. << "sans() should report the iPAddress SAN";
  15130. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15131. << "sans() must not report the dNSName SAN as an address";
  15132. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15133. << "sans() must not report the iPAddress SAN as a DNS name";
  15134. }
  15135. #endif
  15136. // mbedTLS-specific callback constructor test
  15137. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15138. #ifdef CPPHTTPLIB_SSL_ENABLED
  15139. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15141. ASSERT_TRUE(svr.is_valid());
  15142. // Set up a handler to verify client certificate is present
  15143. bool client_cert_verified = false;
  15144. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15145. // Verify that client certificate was provided
  15146. client_cert_verified = true;
  15147. res.set_content("success", "text/plain");
  15148. });
  15149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15150. auto se = detail::scope_exit([&] {
  15151. svr.stop();
  15152. t.join();
  15153. ASSERT_FALSE(svr.is_running());
  15154. });
  15155. svr.wait_until_ready();
  15156. // Client with certificate
  15157. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15158. cli.enable_server_certificate_verification(false);
  15159. cli.set_connection_timeout(30);
  15160. auto res = cli.Get("/test");
  15161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15162. ASSERT_EQ(StatusCode::OK_200, res->status);
  15163. ASSERT_TRUE(client_cert_verified);
  15164. EXPECT_EQ("success", res->body);
  15165. }
  15166. #endif
  15167. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15168. // backends
  15169. #ifdef CPPHTTPLIB_SSL_ENABLED
  15170. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15171. using namespace httplib::tls;
  15172. // Test that when client CA cert file is provided,
  15173. // the server properly requests and validates client certificates
  15174. // Create a server with client authentication
  15175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15176. ASSERT_TRUE(svr.is_valid());
  15177. bool handler_called = false;
  15178. svr.Get("/test", [&](const Request &req, Response &res) {
  15179. handler_called = true;
  15180. // Verify that a client certificate was provided
  15181. auto cert = req.peer_cert();
  15182. ASSERT_TRUE(static_cast<bool>(cert));
  15183. // Get the issuer name
  15184. std::string issuer_str = cert.issuer_name();
  15185. ASSERT_FALSE(issuer_str.empty());
  15186. // The client certificate should be issued by our test CA
  15187. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15188. res.set_content("authenticated", "text/plain");
  15189. });
  15190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. ASSERT_FALSE(svr.is_running());
  15195. });
  15196. svr.wait_until_ready();
  15197. // Connect with a client certificate issued by the CA
  15198. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15199. cli.enable_server_certificate_verification(false);
  15200. cli.set_connection_timeout(30);
  15201. auto res = cli.Get("/test");
  15202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15203. ASSERT_EQ(StatusCode::OK_200, res->status);
  15204. ASSERT_TRUE(handler_called);
  15205. EXPECT_EQ("authenticated", res->body);
  15206. }
  15207. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15208. using namespace httplib::tls;
  15209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15210. ASSERT_TRUE(svr.is_valid());
  15211. svr.Get("/test", [](const Request &, Response &res) {
  15212. res.set_content("ok", "text/plain");
  15213. });
  15214. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15215. auto se = detail::scope_exit([&] {
  15216. svr.stop();
  15217. t.join();
  15218. });
  15219. svr.wait_until_ready();
  15220. SSLClient cli(HOST, PORT);
  15221. cli.enable_server_certificate_verification(false);
  15222. cli.set_connection_timeout(30);
  15223. bool cert_checked = false;
  15224. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15225. if (ctx.cert) {
  15226. auto sans = ctx.sans();
  15227. // Test certificate may or may not have SANs - just verify the API
  15228. // works If SANs exist, verify the types are valid
  15229. for (const auto &san : sans) {
  15230. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15231. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15232. san.type == SanType::OTHER);
  15233. EXPECT_FALSE(san.value.empty());
  15234. }
  15235. cert_checked = true;
  15236. }
  15237. return true;
  15238. });
  15239. auto res = cli.Get("/test");
  15240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15241. EXPECT_TRUE(cert_checked);
  15242. }
  15243. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15244. using namespace httplib::tls;
  15245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15246. ASSERT_TRUE(svr.is_valid());
  15247. svr.Get("/test", [](const Request &, Response &res) {
  15248. res.set_content("ok", "text/plain");
  15249. });
  15250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15251. auto se = detail::scope_exit([&] {
  15252. svr.stop();
  15253. t.join();
  15254. });
  15255. svr.wait_until_ready();
  15256. SSLClient cli(HOST, PORT);
  15257. cli.enable_server_certificate_verification(false);
  15258. cli.set_connection_timeout(30);
  15259. bool validity_checked = false;
  15260. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15261. if (ctx.cert) {
  15262. time_t not_before = 0, not_after = 0;
  15263. bool result = ctx.validity(not_before, not_after);
  15264. EXPECT_TRUE(result);
  15265. // Verify that not_before < now < not_after for a valid cert
  15266. time_t now = time(nullptr);
  15267. EXPECT_LT(not_before, now);
  15268. EXPECT_GT(not_after, now);
  15269. validity_checked = true;
  15270. }
  15271. return true;
  15272. });
  15273. auto res = cli.Get("/test");
  15274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15275. EXPECT_TRUE(validity_checked);
  15276. }
  15277. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15278. using namespace httplib::tls;
  15279. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15280. ASSERT_TRUE(svr.is_valid());
  15281. svr.Get("/test", [](const Request &, Response &res) {
  15282. res.set_content("ok", "text/plain");
  15283. });
  15284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15285. auto se = detail::scope_exit([&] {
  15286. svr.stop();
  15287. t.join();
  15288. });
  15289. svr.wait_until_ready();
  15290. SSLClient cli(HOST, PORT);
  15291. cli.enable_server_certificate_verification(false);
  15292. cli.set_connection_timeout(30);
  15293. bool serial_checked = false;
  15294. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15295. if (ctx.cert) {
  15296. std::string serial = ctx.serial();
  15297. EXPECT_FALSE(serial.empty());
  15298. // Serial should be a hex string
  15299. for (char c : serial) {
  15300. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15301. (c >= 'a' && c <= 'f'));
  15302. }
  15303. serial_checked = true;
  15304. }
  15305. return true;
  15306. });
  15307. auto res = cli.Get("/test");
  15308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15309. EXPECT_TRUE(serial_checked);
  15310. }
  15311. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15312. // Test 1: Valid CA file - no error should be recorded
  15313. {
  15314. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15315. CLIENT_CA_CERT_FILE);
  15316. ASSERT_TRUE(svr.is_valid());
  15317. // With valid setup, last_ssl_error should be 0
  15318. EXPECT_EQ(0, svr.ssl_last_error());
  15319. }
  15320. // Test 2: Invalid CA file content
  15321. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15322. {
  15323. // Create a temporary file with completely invalid content
  15324. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15325. {
  15326. std::ofstream ofs(temp_invalid_ca);
  15327. ofs << "This is not a certificate file at all\n";
  15328. ofs << "Just plain text content\n";
  15329. }
  15330. // Create server with invalid CA file
  15331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15332. // Clean up temporary file
  15333. std::remove(temp_invalid_ca);
  15334. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15335. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15336. // Note: SSL_CTX_load_verify_locations typically fails first,
  15337. // but our error handling code path is still exercised
  15338. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15339. }
  15340. }
  15341. TEST(VerifyCallbackTest, VerifyContextFields) {
  15342. using namespace httplib::tls;
  15343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15344. ASSERT_TRUE(svr.is_valid());
  15345. svr.Get("/test", [](const Request &, Response &res) {
  15346. res.set_content("ok", "text/plain");
  15347. });
  15348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. });
  15353. svr.wait_until_ready();
  15354. SSLClient cli(HOST, PORT);
  15355. cli.enable_server_certificate_verification(false);
  15356. cli.set_connection_timeout(30);
  15357. int callback_count = 0;
  15358. bool saw_leaf_cert = false;
  15359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15360. if (ctx.cert) {
  15361. callback_count++;
  15362. // We should see at least one certificate (the leaf)
  15363. std::string cn = ctx.subject_cn();
  15364. if (!cn.empty()) { saw_leaf_cert = true; }
  15365. // Verify context fields are populated
  15366. EXPECT_NE(ctx.session, nullptr);
  15367. EXPECT_GE(ctx.depth, 0);
  15368. }
  15369. return true;
  15370. });
  15371. auto res = cli.Get("/test");
  15372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15373. EXPECT_GT(callback_count, 0);
  15374. EXPECT_TRUE(saw_leaf_cert);
  15375. }
  15376. // A verifier that accepts runs alongside the built-in verification, and is the
  15377. // only check once that is turned off.
  15378. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15379. using namespace httplib::tls;
  15380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15381. ASSERT_TRUE(svr.is_valid());
  15382. svr.Get("/test", [](const Request &, Response &res) {
  15383. res.set_content("ok", "text/plain");
  15384. });
  15385. auto port = svr.bind_to_any_port(HOST);
  15386. thread t([&]() { svr.listen_after_bind(); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. });
  15391. svr.wait_until_ready();
  15392. SSLClient cli(HOST, port);
  15393. cli.enable_server_hostname_verification(false);
  15394. auto calls = 0;
  15395. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15396. calls++;
  15397. return true;
  15398. });
  15399. // cert.pem is not trusted
  15400. auto res = cli.Get("/test");
  15401. ASSERT_FALSE(res);
  15402. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15403. EXPECT_GT(calls, 0);
  15404. cli.enable_server_certificate_verification(false);
  15405. res = cli.Get("/test");
  15406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15407. EXPECT_EQ("ok", res->body);
  15408. }
  15409. // A verifier belongs to the client that set it, not to the thread that set it.
  15410. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15411. using namespace httplib::tls;
  15412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15413. ASSERT_TRUE(svr.is_valid());
  15414. svr.Get("/test", [](const Request &, Response &res) {
  15415. res.set_content("ok", "text/plain");
  15416. });
  15417. auto port = svr.bind_to_any_port(HOST);
  15418. thread t([&]() { svr.listen_after_bind(); });
  15419. auto se = detail::scope_exit([&] {
  15420. svr.stop();
  15421. t.join();
  15422. });
  15423. svr.wait_until_ready();
  15424. auto rejecting_calls = 0;
  15425. SSLClient rejecting(HOST, port);
  15426. rejecting.enable_server_certificate_verification(false);
  15427. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15428. rejecting_calls++;
  15429. return false;
  15430. });
  15431. auto accepting_calls = 0;
  15432. SSLClient accepting(HOST, port);
  15433. accepting.enable_server_certificate_verification(false);
  15434. // Set on another thread than the requests below.
  15435. thread([&]() {
  15436. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15437. accepting_calls++;
  15438. return true;
  15439. });
  15440. }).join();
  15441. // Requested on another thread than the verifier was set on.
  15442. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15443. EXPECT_GT(rejecting_calls, 0);
  15444. auto res = accepting.Get("/test");
  15445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15446. EXPECT_GT(accepting_calls, 0);
  15447. }
  15448. // A verifier replaced while a handshake runs it lives until it returns.
  15449. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15450. using namespace httplib::tls;
  15451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15452. ASSERT_TRUE(svr.is_valid());
  15453. svr.Get("/test", [](const Request &, Response &res) {
  15454. res.set_content("ok", "text/plain");
  15455. });
  15456. auto port = svr.bind_to_any_port(HOST);
  15457. thread t([&]() { svr.listen_after_bind(); });
  15458. auto se = detail::scope_exit([&] {
  15459. svr.stop();
  15460. t.join();
  15461. });
  15462. svr.wait_until_ready();
  15463. SSLClient cli(HOST, port);
  15464. cli.enable_server_certificate_verification(false);
  15465. std::promise<void> entered;
  15466. std::promise<void> replaced;
  15467. auto replaced_future = replaced.get_future();
  15468. auto first_call = true;
  15469. // Long enough to live on the heap
  15470. std::string expected(64, 'v');
  15471. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15472. if (first_call) {
  15473. first_call = false;
  15474. entered.set_value();
  15475. replaced_future.wait();
  15476. }
  15477. return expected == std::string(64, 'v');
  15478. });
  15479. thread request([&]() {
  15480. auto res = cli.Get("/test");
  15481. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15482. });
  15483. entered.get_future().wait();
  15484. cli.set_server_certificate_verifier(
  15485. [](const VerifyContext &) { return true; });
  15486. replaced.set_value();
  15487. request.join();
  15488. }
  15489. // VerifyContext::session is the same handle the other tls:: functions take.
  15490. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15491. using namespace httplib::tls;
  15492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15493. ASSERT_TRUE(svr.is_valid());
  15494. svr.Get("/test", [](const Request &, Response &res) {
  15495. res.set_content("ok", "text/plain");
  15496. });
  15497. auto port = svr.bind_to_any_port(HOST);
  15498. thread t([&]() { svr.listen_after_bind(); });
  15499. auto se = detail::scope_exit([&] {
  15500. svr.stop();
  15501. t.join();
  15502. });
  15503. svr.wait_until_ready();
  15504. SSLClient cli(HOST, port);
  15505. cli.enable_server_certificate_verification(false);
  15506. session_t verifier_session = nullptr;
  15507. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15508. verifier_session = ctx.session;
  15509. return true;
  15510. });
  15511. session_t session_verifier_session = nullptr;
  15512. cli.set_session_verifier([&](session_t session) {
  15513. session_verifier_session = session;
  15514. return SSLVerifierResponse::NoDecisionMade;
  15515. });
  15516. auto res = cli.Get("/test");
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. EXPECT_NE(nullptr, verifier_session);
  15519. EXPECT_EQ(session_verifier_session, verifier_session);
  15520. }
  15521. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15522. using httplib::tls::TlsError;
  15523. // Test that verify_error_to_string returns empty for success
  15524. std::string success_str = TlsError::verify_error_to_string(0);
  15525. EXPECT_TRUE(success_str.empty());
  15526. // Test that verify_error_to_string returns non-empty for error codes
  15527. // Using a common error code (certificate expired)
  15528. std::string error_str =
  15529. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15530. EXPECT_FALSE(error_str.empty());
  15531. }
  15532. TEST(SessionVerifierTest, CertificateAccepted) {
  15533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15534. ASSERT_TRUE(svr.is_valid());
  15535. svr.Get("/test", [](const Request &, Response &res) {
  15536. res.set_content("ok", "text/plain");
  15537. });
  15538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15539. auto se = detail::scope_exit([&] {
  15540. svr.stop();
  15541. t.join();
  15542. });
  15543. svr.wait_until_ready();
  15544. SSLClient cli(HOST, PORT);
  15545. cli.enable_server_certificate_verification(false);
  15546. cli.set_connection_timeout(30);
  15547. bool callback_called = false;
  15548. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15549. EXPECT_NE(session, nullptr);
  15550. callback_called = true;
  15551. return SSLVerifierResponse::CertificateAccepted;
  15552. });
  15553. auto res = cli.Get("/test");
  15554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15555. EXPECT_EQ(200, res->status);
  15556. EXPECT_TRUE(callback_called);
  15557. }
  15558. TEST(SessionVerifierTest, CertificateRejected) {
  15559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15560. ASSERT_TRUE(svr.is_valid());
  15561. svr.Get("/test", [](const Request &, Response &res) {
  15562. res.set_content("ok", "text/plain");
  15563. });
  15564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15565. auto se = detail::scope_exit([&] {
  15566. svr.stop();
  15567. t.join();
  15568. });
  15569. svr.wait_until_ready();
  15570. SSLClient cli(HOST, PORT);
  15571. cli.enable_server_certificate_verification(false);
  15572. cli.set_connection_timeout(30);
  15573. bool callback_called = false;
  15574. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15575. EXPECT_NE(session, nullptr);
  15576. callback_called = true;
  15577. return SSLVerifierResponse::CertificateRejected;
  15578. });
  15579. auto res = cli.Get("/test");
  15580. EXPECT_FALSE(res);
  15581. EXPECT_TRUE(callback_called);
  15582. }
  15583. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15585. ASSERT_TRUE(svr.is_valid());
  15586. svr.Get("/test", [](const Request &, Response &res) {
  15587. res.set_content("ok", "text/plain");
  15588. });
  15589. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15590. auto se = detail::scope_exit([&] {
  15591. svr.stop();
  15592. t.join();
  15593. });
  15594. svr.wait_until_ready();
  15595. // NoDecisionMade with verification disabled should succeed (no default check)
  15596. SSLClient cli(HOST, PORT);
  15597. cli.enable_server_certificate_verification(false);
  15598. cli.set_connection_timeout(30);
  15599. bool callback_called = false;
  15600. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15601. EXPECT_NE(session, nullptr);
  15602. callback_called = true;
  15603. return SSLVerifierResponse::NoDecisionMade;
  15604. });
  15605. auto res = cli.Get("/test");
  15606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15607. EXPECT_EQ(200, res->status);
  15608. EXPECT_TRUE(callback_called);
  15609. }
  15610. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15612. ASSERT_TRUE(svr.is_valid());
  15613. svr.Get("/test", [](const Request &, Response &res) {
  15614. res.set_content("ok", "text/plain");
  15615. });
  15616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15617. auto se = detail::scope_exit([&] {
  15618. svr.stop();
  15619. t.join();
  15620. });
  15621. svr.wait_until_ready();
  15622. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15623. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15624. // so we only check that the request fails, not whether the callback was
  15625. // called.
  15626. SSLClient cli(HOST, PORT);
  15627. cli.enable_server_certificate_verification(true);
  15628. cli.set_connection_timeout(30);
  15629. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15630. EXPECT_NE(session, nullptr);
  15631. return SSLVerifierResponse::NoDecisionMade;
  15632. });
  15633. auto res = cli.Get("/test");
  15634. EXPECT_FALSE(res);
  15635. }
  15636. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15637. // Test SSL server using PemMemory constructor with client CA certificates
  15638. // Read PEM files
  15639. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15640. read_file(SERVER_CERT_FILE, server_cert_pem);
  15641. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15642. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15643. // Create SSLServer with PemMemory constructor including client CA
  15644. SSLServer::PemMemory server_pem = {
  15645. server_cert_pem.c_str(),
  15646. server_cert_pem.size(),
  15647. server_key_pem.c_str(),
  15648. server_key_pem.size(),
  15649. client_ca_pem.c_str(),
  15650. client_ca_pem.size(),
  15651. nullptr // no password for server key
  15652. };
  15653. SSLServer svr(server_pem);
  15654. ASSERT_TRUE(svr.is_valid());
  15655. // No SSL error should be recorded for valid setup
  15656. EXPECT_EQ(0, svr.ssl_last_error());
  15657. // Set up server endpoints
  15658. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15659. res.set_content("ok", "text/plain");
  15660. });
  15661. // Start server in a thread
  15662. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15663. svr.wait_until_ready();
  15664. // Connect with client certificate (using constructor with paths)
  15665. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15666. cli.enable_server_certificate_verification(false);
  15667. auto res = cli.Get("/test-pem-ca");
  15668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15669. EXPECT_EQ(200, res->status);
  15670. EXPECT_EQ("ok", res->body);
  15671. svr.stop();
  15672. server_thread.join();
  15673. }
  15674. #endif
  15675. #ifdef _WIN32
  15676. TEST(CleanupTest, WSACleanup) {
  15677. int ret = WSACleanup();
  15678. ASSERT_EQ(0, ret);
  15679. }
  15680. #endif
  15681. #ifndef CPPHTTPLIB_SSL_ENABLED
  15682. TEST(NoSSLSupport, SimpleInterface) {
  15683. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15684. }
  15685. #endif
  15686. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15687. TEST(InvalidScheme, SimpleInterface) {
  15688. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15689. }
  15690. #endif
  15691. TEST(NoScheme, SimpleInterface) {
  15692. Client cli("yahoo.com:80");
  15693. ASSERT_TRUE(cli.is_valid());
  15694. }
  15695. TEST(SendAPI, SimpleInterface_Online) {
  15696. Client cli("http://yahoo.com");
  15697. Request req;
  15698. req.method = "GET";
  15699. req.path = "/";
  15700. auto res = cli.send(req);
  15701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15703. }
  15704. TEST(SendAPI, WithParamsInRequest) {
  15705. Server svr;
  15706. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15707. EXPECT_TRUE(req.has_param("test"));
  15708. EXPECT_EQ("test_value", req.get_param_value("test"));
  15709. });
  15710. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15711. auto se = detail::scope_exit([&] {
  15712. svr.stop();
  15713. t.join();
  15714. ASSERT_FALSE(svr.is_running());
  15715. });
  15716. svr.wait_until_ready();
  15717. Client cli(HOST, PORT);
  15718. {
  15719. Request req;
  15720. req.method = "GET";
  15721. req.path = "/";
  15722. req.params.emplace("test", "test_value");
  15723. auto res = cli.send(req);
  15724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15725. }
  15726. {
  15727. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15729. }
  15730. }
  15731. TEST(ClientImplMethods, GetSocketTest) {
  15732. httplib::Server svr;
  15733. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15734. res.status = StatusCode::OK_200;
  15735. });
  15736. auto port = svr.bind_to_any_port("127.0.0.1");
  15737. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15738. auto se = detail::scope_exit([&] {
  15739. svr.stop();
  15740. thread.join();
  15741. ASSERT_FALSE(svr.is_running());
  15742. });
  15743. svr.wait_until_ready();
  15744. {
  15745. httplib::Client cli("127.0.0.1", port);
  15746. cli.set_keep_alive(true);
  15747. // Use the behavior of cpp-httplib of opening the connection
  15748. // only when the first request happens. If that changes,
  15749. // this test would be obsolete.
  15750. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15751. // This also implicitly tests the server. But other tests would fail much
  15752. // earlier than this one to be considered.
  15753. auto res = cli.Get("/");
  15754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15755. EXPECT_EQ(StatusCode::OK_200, res->status);
  15756. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15757. }
  15758. }
  15759. #ifdef CPPHTTPLIB_SSL_ENABLED
  15760. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15761. Client cli("http://yahoo.com");
  15762. auto res = cli.Get("/");
  15763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15764. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15765. cli.set_follow_location(true);
  15766. res = cli.Get("/");
  15767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15768. EXPECT_EQ(StatusCode::OK_200, res->status);
  15769. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15770. }
  15771. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15772. Client cli("https://yahoo.com");
  15773. auto res = cli.Get("/");
  15774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15775. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15776. cli.set_follow_location(true);
  15777. res = cli.Get("/");
  15778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15779. EXPECT_EQ(StatusCode::OK_200, res->status);
  15780. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15781. }
  15782. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15783. Client cli("https://yahoo.com");
  15784. auto res = cli.Get("/");
  15785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15786. ASSERT_FALSE(!res);
  15787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15788. ASSERT_FALSE(res == nullptr);
  15789. ASSERT_TRUE(res != nullptr);
  15790. EXPECT_EQ(Error::Success, res.error());
  15791. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15792. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15793. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15794. cli.set_follow_location(true);
  15795. res = cli.Get("/");
  15796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15797. EXPECT_EQ(Error::Success, res.error());
  15798. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15799. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15800. EXPECT_EQ(StatusCode::OK_200, res->status);
  15801. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15802. }
  15803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15804. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15805. Client cli("https://cdnjs.cloudflare.com");
  15806. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15807. Headers{{"Accept-Encoding", "br"}});
  15808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15809. EXPECT_EQ(StatusCode::OK_200, res->status);
  15810. EXPECT_EQ(287630U, res->body.size());
  15811. EXPECT_EQ("application/javascript; charset=utf-8",
  15812. res->get_header_value("Content-Type"));
  15813. }
  15814. #endif
  15815. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15816. #undef REDIR_HOST // Silence compiler warning
  15817. #define REDIR_HOST "https://httpbingo.org"
  15818. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15819. Client cli(REDIR_HOST);
  15820. cli.set_follow_location(true);
  15821. auto res =
  15822. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15824. EXPECT_EQ(StatusCode::OK_200, res->status);
  15825. }
  15826. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15827. Client cli(REDIR_HOST);
  15828. cli.set_follow_location(true);
  15829. Params params;
  15830. params.emplace("url", "http://example.com");
  15831. params.emplace("status_code", "302");
  15832. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. EXPECT_EQ(StatusCode::OK_200, res->status);
  15835. }
  15836. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15837. Client cli(REDIR_HOST);
  15838. cli.set_follow_location(true);
  15839. Params params;
  15840. params.emplace("url", "http://example.com");
  15841. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15843. EXPECT_EQ(StatusCode::OK_200, res->status);
  15844. }
  15845. TEST(HttpToHttpsRedirectTest, CertFile) {
  15846. auto ssl_port = PORT + 1;
  15847. Server svr;
  15848. ASSERT_TRUE(svr.is_valid());
  15849. svr.Get("/index", [&](const Request &, Response &res) {
  15850. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15851. "/index");
  15852. svr.stop();
  15853. });
  15854. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15855. ASSERT_TRUE(ssl_svr.is_valid());
  15856. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15857. res.set_content("test", "text/plain");
  15858. ssl_svr.stop();
  15859. });
  15860. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15861. thread t2 =
  15862. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15863. auto se = detail::scope_exit([&] {
  15864. t2.join();
  15865. t.join();
  15866. ASSERT_FALSE(svr.is_running());
  15867. });
  15868. svr.wait_until_ready();
  15869. ssl_svr.wait_until_ready();
  15870. Client cli("127.0.0.1", PORT);
  15871. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15872. cli.enable_server_certificate_verification(true);
  15873. cli.set_follow_location(true);
  15874. cli.set_connection_timeout(30);
  15875. auto res = cli.Get("/index");
  15876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15877. ASSERT_EQ(StatusCode::OK_200, res->status);
  15878. }
  15879. TEST(UppercaseSchemeTest, UsesTLS) {
  15880. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15881. ASSERT_TRUE(ssl_svr.is_valid());
  15882. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15883. res.set_content("test", "text/plain");
  15884. });
  15885. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15886. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15887. Server svr;
  15888. svr.Get("/index", [&](const Request &, Response &res) {
  15889. res.set_redirect(https_url + "/index");
  15890. });
  15891. auto port = svr.bind_to_any_port("127.0.0.1");
  15892. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15893. auto t2 = thread([&] { svr.listen_after_bind(); });
  15894. auto se = detail::scope_exit([&] {
  15895. svr.stop();
  15896. ssl_svr.stop();
  15897. t2.join();
  15898. t.join();
  15899. });
  15900. ssl_svr.wait_until_ready();
  15901. svr.wait_until_ready();
  15902. {
  15903. Client cli(https_url);
  15904. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15905. auto res = cli.Get("/index");
  15906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15907. EXPECT_EQ("test", res->body);
  15908. }
  15909. {
  15910. Client cli("127.0.0.1", port);
  15911. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15912. cli.set_follow_location(true);
  15913. auto res = cli.Get("/index");
  15914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15915. EXPECT_EQ("test", res->body);
  15916. }
  15917. }
  15918. TEST(SSLClientRedirectTest, CertFile) {
  15919. auto ssl_port = PORT + 1;
  15920. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15921. ASSERT_TRUE(ssl_svr1.is_valid());
  15922. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15923. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15924. "/index");
  15925. ssl_svr1.stop();
  15926. });
  15927. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15928. ASSERT_TRUE(ssl_svr2.is_valid());
  15929. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15930. res.set_content("test", "text/plain");
  15931. ssl_svr2.stop();
  15932. });
  15933. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15934. thread t2 =
  15935. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15936. auto se = detail::scope_exit([&] {
  15937. t2.join();
  15938. t.join();
  15939. ASSERT_FALSE(ssl_svr1.is_running());
  15940. });
  15941. ssl_svr1.wait_until_ready();
  15942. ssl_svr2.wait_until_ready();
  15943. SSLClient cli("127.0.0.1", PORT);
  15944. std::string cert;
  15945. read_file(SERVER_CERT2_FILE, cert);
  15946. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15947. cli.enable_server_certificate_verification(true);
  15948. cli.set_follow_location(true);
  15949. cli.set_connection_timeout(30);
  15950. auto res = cli.Get("/index");
  15951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15952. ASSERT_EQ(StatusCode::OK_200, res->status);
  15953. }
  15954. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15955. // another port, so the client follows it with a new client.
  15956. static Result GetThroughTlsRedirectToDifferentPort(
  15957. const std::function<void(SSLClient &)> &setup,
  15958. const char *target_cert = SERVER_CERT2_FILE,
  15959. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15960. auto ssl_port = PORT + 1;
  15961. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15962. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15963. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15964. "/index");
  15965. });
  15966. SSLServer ssl_svr2(target_cert, target_key);
  15967. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15968. res.set_content("test", "text/plain");
  15969. });
  15970. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15971. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15972. auto se = detail::scope_exit([&] {
  15973. ssl_svr2.stop();
  15974. ssl_svr1.stop();
  15975. t2.join();
  15976. t.join();
  15977. });
  15978. ssl_svr1.wait_until_ready();
  15979. ssl_svr2.wait_until_ready();
  15980. SSLClient cli("127.0.0.1", PORT);
  15981. cli.set_follow_location(true);
  15982. cli.set_connection_timeout(30);
  15983. setup(cli);
  15984. return cli.Get("/index");
  15985. }
  15986. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15987. auto calls = 0;
  15988. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15989. cli.enable_server_certificate_verification(false);
  15990. // Accept the first server only.
  15991. cli.set_session_verifier([&](tls::session_t) {
  15992. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15993. : SSLVerifierResponse::CertificateRejected;
  15994. });
  15995. });
  15996. ASSERT_FALSE(res);
  15997. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15998. EXPECT_EQ(2, calls);
  15999. }
  16000. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16001. std::string pinned;
  16002. auto res = GetThroughTlsRedirectToDifferentPort(
  16003. [&](SSLClient &cli) {
  16004. cli.enable_server_certificate_verification(false);
  16005. // Pin the first certificate seen.
  16006. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16007. if (pinned.empty()) { pinned = ctx.serial(); }
  16008. return ctx.serial() == pinned;
  16009. });
  16010. },
  16011. // A certificate other than the first server's.
  16012. SERVER_CERT_FILE);
  16013. EXPECT_FALSE(res);
  16014. EXPECT_FALSE(pinned.empty());
  16015. }
  16016. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16017. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16018. std::string cert;
  16019. read_file(SERVER_CERT2_FILE, cert);
  16020. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16021. });
  16022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16023. EXPECT_EQ(StatusCode::OK_200, res->status);
  16024. }
  16025. // The target's certificate is signed by the root CA, which the first server's
  16026. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16027. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16028. auto res = GetThroughTlsRedirectToDifferentPort(
  16029. [](SSLClient &cli) {
  16030. std::string root_ca, cert;
  16031. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16032. read_file(SERVER_CERT2_FILE, cert);
  16033. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16034. cli.load_ca_cert_store(cert.data(), cert.size());
  16035. cli.enable_server_hostname_verification(false);
  16036. },
  16037. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16039. EXPECT_EQ(StatusCode::OK_200, res->status);
  16040. }
  16041. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16042. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16043. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16044. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16045. auto res = GetThroughTlsRedirectToDifferentPort(
  16046. [](SSLClient &cli) {
  16047. std::string root_ca, cert;
  16048. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16049. read_file(SERVER_CERT2_FILE, cert);
  16050. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16051. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16052. cli.enable_server_hostname_verification(false);
  16053. },
  16054. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16055. ASSERT_FALSE(res);
  16056. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16057. }
  16058. #endif
  16059. #endif
  16060. #ifdef CPPHTTPLIB_SSL_ENABLED
  16061. // Test that set_ca_cert_store() skips system certs (consistent with
  16062. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16063. // should be trusted - system certs should NOT be loaded.
  16064. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16065. // Load a specific cert that is NOT a system CA cert
  16066. std::string cert;
  16067. read_file(SERVER_CERT2_FILE, cert);
  16068. SSLClient cli("google.com");
  16069. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16070. cli.enable_server_certificate_verification(true);
  16071. // This should FAIL because:
  16072. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16073. // 2. System certs should NOT be loaded when custom store is set
  16074. // If system certs WERE loaded, this would succeed
  16075. auto res = cli.Get("/");
  16076. ASSERT_FALSE(res);
  16077. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16078. }
  16079. // Same as above, but through the native store handle path. Regression test:
  16080. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16081. // merged system certs into the user-provided store.
  16082. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16083. std::string cert;
  16084. read_file(SERVER_CERT2_FILE, cert);
  16085. SSLClient cli("google.com");
  16086. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16087. cli.enable_server_certificate_verification(true);
  16088. auto res = cli.Get("/");
  16089. ASSERT_FALSE(res);
  16090. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16091. }
  16092. // A custom store set via the native handle must still verify a server whose
  16093. // cert it does contain.
  16094. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16095. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16096. ASSERT_TRUE(svr.is_valid());
  16097. svr.Get("/test", [&](const Request &, Response &res) {
  16098. res.set_content("test", "text/plain");
  16099. });
  16100. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16101. auto se = detail::scope_exit([&] {
  16102. svr.stop();
  16103. t.join();
  16104. ASSERT_FALSE(svr.is_running());
  16105. });
  16106. svr.wait_until_ready();
  16107. SSLClient cli("127.0.0.1", PORT);
  16108. std::string cert;
  16109. read_file(SERVER_CERT2_FILE, cert);
  16110. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16111. cli.enable_server_certificate_verification(true);
  16112. cli.set_connection_timeout(30);
  16113. auto res = cli.Get("/test");
  16114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16115. ASSERT_EQ(StatusCode::OK_200, res->status);
  16116. }
  16117. // CA certs loaded through the universal Client must be transferred to the
  16118. // client created internally for following an HTTPS redirect. Regression test:
  16119. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16120. // the CA data for redirect transfer.
  16121. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16122. auto ssl_port = PORT + 1;
  16123. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16124. ASSERT_TRUE(ssl_svr1.is_valid());
  16125. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16126. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16127. "/index");
  16128. });
  16129. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16130. ASSERT_TRUE(ssl_svr2.is_valid());
  16131. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16132. res.set_content("test", "text/plain");
  16133. });
  16134. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16135. thread t2 =
  16136. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16137. auto se = detail::scope_exit([&] {
  16138. ssl_svr2.stop();
  16139. ssl_svr1.stop();
  16140. t2.join();
  16141. t.join();
  16142. ASSERT_FALSE(ssl_svr1.is_running());
  16143. });
  16144. ssl_svr1.wait_until_ready();
  16145. ssl_svr2.wait_until_ready();
  16146. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16147. std::string cert;
  16148. read_file(SERVER_CERT2_FILE, cert);
  16149. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16150. cli.enable_server_certificate_verification(true);
  16151. cli.set_follow_location(true);
  16152. cli.set_connection_timeout(30);
  16153. auto res = cli.Get("/index");
  16154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16155. ASSERT_EQ(StatusCode::OK_200, res->status);
  16156. }
  16157. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16158. // so a host signed by a system CA verifies even though a custom CA is set
  16159. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16160. std::string cert;
  16161. read_file(SERVER_CERT2_FILE, cert);
  16162. SSLClient cli("google.com");
  16163. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16164. cli.enable_system_ca(true);
  16165. cli.enable_server_certificate_verification(true);
  16166. auto res = cli.Get("/");
  16167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16168. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16169. }
  16170. // The custom CA remains effective when combined with the system CA
  16171. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16172. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16173. ASSERT_TRUE(svr.is_valid());
  16174. svr.Get("/test", [&](const Request &, Response &res) {
  16175. res.set_content("test", "text/plain");
  16176. });
  16177. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16178. auto se = detail::scope_exit([&] {
  16179. svr.stop();
  16180. t.join();
  16181. ASSERT_FALSE(svr.is_running());
  16182. });
  16183. svr.wait_until_ready();
  16184. SSLClient cli("127.0.0.1", PORT);
  16185. std::string cert;
  16186. read_file(SERVER_CERT2_FILE, cert);
  16187. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16188. cli.enable_system_ca(true);
  16189. cli.enable_server_certificate_verification(true);
  16190. cli.set_connection_timeout(30);
  16191. auto res = cli.Get("/test");
  16192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16193. ASSERT_EQ(StatusCode::OK_200, res->status);
  16194. }
  16195. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16196. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16197. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16198. static CFDictionaryRef
  16199. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16200. const SecTrustSettingsResult *result) {
  16201. auto constraint =
  16202. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16203. &kCFTypeDictionaryValueCallBacks);
  16204. if (policy) {
  16205. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16206. }
  16207. if (policy_string) {
  16208. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16209. kCFStringEncodingUTF8);
  16210. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16211. CFRelease(str);
  16212. }
  16213. if (result) {
  16214. auto number_value = static_cast<SInt32>(*result);
  16215. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16216. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16217. CFRelease(number);
  16218. }
  16219. return constraint;
  16220. }
  16221. static SecTrustSettingsResult
  16222. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16223. auto trust_settings =
  16224. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16225. for (auto constraint : constraints) {
  16226. CFArrayAppendValue(trust_settings, constraint);
  16227. CFRelease(constraint);
  16228. }
  16229. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16230. CFRelease(trust_settings);
  16231. return result;
  16232. }
  16233. // The system CA loader takes a Keychain certificate as a trusted root only
  16234. // when its Trust Settings say so for SSL, not merely because it has some.
  16235. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16236. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16237. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16238. const auto deny = kSecTrustSettingsResultDeny;
  16239. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16240. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16241. auto x509_policy = SecPolicyCreateBasicX509();
  16242. // "Always Trust", which stores no constraint at all
  16243. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16244. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16245. ssl_trust_settings_result(
  16246. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16247. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16248. ssl_trust_settings_result(
  16249. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16250. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16251. ssl_trust_settings_result(
  16252. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16253. // "Never Trust", for everything or for SSL
  16254. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16255. ssl_trust_settings_result(
  16256. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16257. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16258. ssl_trust_settings_result(
  16259. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16260. // Trusted for another policy, for one host, or not at all
  16261. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16262. ssl_trust_settings_result(
  16263. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16264. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16265. ssl_trust_settings_result({make_usage_constraint(
  16266. ssl_policy, "www.example.com", &trust_root)}));
  16267. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16268. ssl_trust_settings_result(
  16269. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16270. // The first constraint that applies to SSL decides
  16271. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16272. ssl_trust_settings_result(
  16273. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16274. make_usage_constraint(nullptr, nullptr, &deny)}));
  16275. CFRelease(x509_policy);
  16276. CFRelease(ssl_policy);
  16277. }
  16278. #endif
  16279. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16280. // skip chain verification entirely (only the certificate identity was
  16281. // checked), so a server presenting an untrusted certificate with a matching
  16282. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16283. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16284. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16285. ASSERT_TRUE(svr.is_valid());
  16286. svr.Get("/test", [&](const Request &, Response &res) {
  16287. res.set_content("test", "text/plain");
  16288. });
  16289. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16290. auto se = detail::scope_exit([&] {
  16291. svr.stop();
  16292. t.join();
  16293. ASSERT_FALSE(svr.is_running());
  16294. });
  16295. svr.wait_until_ready();
  16296. SSLClient cli("127.0.0.1", PORT);
  16297. std::string cert;
  16298. // A trusted CA that did not sign the server certificate. The server cert
  16299. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16300. // this connection.
  16301. read_file(CLIENT_CA_CERT_FILE, cert);
  16302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16303. cli.enable_server_certificate_verification(true);
  16304. cli.set_connection_timeout(30);
  16305. auto res = cli.Get("/test");
  16306. ASSERT_FALSE(res);
  16307. }
  16308. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16309. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16310. // CA that failed to come through fails verification instead of trusting them.
  16311. // (wolfSSL does not list the system CAs it loaded.)
  16312. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16313. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16314. ASSERT_TRUE(svr.is_valid());
  16315. auto port = svr.bind_to_any_port("127.0.0.1");
  16316. ASSERT_LT(0, port);
  16317. thread t = thread([&] { svr.listen_after_bind(); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. });
  16323. svr.wait_until_ready();
  16324. // The CAs a client trusts once its first request has loaded them
  16325. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16326. Client cli("https://127.0.0.1:" + std::to_string(port));
  16327. setup(cli);
  16328. cli.Get("/");
  16329. return tls::get_ca_names(cli.tls_context()).size();
  16330. };
  16331. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16332. EXPECT_EQ(0u,
  16333. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16334. }
  16335. #endif
  16336. // A TLS setting changed between requests applies to the next one, not just to
  16337. // the next connection
  16338. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16339. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16340. ASSERT_TRUE(svr.is_valid());
  16341. svr.Get("/", [](const Request &req, Response &res) {
  16342. res.set_content(std::to_string(req.remote_port), "text/plain");
  16343. });
  16344. auto port = svr.bind_to_any_port("127.0.0.1");
  16345. ASSERT_LT(0, port);
  16346. thread t = thread([&] { svr.listen_after_bind(); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. t.join();
  16350. ASSERT_FALSE(svr.is_running());
  16351. });
  16352. svr.wait_until_ready();
  16353. SSLClient cli("127.0.0.1", port);
  16354. cli.set_keep_alive(true);
  16355. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16356. cli.enable_server_certificate_verification(false);
  16357. // The port the request went out from, so a new one means a new connection
  16358. auto client_port = [&] {
  16359. auto res = cli.Get("/");
  16360. return res ? res->body : std::string();
  16361. };
  16362. auto last = client_port();
  16363. ASSERT_FALSE(last.empty());
  16364. // Setting a value it already has keeps the connection
  16365. cli.enable_server_certificate_verification(false);
  16366. cli.enable_server_hostname_verification(true);
  16367. EXPECT_EQ(last, client_port());
  16368. cli.enable_server_certificate_verification(true);
  16369. auto res = cli.Get("/");
  16370. EXPECT_FALSE(res);
  16371. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16372. std::string ca;
  16373. read_file(SERVER_CERT2_FILE, ca);
  16374. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16375. last = client_port();
  16376. ASSERT_FALSE(last.empty());
  16377. std::vector<std::function<void()>> setters = {
  16378. [&] { cli.enable_server_hostname_verification(false); },
  16379. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16380. [&] {
  16381. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16382. },
  16383. [&] {
  16384. cli.set_server_certificate_verifier(
  16385. [](const tls::VerifyContext &) { return true; });
  16386. },
  16387. [&] {
  16388. cli.set_session_verifier(
  16389. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16390. },
  16391. };
  16392. for (const auto &setter : setters) {
  16393. setter();
  16394. auto next = client_port();
  16395. ASSERT_FALSE(next.empty());
  16396. EXPECT_NE(last, next);
  16397. last = next;
  16398. }
  16399. cli.set_session_verifier(
  16400. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16401. auto handle = cli.open_stream("GET", "/");
  16402. EXPECT_FALSE(handle.is_valid());
  16403. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16404. }
  16405. // A PEM given to create_ca_store() needs no NUL after it
  16406. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16407. std::string pem;
  16408. read_file(SERVER_CERT2_FILE, pem);
  16409. auto buf = pem + "X";
  16410. auto store = tls::create_ca_store(buf.data(), pem.size());
  16411. EXPECT_TRUE(store != nullptr);
  16412. SSLClient cli("localhost");
  16413. cli.set_ca_cert_store(store);
  16414. }
  16415. // enable_system_ca(false) prevents system CA loading entirely
  16416. TEST(SSLClientTest, DisableSystemCa_Online) {
  16417. SSLClient cli("google.com");
  16418. cli.enable_system_ca(false);
  16419. cli.enable_server_certificate_verification(true);
  16420. auto res = cli.Get("/");
  16421. ASSERT_FALSE(res);
  16422. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16423. // itself when the CA chain is empty
  16424. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16425. res.error() == Error::SSLConnection);
  16426. }
  16427. // The universal Client forwards enable_system_ca()
  16428. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16429. std::string cert;
  16430. read_file(SERVER_CERT2_FILE, cert);
  16431. Client cli("https://google.com");
  16432. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16433. cli.enable_system_ca(true);
  16434. cli.enable_server_certificate_verification(true);
  16435. auto res = cli.Get("/");
  16436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16437. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16438. }
  16439. // The system CA policy must carry over to the client created internally for
  16440. // following a cross-host HTTPS redirect
  16441. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16442. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16443. ASSERT_TRUE(svr.is_valid());
  16444. svr.Get("/index", [&](const Request &, Response &res) {
  16445. res.set_redirect("https://www.google.com/");
  16446. });
  16447. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16448. auto se = detail::scope_exit([&] {
  16449. svr.stop();
  16450. t.join();
  16451. ASSERT_FALSE(svr.is_running());
  16452. });
  16453. svr.wait_until_ready();
  16454. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16455. std::string cert;
  16456. read_file(SERVER_CERT2_FILE, cert);
  16457. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16458. cli.enable_system_ca(true);
  16459. cli.enable_server_certificate_verification(true);
  16460. cli.set_follow_location(true);
  16461. cli.set_connection_timeout(30);
  16462. // Receiving any response proves the redirect client completed the TLS
  16463. // handshake with a system-CA-signed host
  16464. auto res = cli.Get("/index");
  16465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16466. }
  16467. TEST(MultipartFormDataTest, LargeData) {
  16468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16469. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16470. const ContentReader &content_reader) {
  16471. if (req.is_multipart_form_data()) {
  16472. std::vector<FormData> items;
  16473. content_reader(
  16474. [&](const FormData &file) {
  16475. items.push_back(file);
  16476. return true;
  16477. },
  16478. [&](const char *data, size_t data_length) {
  16479. items.back().content.append(data, data_length);
  16480. return true;
  16481. });
  16482. EXPECT_TRUE(std::string(items[0].name) == "document");
  16483. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16484. EXPECT_TRUE(items[0].filename == "2MB_data");
  16485. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16486. EXPECT_TRUE(items[1].name == "hello");
  16487. EXPECT_TRUE(items[1].content == "world");
  16488. EXPECT_TRUE(items[1].filename == "");
  16489. EXPECT_TRUE(items[1].content_type == "");
  16490. } else {
  16491. std::string body;
  16492. content_reader([&](const char *data, size_t data_length) {
  16493. body.append(data, data_length);
  16494. return true;
  16495. });
  16496. }
  16497. });
  16498. auto port = svr.bind_to_any_port(HOST);
  16499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16500. auto se = detail::scope_exit([&] {
  16501. svr.stop();
  16502. t.join();
  16503. ASSERT_FALSE(svr.is_running());
  16504. });
  16505. svr.wait_until_ready();
  16506. {
  16507. std::string data(1024 * 1024 * 2, '.');
  16508. std::stringstream buffer;
  16509. buffer << data;
  16510. SSLClient cli(HOST, port);
  16511. cli.enable_server_certificate_verification(false);
  16512. UploadFormDataItems items{
  16513. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16514. {"hello", "world", "", ""},
  16515. };
  16516. auto res = cli.Post("/post", items);
  16517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16518. ASSERT_EQ(StatusCode::OK_200, res->status);
  16519. }
  16520. }
  16521. TEST(MultipartFormDataTest, DataProviderItems) {
  16522. std::random_device seed_gen;
  16523. std::mt19937 random(seed_gen());
  16524. std::string rand1;
  16525. rand1.resize(1000);
  16526. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16527. std::string rand2;
  16528. rand2.resize(3000);
  16529. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16531. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16532. const ContentReader &content_reader) {
  16533. ASSERT_FALSE(req.is_multipart_form_data());
  16534. std::string body;
  16535. content_reader([&](const char *data, size_t data_length) {
  16536. body.append(data, data_length);
  16537. return true;
  16538. });
  16539. EXPECT_EQ(body, "");
  16540. });
  16541. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16542. const ContentReader &content_reader) {
  16543. ASSERT_TRUE(req.is_multipart_form_data());
  16544. std::vector<FormData> items;
  16545. content_reader(
  16546. [&](const FormData &file) {
  16547. items.push_back(file);
  16548. return true;
  16549. },
  16550. [&](const char *data, size_t data_length) {
  16551. items.back().content.append(data, data_length);
  16552. return true;
  16553. });
  16554. ASSERT_TRUE(items.size() == 2);
  16555. EXPECT_EQ(std::string(items[0].name), "name1");
  16556. EXPECT_EQ(items[0].content, "Testing123");
  16557. EXPECT_EQ(items[0].filename, "filename1");
  16558. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16559. EXPECT_EQ(items[1].name, "name2");
  16560. EXPECT_EQ(items[1].content, "Testing456");
  16561. EXPECT_EQ(items[1].filename, "");
  16562. EXPECT_EQ(items[1].content_type, "");
  16563. });
  16564. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16565. const ContentReader &content_reader) {
  16566. ASSERT_TRUE(req.is_multipart_form_data());
  16567. std::vector<FormData> items;
  16568. content_reader(
  16569. [&](const FormData &file) {
  16570. items.push_back(file);
  16571. return true;
  16572. },
  16573. [&](const char *data, size_t data_length) {
  16574. items.back().content.append(data, data_length);
  16575. return true;
  16576. });
  16577. ASSERT_TRUE(items.size() == 2);
  16578. EXPECT_EQ(items[0].name, "name3");
  16579. EXPECT_EQ(items[0].content, rand1);
  16580. EXPECT_EQ(items[0].filename, "filename3");
  16581. EXPECT_EQ(items[0].content_type, "");
  16582. EXPECT_EQ(items[1].name, "name4");
  16583. EXPECT_EQ(items[1].content, rand2);
  16584. EXPECT_EQ(items[1].filename, "filename4");
  16585. EXPECT_EQ(items[1].content_type, "");
  16586. });
  16587. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16588. const ContentReader &content_reader) {
  16589. ASSERT_TRUE(req.is_multipart_form_data());
  16590. std::vector<FormData> items;
  16591. content_reader(
  16592. [&](const FormData &file) {
  16593. items.push_back(file);
  16594. return true;
  16595. },
  16596. [&](const char *data, size_t data_length) {
  16597. items.back().content.append(data, data_length);
  16598. return true;
  16599. });
  16600. ASSERT_TRUE(items.size() == 4);
  16601. EXPECT_EQ(std::string(items[0].name), "name1");
  16602. EXPECT_EQ(items[0].content, "Testing123");
  16603. EXPECT_EQ(items[0].filename, "filename1");
  16604. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16605. EXPECT_EQ(items[1].name, "name2");
  16606. EXPECT_EQ(items[1].content, "Testing456");
  16607. EXPECT_EQ(items[1].filename, "");
  16608. EXPECT_EQ(items[1].content_type, "");
  16609. EXPECT_EQ(items[2].name, "name3");
  16610. EXPECT_EQ(items[2].content, rand1);
  16611. EXPECT_EQ(items[2].filename, "filename3");
  16612. EXPECT_EQ(items[2].content_type, "");
  16613. EXPECT_EQ(items[3].name, "name4");
  16614. EXPECT_EQ(items[3].content, rand2);
  16615. EXPECT_EQ(items[3].filename, "filename4");
  16616. EXPECT_EQ(items[3].content_type, "");
  16617. });
  16618. auto port = svr.bind_to_any_port("localhost");
  16619. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16620. auto se = detail::scope_exit([&] {
  16621. svr.stop();
  16622. t.join();
  16623. ASSERT_FALSE(svr.is_running());
  16624. });
  16625. svr.wait_until_ready();
  16626. {
  16627. SSLClient cli("localhost", port);
  16628. cli.enable_server_certificate_verification(false);
  16629. UploadFormDataItems items{
  16630. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16631. {"name2", "Testing456", "", ""}, // not a file
  16632. };
  16633. {
  16634. auto res = cli.Post("/post-none", {}, {}, {});
  16635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16636. ASSERT_EQ(StatusCode::OK_200, res->status);
  16637. }
  16638. FormDataProviderItems providers;
  16639. {
  16640. auto res =
  16641. cli.Post("/post-items", {}, items, providers); // empty providers
  16642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16643. ASSERT_EQ(StatusCode::OK_200, res->status);
  16644. }
  16645. providers.push_back({"name3",
  16646. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16647. // test the offset is given correctly at each step
  16648. if (!offset)
  16649. sink.os.write(rand1.data(), 30);
  16650. else if (offset == 30)
  16651. sink.os.write(rand1.data() + 30, 300);
  16652. else if (offset == 330)
  16653. sink.os.write(rand1.data() + 330, 670);
  16654. else if (offset == rand1.size())
  16655. sink.done();
  16656. return true;
  16657. },
  16658. "filename3",
  16659. {}});
  16660. providers.push_back({"name4",
  16661. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16662. // test the offset is given correctly at each step
  16663. if (!offset)
  16664. sink.os.write(rand2.data(), 2000);
  16665. else if (offset == 2000)
  16666. sink.os.write(rand2.data() + 2000, 1);
  16667. else if (offset == 2001)
  16668. sink.os.write(rand2.data() + 2001, 999);
  16669. else if (offset == rand2.size())
  16670. sink.done();
  16671. return true;
  16672. },
  16673. "filename4",
  16674. {}});
  16675. {
  16676. auto res = cli.Post("/post-providers", {}, {}, providers);
  16677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16678. ASSERT_EQ(StatusCode::OK_200, res->status);
  16679. }
  16680. {
  16681. auto res = cli.Post("/post-both", {}, items, providers);
  16682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16683. ASSERT_EQ(StatusCode::OK_200, res->status);
  16684. }
  16685. }
  16686. }
  16687. TEST(MultipartFormDataTest, BadHeader) {
  16688. Server svr;
  16689. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16690. res.set_content("ok", "text/plain");
  16691. });
  16692. thread t = thread([&] { svr.listen(HOST, PORT); });
  16693. auto se = detail::scope_exit([&] {
  16694. svr.stop();
  16695. t.join();
  16696. ASSERT_FALSE(svr.is_running());
  16697. });
  16698. svr.wait_until_ready();
  16699. const std::string body =
  16700. "This is the preamble. It is to be ignored, though it\r\n"
  16701. "is a handy place for composition agents to include an\r\n"
  16702. "explanatory note to non-MIME conformant readers.\r\n"
  16703. "\r\n"
  16704. "\r\n"
  16705. "--simple boundary\r\n"
  16706. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16707. ": BAD...\r\n"
  16708. "\r\n"
  16709. "value1\r\n"
  16710. "--simple boundary\r\n"
  16711. "Content-Disposition: form-data; name=\"field2\"; "
  16712. "filename=\"example.txt\"\r\n"
  16713. "\r\n"
  16714. "value2\r\n"
  16715. "--simple boundary--\r\n"
  16716. "This is the epilogue. It is also to be ignored.\r\n";
  16717. std::string content_type =
  16718. R"(multipart/form-data; boundary="simple boundary")";
  16719. Client cli(HOST, PORT);
  16720. auto res = cli.Post("/post", body, content_type.c_str());
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16723. }
  16724. TEST(MultipartFormDataTest, WithPreamble) {
  16725. Server svr;
  16726. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16727. res.set_content("ok", "text/plain");
  16728. });
  16729. thread t = thread([&] { svr.listen(HOST, PORT); });
  16730. auto se = detail::scope_exit([&] {
  16731. svr.stop();
  16732. t.join();
  16733. ASSERT_FALSE(svr.is_running());
  16734. });
  16735. svr.wait_until_ready();
  16736. const std::string body =
  16737. "This is the preamble. It is to be ignored, though it\r\n"
  16738. "is a handy place for composition agents to include an\r\n"
  16739. "explanatory note to non-MIME conformant readers.\r\n"
  16740. "\r\n"
  16741. "\r\n"
  16742. "--simple boundary\r\n"
  16743. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16744. "\r\n"
  16745. "value1\r\n"
  16746. "--simple boundary\r\n"
  16747. "Content-Disposition: form-data; name=\"field2\"; "
  16748. "filename=\"example.txt\"\r\n"
  16749. "\r\n"
  16750. "value2\r\n"
  16751. "--simple boundary--\r\n"
  16752. "This is the epilogue. It is also to be ignored.\r\n";
  16753. std::string content_type =
  16754. R"(multipart/form-data; boundary="simple boundary")";
  16755. Client cli(HOST, PORT);
  16756. auto res = cli.Post("/post", body, content_type.c_str());
  16757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16758. EXPECT_EQ(StatusCode::OK_200, res->status);
  16759. }
  16760. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16762. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16763. const ContentReader &content_reader) {
  16764. if (req.is_multipart_form_data()) {
  16765. std::vector<FormData> items;
  16766. content_reader(
  16767. [&](const FormData &file) {
  16768. items.push_back(file);
  16769. return true;
  16770. },
  16771. [&](const char *data, size_t data_length) {
  16772. items.back().content.append(data, data_length);
  16773. return true;
  16774. });
  16775. EXPECT_TRUE(std::string(items[0].name) == "document");
  16776. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16777. EXPECT_TRUE(items[0].filename == "2MB_data");
  16778. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16779. EXPECT_TRUE(items[1].name == "hello");
  16780. EXPECT_TRUE(items[1].content == "world");
  16781. EXPECT_TRUE(items[1].filename == "");
  16782. EXPECT_TRUE(items[1].content_type == "");
  16783. } else {
  16784. std::string body;
  16785. content_reader([&](const char *data, size_t data_length) {
  16786. body.append(data, data_length);
  16787. return true;
  16788. });
  16789. }
  16790. });
  16791. auto port = svr.bind_to_any_port("localhost");
  16792. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16793. auto se = detail::scope_exit([&] {
  16794. svr.stop();
  16795. t.join();
  16796. ASSERT_FALSE(svr.is_running());
  16797. });
  16798. svr.wait_until_ready();
  16799. {
  16800. std::string data(1024 * 1024 * 2, '.');
  16801. std::stringstream buffer;
  16802. buffer << data;
  16803. SSLClient cli("localhost", port);
  16804. cli.enable_server_certificate_verification(false);
  16805. UploadFormDataItems items{
  16806. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16807. {"hello", "world", "", ""},
  16808. };
  16809. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16811. ASSERT_EQ(StatusCode::OK_200, res->status);
  16812. }
  16813. }
  16814. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16815. std::string data(1024 * 1024 * 2, '&');
  16816. std::stringstream buffer;
  16817. buffer << data;
  16818. Client cli("https://localhost:8080");
  16819. UploadFormDataItems items{
  16820. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16821. {"hello", "world", "", ""},
  16822. };
  16823. for (const char &c : " \t\r\n") {
  16824. auto res =
  16825. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16826. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16827. ASSERT_FALSE(res);
  16828. }
  16829. }
  16830. TEST(MultipartFormDataTest, PutFormData) {
  16831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16832. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16833. const ContentReader &content_reader) {
  16834. if (req.is_multipart_form_data()) {
  16835. std::vector<FormData> items;
  16836. content_reader(
  16837. [&](const FormData &file) {
  16838. items.push_back(file);
  16839. return true;
  16840. },
  16841. [&](const char *data, size_t data_length) {
  16842. items.back().content.append(data, data_length);
  16843. return true;
  16844. });
  16845. EXPECT_TRUE(std::string(items[0].name) == "document");
  16846. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16847. EXPECT_TRUE(items[0].filename == "2MB_data");
  16848. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16849. EXPECT_TRUE(items[1].name == "hello");
  16850. EXPECT_TRUE(items[1].content == "world");
  16851. EXPECT_TRUE(items[1].filename == "");
  16852. EXPECT_TRUE(items[1].content_type == "");
  16853. } else {
  16854. std::string body;
  16855. content_reader([&](const char *data, size_t data_length) {
  16856. body.append(data, data_length);
  16857. return true;
  16858. });
  16859. }
  16860. });
  16861. auto port = svr.bind_to_any_port("localhost");
  16862. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16863. auto se = detail::scope_exit([&] {
  16864. svr.stop();
  16865. t.join();
  16866. ASSERT_FALSE(svr.is_running());
  16867. });
  16868. svr.wait_until_ready();
  16869. {
  16870. std::string data(1024 * 1024 * 2, '&');
  16871. std::stringstream buffer;
  16872. buffer << data;
  16873. SSLClient cli("localhost", port);
  16874. cli.enable_server_certificate_verification(false);
  16875. UploadFormDataItems items{
  16876. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16877. {"hello", "world", "", ""},
  16878. };
  16879. auto res = cli.Put("/put", items);
  16880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16881. ASSERT_EQ(StatusCode::OK_200, res->status);
  16882. }
  16883. }
  16884. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16886. svr.Put("/put_customboundary",
  16887. [&](const Request &req, const Response & /*res*/,
  16888. const ContentReader &content_reader) {
  16889. if (req.is_multipart_form_data()) {
  16890. std::vector<FormData> items;
  16891. content_reader(
  16892. [&](const FormData &file) {
  16893. items.push_back(file);
  16894. return true;
  16895. },
  16896. [&](const char *data, size_t data_length) {
  16897. items.back().content.append(data, data_length);
  16898. return true;
  16899. });
  16900. EXPECT_TRUE(std::string(items[0].name) == "document");
  16901. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16902. EXPECT_TRUE(items[0].filename == "2MB_data");
  16903. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16904. EXPECT_TRUE(items[1].name == "hello");
  16905. EXPECT_TRUE(items[1].content == "world");
  16906. EXPECT_TRUE(items[1].filename == "");
  16907. EXPECT_TRUE(items[1].content_type == "");
  16908. } else {
  16909. std::string body;
  16910. content_reader([&](const char *data, size_t data_length) {
  16911. body.append(data, data_length);
  16912. return true;
  16913. });
  16914. }
  16915. });
  16916. auto port = svr.bind_to_any_port("localhost");
  16917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16918. auto se = detail::scope_exit([&] {
  16919. svr.stop();
  16920. t.join();
  16921. ASSERT_FALSE(svr.is_running());
  16922. });
  16923. svr.wait_until_ready();
  16924. {
  16925. std::string data(1024 * 1024 * 2, '&');
  16926. std::stringstream buffer;
  16927. buffer << data;
  16928. SSLClient cli("localhost", port);
  16929. cli.enable_server_certificate_verification(false);
  16930. UploadFormDataItems items{
  16931. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16932. {"hello", "world", "", ""},
  16933. };
  16934. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16936. ASSERT_EQ(StatusCode::OK_200, res->status);
  16937. }
  16938. }
  16939. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16940. std::string data(1024 * 1024 * 2, '&');
  16941. std::stringstream buffer;
  16942. buffer << data;
  16943. Client cli("https://localhost:8080");
  16944. cli.enable_server_certificate_verification(false);
  16945. UploadFormDataItems items{
  16946. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16947. {"hello", "world", "", ""},
  16948. };
  16949. for (const char &c : " \t\r\n") {
  16950. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16951. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16952. ASSERT_FALSE(res);
  16953. }
  16954. }
  16955. TEST(MultipartFormDataTest, AlternateFilename) {
  16956. auto handled = false;
  16957. Server svr;
  16958. svr.Post("/test", [&](const Request &req, Response &res) {
  16959. ASSERT_EQ(2u, req.form.files.size());
  16960. ASSERT_EQ(1u, req.form.fields.size());
  16961. // Test files
  16962. const auto &file1 = req.form.get_file("file1");
  16963. ASSERT_EQ("file1", file1.name);
  16964. ASSERT_EQ("A.txt", file1.filename);
  16965. ASSERT_EQ("text/plain", file1.content_type);
  16966. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16967. const auto &file2 = req.form.get_file("file2");
  16968. ASSERT_EQ("file2", file2.name);
  16969. ASSERT_EQ("a.html", file2.filename);
  16970. ASSERT_EQ("text/html", file2.content_type);
  16971. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16972. file2.content);
  16973. // Test text field
  16974. const auto &text = req.form.get_field("text");
  16975. ASSERT_EQ("text default", text);
  16976. res.set_content("ok", "text/plain");
  16977. handled = true;
  16978. });
  16979. thread t = thread([&] { svr.listen(HOST, PORT); });
  16980. auto se = detail::scope_exit([&] {
  16981. svr.stop();
  16982. t.join();
  16983. ASSERT_FALSE(svr.is_running());
  16984. ASSERT_TRUE(handled);
  16985. });
  16986. svr.wait_until_ready();
  16987. auto req = "POST /test HTTP/1.1\r\n"
  16988. "Host: localhost\r\n"
  16989. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16990. "Content-Length: 399\r\n"
  16991. "\r\n"
  16992. "----------\r\n"
  16993. "Content-Disposition: form-data; name=\"text\"\r\n"
  16994. "\r\n"
  16995. "text default\r\n"
  16996. "----------\r\n"
  16997. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16998. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16999. "Content-Type: text/plain\r\n"
  17000. "\r\n"
  17001. "Content of a.txt.\r\n"
  17002. "\r\n"
  17003. "----------\r\n"
  17004. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17005. "\"a.html\"\r\n"
  17006. "Content-Type: text/html\r\n"
  17007. "\r\n"
  17008. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17009. "\r\n"
  17010. "------------\r\n";
  17011. ASSERT_TRUE(send_request(1, req));
  17012. }
  17013. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17014. auto handled = false;
  17015. Server svr;
  17016. svr.Post("/test", [&](const Request &req, Response &res) {
  17017. // Case-insensitive "utf-8''" prefix with a long value
  17018. const auto &file = req.form.get_file("file1");
  17019. ASSERT_EQ("file1", file.name);
  17020. // 8000 chars exercises both the Content-Disposition parser and the
  17021. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17022. // Prior to the fix, std::regex_match on this header would cause O(N)
  17023. // stack recursion in libstdc++, leading to SIGSEGV.
  17024. std::string expected_filename(8000, 'A');
  17025. ASSERT_EQ(expected_filename, file.filename);
  17026. res.set_content("ok", "text/plain");
  17027. handled = true;
  17028. });
  17029. thread t = thread([&] { svr.listen(HOST, PORT); });
  17030. auto se = detail::scope_exit([&] {
  17031. svr.stop();
  17032. t.join();
  17033. ASSERT_FALSE(svr.is_running());
  17034. ASSERT_TRUE(handled);
  17035. });
  17036. svr.wait_until_ready();
  17037. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17038. // Regression test for GHSA-qq6v-r583-3h69
  17039. std::string long_filename(8000, 'A');
  17040. std::string body = "----------\r\n"
  17041. "Content-Disposition: form-data; name=\"file1\"; "
  17042. "filename*=\"Utf-8''" +
  17043. long_filename +
  17044. "\"\r\n"
  17045. "\r\n"
  17046. "hello\r\n"
  17047. "------------\r\n";
  17048. auto req = "POST /test HTTP/1.1\r\n"
  17049. "Host: localhost\r\n"
  17050. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17051. "Content-Length: " +
  17052. std::to_string(body.size()) + "\r\n\r\n" + body;
  17053. ASSERT_TRUE(send_request(1, req));
  17054. }
  17055. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17056. auto handled = false;
  17057. Server svr;
  17058. svr.Post("/test", [&](const Request &req, Response &) {
  17059. ASSERT_EQ(2u, req.form.fields.size());
  17060. const auto &text1 = req.form.get_field("text1");
  17061. ASSERT_EQ("text1", text1);
  17062. const auto &text2 = req.form.get_field("text2");
  17063. ASSERT_EQ("text2", text2);
  17064. handled = true;
  17065. });
  17066. thread t = thread([&] { svr.listen(HOST, PORT); });
  17067. auto se = detail::scope_exit([&] {
  17068. svr.stop();
  17069. t.join();
  17070. ASSERT_FALSE(svr.is_running());
  17071. ASSERT_TRUE(handled);
  17072. });
  17073. svr.wait_until_ready();
  17074. auto req = "POST /test HTTP/1.1\r\n"
  17075. "Host: localhost\r\n"
  17076. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17077. "Content-Length: 146\r\n"
  17078. "\r\n----------\r\n"
  17079. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17080. "\r\n"
  17081. "text1"
  17082. "\r\n----------\r\n"
  17083. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17084. "\r\n"
  17085. "text2"
  17086. "\r\n------------";
  17087. std::string response;
  17088. ASSERT_TRUE(send_request(1, req, &response));
  17089. ASSERT_EQ("200", response.substr(9, 3));
  17090. }
  17091. TEST(MultipartFormDataTest, ContentLength) {
  17092. auto handled = false;
  17093. Server svr;
  17094. svr.Post("/test", [&](const Request &req, Response &) {
  17095. ASSERT_EQ(2u, req.form.fields.size());
  17096. const auto &text1 = req.form.get_field("text1");
  17097. ASSERT_EQ("text1", text1);
  17098. const auto &text2 = req.form.get_field("text2");
  17099. ASSERT_EQ("text2", text2);
  17100. handled = true;
  17101. });
  17102. thread t = thread([&] { svr.listen(HOST, PORT); });
  17103. auto se = detail::scope_exit([&] {
  17104. svr.stop();
  17105. t.join();
  17106. ASSERT_FALSE(svr.is_running());
  17107. ASSERT_TRUE(handled);
  17108. });
  17109. svr.wait_until_ready();
  17110. auto req = "POST /test HTTP/1.1\r\n"
  17111. "Host: localhost\r\n"
  17112. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17113. "Content-Length: 167\r\n"
  17114. "\r\n----------\r\n"
  17115. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17116. "Content-Length: 5\r\n"
  17117. "\r\n"
  17118. "text1"
  17119. "\r\n----------\r\n"
  17120. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17121. "\r\n"
  17122. "text2"
  17123. "\r\n------------\r\n";
  17124. std::string response;
  17125. ASSERT_TRUE(send_request(1, req, &response));
  17126. ASSERT_EQ("200", response.substr(9, 3));
  17127. }
  17128. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17129. auto handled = false;
  17130. Server svr;
  17131. svr.Post("/test", [&](const Request &req, Response &) {
  17132. ASSERT_EQ(2u, req.form.fields.size());
  17133. const auto &text1 = req.form.get_field("text1");
  17134. ASSERT_EQ("text1", text1);
  17135. // TODO: Add header access for text fields if needed
  17136. const auto &text2 = req.form.get_field("text2");
  17137. ASSERT_EQ("text2", text2);
  17138. // TODO: Header access for text fields needs to be implemented
  17139. // auto &headers = it->second.headers;
  17140. // ASSERT_EQ(3U, headers.size());
  17141. // auto custom_header = headers.find("x-whatever");
  17142. // ASSERT_TRUE(custom_header != headers.end());
  17143. // ASSERT_NE("customvalue", custom_header->second);
  17144. // ASSERT_EQ("CustomValue", custom_header->second);
  17145. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17146. handled = true;
  17147. });
  17148. thread t = thread([&] { svr.listen(HOST, PORT); });
  17149. auto se = detail::scope_exit([&] {
  17150. svr.stop();
  17151. t.join();
  17152. ASSERT_FALSE(svr.is_running());
  17153. ASSERT_TRUE(handled);
  17154. });
  17155. svr.wait_until_ready();
  17156. auto req = "POST /test HTTP/1.1\r\n"
  17157. "Host: localhost\r\n"
  17158. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17159. "Content-Length: 232\r\n"
  17160. "\r\n----------\r\n"
  17161. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17162. "Content-Length: 5\r\n"
  17163. "X-Test: 1\r\n"
  17164. "\r\n"
  17165. "text1"
  17166. "\r\n----------\r\n"
  17167. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17168. "Content-Type: text/plain\r\n"
  17169. "X-Whatever: CustomValue\r\n"
  17170. "\r\n"
  17171. "text2"
  17172. "\r\n------------\r\n"
  17173. "That should be disregarded. Not even read";
  17174. std::string response;
  17175. ASSERT_TRUE(send_request(1, req, &response));
  17176. ASSERT_EQ("200", response.substr(9, 3));
  17177. }
  17178. TEST(MultipartFormDataTest, LargeHeader) {
  17179. auto handled = false;
  17180. Server svr;
  17181. svr.Post("/test", [&](const Request &req, Response &) {
  17182. ASSERT_EQ(1u, req.form.fields.size());
  17183. const auto &text = req.form.get_field("name1");
  17184. ASSERT_EQ("text1", text);
  17185. handled = true;
  17186. });
  17187. thread t = thread([&] { svr.listen(HOST, PORT); });
  17188. auto se = detail::scope_exit([&] {
  17189. svr.stop();
  17190. t.join();
  17191. ASSERT_FALSE(svr.is_running());
  17192. ASSERT_TRUE(handled);
  17193. });
  17194. svr.wait_until_ready();
  17195. auto boundary = std::string("cpp-httplib-multipart-data");
  17196. std::string content = "--" + boundary +
  17197. "\r\n"
  17198. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17199. "\r\n"
  17200. "text1\r\n"
  17201. "--" +
  17202. boundary + "--\r\n";
  17203. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17204. "Host: localhost\r\n"
  17205. "Content-Type: multipart/form-data;boundary=" +
  17206. boundary +
  17207. "\r\n"
  17208. "Content-Length: " +
  17209. std::to_string(content.size()) +
  17210. "\r\n"
  17211. "Dummy-Header: ";
  17212. std::string header_suffix = "\r\n"
  17213. "\r\n";
  17214. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17215. size_t header_dummy_size =
  17216. read_buff_size -
  17217. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17218. auto header_dummy = std::string(header_dummy_size, '@');
  17219. auto req = header_prefix + header_dummy + header_suffix + content;
  17220. std::string response;
  17221. ASSERT_TRUE(send_request(1, req, &response));
  17222. ASSERT_EQ("200", response.substr(9, 3));
  17223. }
  17224. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17225. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17226. // (not chunked Transfer-Encoding) after the streaming refactor.
  17227. auto handled = false;
  17228. Server svr;
  17229. svr.Post("/upload", [&](const Request &req, Response &res) {
  17230. auto cl_it = req.headers.find("Content-Length");
  17231. EXPECT_TRUE(cl_it != req.headers.end());
  17232. auto te_it = req.headers.find("Transfer-Encoding");
  17233. EXPECT_TRUE(te_it == req.headers.end());
  17234. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17235. res.set_content("ok", "text/plain");
  17236. handled = true;
  17237. });
  17238. auto port = svr.bind_to_any_port(HOST);
  17239. auto t = thread([&] { svr.listen_after_bind(); });
  17240. auto se = detail::scope_exit([&] {
  17241. svr.stop();
  17242. t.join();
  17243. ASSERT_FALSE(svr.is_running());
  17244. ASSERT_TRUE(handled);
  17245. });
  17246. svr.wait_until_ready();
  17247. UploadFormDataItems items = {
  17248. {"field1", "hello", "", "text/plain"},
  17249. {"file1", "world", "test.txt", "application/octet-stream"},
  17250. };
  17251. Client cli(HOST, port);
  17252. auto res = cli.Post("/upload", {}, items);
  17253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17254. EXPECT_EQ(StatusCode::OK_200, res->status);
  17255. }
  17256. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17257. // Verify that make_multipart_content_provider coalesces many small segments
  17258. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17259. constexpr size_t kItemCount = 1000;
  17260. UploadFormDataItems items;
  17261. items.reserve(kItemCount);
  17262. for (size_t i = 0; i < kItemCount; i++) {
  17263. items.push_back(
  17264. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17265. }
  17266. const std::string boundary = "----test-boundary";
  17267. auto content_length = detail::get_multipart_content_length(items, boundary);
  17268. auto provider = detail::make_multipart_content_provider(items, boundary);
  17269. // Drive the provider the same way write_content_with_progress does
  17270. size_t write_count = 0;
  17271. size_t total_bytes = 0;
  17272. DataSink sink;
  17273. size_t offset = 0;
  17274. sink.write = [&](const char *d, size_t l) -> bool {
  17275. (void)d;
  17276. write_count++;
  17277. total_bytes += l;
  17278. offset += l;
  17279. return true;
  17280. };
  17281. sink.is_writable = []() -> bool { return true; };
  17282. while (offset < content_length) {
  17283. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17284. }
  17285. EXPECT_EQ(content_length, total_bytes);
  17286. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17287. // With buffering into 64KB blocks, write_count should be much smaller.
  17288. auto segment_count = 3 * kItemCount + 1;
  17289. EXPECT_LT(write_count, segment_count / 10);
  17290. }
  17291. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17292. // Integration test: send many UploadFormDataItems and verify the server
  17293. // receives all of them correctly (#2410).
  17294. constexpr size_t kItemCount = 500;
  17295. auto handled = false;
  17296. Server svr;
  17297. svr.Post("/upload", [&](const Request &req, Response &res) {
  17298. EXPECT_EQ(kItemCount, req.form.fields.size());
  17299. for (size_t i = 0; i < kItemCount; i++) {
  17300. auto key = "field" + std::to_string(i);
  17301. auto val = "value" + std::to_string(i);
  17302. auto it = req.form.fields.find(key);
  17303. if (it != req.form.fields.end()) {
  17304. EXPECT_EQ(val, it->second.content);
  17305. } else {
  17306. ADD_FAILURE() << "Missing field: " << key;
  17307. }
  17308. }
  17309. res.set_content("ok", "text/plain");
  17310. handled = true;
  17311. });
  17312. auto port = svr.bind_to_any_port(HOST);
  17313. auto t = thread([&] { svr.listen_after_bind(); });
  17314. auto se = detail::scope_exit([&] {
  17315. svr.stop();
  17316. t.join();
  17317. ASSERT_FALSE(svr.is_running());
  17318. ASSERT_TRUE(handled);
  17319. });
  17320. svr.wait_until_ready();
  17321. UploadFormDataItems items;
  17322. items.reserve(kItemCount);
  17323. for (size_t i = 0; i < kItemCount; i++) {
  17324. items.push_back(
  17325. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17326. }
  17327. Client cli(HOST, port);
  17328. auto res = cli.Post("/upload", items);
  17329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17330. EXPECT_EQ(StatusCode::OK_200, res->status);
  17331. }
  17332. TEST(MultipartFormDataTest, MakeFileProvider) {
  17333. // Verify make_file_provider sends a file's contents correctly.
  17334. const std::string file_content(4096, 'Z');
  17335. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17336. {
  17337. std::ofstream ofs(tmp_path, std::ios::binary);
  17338. ofs.write(file_content.data(),
  17339. static_cast<std::streamsize>(file_content.size()));
  17340. }
  17341. auto handled = false;
  17342. Server svr;
  17343. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17344. const ContentReader &content_reader) {
  17345. ASSERT_TRUE(req.is_multipart_form_data());
  17346. std::vector<FormData> items;
  17347. content_reader(
  17348. [&](const FormData &file) {
  17349. items.push_back(file);
  17350. return true;
  17351. },
  17352. [&](const char *data, size_t data_length) {
  17353. items.back().content.append(data, data_length);
  17354. return true;
  17355. });
  17356. ASSERT_EQ(1u, items.size());
  17357. EXPECT_EQ("myfile", items[0].name);
  17358. EXPECT_EQ("data.bin", items[0].filename);
  17359. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17360. EXPECT_EQ(file_content, items[0].content);
  17361. handled = true;
  17362. });
  17363. auto port = svr.bind_to_any_port(HOST);
  17364. auto t = thread([&] { svr.listen_after_bind(); });
  17365. auto se = detail::scope_exit([&] {
  17366. svr.stop();
  17367. t.join();
  17368. ASSERT_FALSE(svr.is_running());
  17369. ASSERT_TRUE(handled);
  17370. std::remove(tmp_path.c_str());
  17371. });
  17372. svr.wait_until_ready();
  17373. FormDataProviderItems providers;
  17374. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17375. "application/octet-stream"));
  17376. Client cli(HOST, port);
  17377. auto res = cli.Post("/upload", {}, {}, providers);
  17378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17379. EXPECT_EQ(StatusCode::OK_200, res->status);
  17380. }
  17381. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17382. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17383. // (100) headers is rejected with a 400 Bad Request response.
  17384. Server svr;
  17385. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17386. res.set_content("ok", "text/plain");
  17387. });
  17388. thread t = thread([&] { svr.listen(HOST, PORT); });
  17389. auto se = detail::scope_exit([&] {
  17390. svr.stop();
  17391. t.join();
  17392. ASSERT_FALSE(svr.is_running());
  17393. });
  17394. svr.wait_until_ready();
  17395. // Build a multipart part with 101 custom headers (exceeding
  17396. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17397. std::stringstream body;
  17398. body << "--simpleboundary\r\n"
  17399. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17400. for (int i = 0; i < 101; i++) {
  17401. body << "X-Custom-Header-" << i << ": value\r\n";
  17402. }
  17403. body << "\r\n"
  17404. << "value1\r\n"
  17405. << "--simpleboundary--\r\n";
  17406. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17407. Client cli(HOST, PORT);
  17408. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17410. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17411. }
  17412. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17413. // A body that never contains the declared boundary must not be accumulated
  17414. // while the parser waits for it. Buffering it would also make every read
  17415. // rescan everything seen so far, which is quadratic in the body size.
  17416. Server svr;
  17417. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17418. res.set_content("ok", "text/plain");
  17419. });
  17420. auto port = svr.bind_to_any_port(HOST);
  17421. thread t = thread([&] { svr.listen_after_bind(); });
  17422. auto se = detail::scope_exit([&] {
  17423. svr.stop();
  17424. t.join();
  17425. ASSERT_FALSE(svr.is_running());
  17426. });
  17427. svr.wait_until_ready();
  17428. Client cli(HOST, port);
  17429. cli.set_read_timeout(60, 0);
  17430. cli.set_write_timeout(60, 0);
  17431. // '-' is the worst case: it matches the first character of the boundary, so
  17432. // every position has to be checked against it.
  17433. auto post_dashes = [&](size_t size) {
  17434. const std::string body(size, '-');
  17435. auto start = std::chrono::steady_clock::now();
  17436. auto res =
  17437. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17438. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17439. std::chrono::steady_clock::now() - start)
  17440. .count();
  17441. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17442. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17443. return ms;
  17444. };
  17445. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17446. // Windows.
  17447. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17448. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17449. // Comparing the two sizes rather than checking an absolute duration keeps
  17450. // this meaningful across build types and CI load, both of which move the
  17451. // absolute numbers by more than an order of magnitude. Four times the bytes
  17452. // costs about four times the time when parsing is linear, and about sixteen
  17453. // times when the body is buffered and rescanned.
  17454. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17455. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17456. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17457. << "ms, which suggests the body is being buffered and rescanned";
  17458. }
  17459. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17460. // A boundary can only be followed by CRLF or by "--", so anything else is
  17461. // malformed no matter what comes next. The parser must say so right away
  17462. // instead of buffering the rest of the declared body.
  17463. Server svr;
  17464. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17465. res.set_content("ok", "text/plain");
  17466. });
  17467. auto port = svr.bind_to_any_port(HOST);
  17468. thread t = thread([&] { svr.listen_after_bind(); });
  17469. auto se = detail::scope_exit([&] {
  17470. svr.stop();
  17471. t.join();
  17472. ASSERT_FALSE(svr.is_running());
  17473. });
  17474. svr.wait_until_ready();
  17475. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17476. // buffers instead of failing would still be waiting for the remaining bytes.
  17477. const std::string body = "--zzzz\r\n"
  17478. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17479. "\r\n"
  17480. "text1"
  17481. "\r\n--zzzzXX";
  17482. const std::string req = "POST /post HTTP/1.1\r\n"
  17483. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17484. "Content-Length: 1048576\r\n"
  17485. "\r\n" +
  17486. body;
  17487. std::string response;
  17488. ASSERT_TRUE(send_request(3, req, &response, port));
  17489. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17490. EXPECT_EQ("400", response.substr(9, 3));
  17491. }
  17492. // Posts a multipart body split into two writes, so that the server sees the
  17493. // split at whatever offset the caller chose, and expects the single "text1"
  17494. // field to come through.
  17495. static void expect_split_multipart_ok(const std::string &body1,
  17496. const std::string &body2) {
  17497. auto handled = false;
  17498. Server svr;
  17499. svr.Post("/post", [&](const Request &req, Response &) {
  17500. EXPECT_EQ(1u, req.form.fields.size());
  17501. EXPECT_EQ("text1", req.form.get_field("text1"));
  17502. handled = true;
  17503. });
  17504. auto port = svr.bind_to_any_port(HOST);
  17505. thread t = thread([&] { svr.listen_after_bind(); });
  17506. auto se = detail::scope_exit([&] {
  17507. svr.stop();
  17508. t.join();
  17509. ASSERT_FALSE(svr.is_running());
  17510. ASSERT_TRUE(handled);
  17511. });
  17512. svr.wait_until_ready();
  17513. // "Connection: close" makes the server close once it has answered, so the
  17514. // response drain ends immediately instead of idling until the read timeout.
  17515. const std::string head =
  17516. "POST /post HTTP/1.1\r\n"
  17517. "Host: localhost\r\n"
  17518. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17519. "Connection: close\r\n"
  17520. "Content-Length: " +
  17521. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17522. std::string response;
  17523. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17524. ASSERT_GE(response.size(), 12u) << "no response";
  17525. EXPECT_EQ("200", response.substr(9, 3));
  17526. }
  17527. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17528. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17529. // ignored, including when it does not arrive in the same read as the
  17530. // close-delimiter itself.
  17531. expect_split_multipart_ok("--zzzz\r\n"
  17532. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17533. "\r\n"
  17534. "text1"
  17535. "\r\n--zzzz--",
  17536. "\r\nthis epilogue must be ignored\r\n");
  17537. }
  17538. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17539. // The initial boundary may be preceded by a preamble of any length and may
  17540. // straddle a read boundary. Discarding data while waiting for it must not
  17541. // throw away a partial boundary sitting at the end of the buffer.
  17542. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17543. "zz\r\n"
  17544. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17545. "\r\n"
  17546. "text1"
  17547. "\r\n--zzzz--\r\n");
  17548. }
  17549. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17550. // The received boundary was only checked for being non-empty, so it could be
  17551. // as long as a header is allowed to be. The parser scans the body for
  17552. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17553. // costs a nearly full comparison at nearly every position, making the
  17554. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17555. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17556. Server svr;
  17557. svr.Post("/post", [](const Request &req, Response &res) {
  17558. EXPECT_EQ(1u, req.form.fields.size());
  17559. EXPECT_EQ("text1", req.form.get_field("text1"));
  17560. res.set_content("ok", "text/plain");
  17561. });
  17562. auto port = svr.bind_to_any_port(HOST);
  17563. thread t = thread([&] { svr.listen_after_bind(); });
  17564. auto se = detail::scope_exit([&] {
  17565. svr.stop();
  17566. t.join();
  17567. ASSERT_FALSE(svr.is_running());
  17568. });
  17569. svr.wait_until_ready();
  17570. Client cli(HOST, port);
  17571. auto post_with_boundary_of_length = [&](size_t len) {
  17572. const std::string boundary(len, 'a');
  17573. const std::string body =
  17574. "--" + boundary +
  17575. "\r\n"
  17576. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17577. "\r\n"
  17578. "text1"
  17579. "\r\n--" +
  17580. boundary + "--\r\n";
  17581. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17582. };
  17583. auto res = post_with_boundary_of_length(70);
  17584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17585. EXPECT_EQ(StatusCode::OK_200, res->status);
  17586. res = post_with_boundary_of_length(71);
  17587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17588. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17589. }
  17590. TEST(MakeFileBodyTest, Basic) {
  17591. const std::string file_content(4096, 'Z');
  17592. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17593. {
  17594. std::ofstream ofs(tmp_path, std::ios::binary);
  17595. ofs.write(file_content.data(),
  17596. static_cast<std::streamsize>(file_content.size()));
  17597. }
  17598. auto handled = false;
  17599. Server svr;
  17600. svr.Post("/upload", [&](const Request &req, Response &res) {
  17601. EXPECT_EQ(file_content, req.body);
  17602. handled = true;
  17603. res.status = StatusCode::OK_200;
  17604. });
  17605. auto port = svr.bind_to_any_port(HOST);
  17606. auto t = thread([&] { svr.listen_after_bind(); });
  17607. auto se = detail::scope_exit([&] {
  17608. svr.stop();
  17609. t.join();
  17610. ASSERT_FALSE(svr.is_running());
  17611. ASSERT_TRUE(handled);
  17612. std::remove(tmp_path.c_str());
  17613. });
  17614. svr.wait_until_ready();
  17615. auto fb = make_file_body(tmp_path);
  17616. ASSERT_GT(fb.first, 0u);
  17617. Client cli(HOST, port);
  17618. auto res =
  17619. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17621. EXPECT_EQ(StatusCode::OK_200, res->status);
  17622. }
  17623. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17624. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17625. {
  17626. std::ofstream ofs(path, std::ios::binary);
  17627. const std::string content(100, 'A');
  17628. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17629. }
  17630. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17631. auto body = make_file_body(path);
  17632. ASSERT_EQ(100u, body.first);
  17633. ASSERT_TRUE(static_cast<bool>(body.second));
  17634. // Rewritten shorter after its length was measured - and, on a server, after
  17635. // that length has already gone out as Content-Length.
  17636. {
  17637. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17638. const std::string content(10, 'A');
  17639. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17640. }
  17641. std::string written;
  17642. DataSink sink;
  17643. sink.write = [&](const char *d, size_t l) {
  17644. written.append(d, l);
  17645. return true;
  17646. };
  17647. // The provider has to report failure. write_content_with_progress() advances
  17648. // its offset only by what was written, so a provider that returns true
  17649. // without completing the length it promised is called again straight away,
  17650. // and again.
  17651. EXPECT_FALSE(body.second(0, body.first, sink));
  17652. EXPECT_EQ(std::string(10, 'A'), written);
  17653. }
  17654. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17655. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17656. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17657. {
  17658. std::ofstream ofs(path, std::ios::binary);
  17659. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17660. }
  17661. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17662. auto body = make_file_body(path);
  17663. ASSERT_EQ(content.size(), body.first);
  17664. ASSERT_TRUE(static_cast<bool>(body.second));
  17665. std::string written;
  17666. DataSink sink;
  17667. sink.write = [&](const char *d, size_t l) {
  17668. written.append(d, l);
  17669. return true;
  17670. };
  17671. EXPECT_TRUE(body.second(0, body.first, sink));
  17672. EXPECT_EQ(content, written);
  17673. }
  17674. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17675. static constexpr unsigned int number_of_tasks{1000000};
  17676. std::atomic_uint count{0};
  17677. std::unique_ptr<TaskQueue> task_queue{
  17678. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17679. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17680. auto queued = task_queue->enqueue(
  17681. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17682. EXPECT_TRUE(queued);
  17683. }
  17684. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17685. task_queue->shutdown();
  17686. #else
  17687. EXPECT_NO_THROW(task_queue->shutdown());
  17688. #endif
  17689. EXPECT_EQ(number_of_tasks, count.load());
  17690. }
  17691. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17692. static constexpr unsigned int number_of_tasks{1000000};
  17693. static constexpr unsigned int qlimit{2};
  17694. unsigned int queued_count{0};
  17695. std::atomic_uint count{0};
  17696. std::unique_ptr<TaskQueue> task_queue{
  17697. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17698. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17699. if (task_queue->enqueue(
  17700. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17701. queued_count++;
  17702. }
  17703. }
  17704. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17705. task_queue->shutdown();
  17706. #else
  17707. EXPECT_NO_THROW(task_queue->shutdown());
  17708. #endif
  17709. EXPECT_EQ(queued_count, count.load());
  17710. EXPECT_TRUE(queued_count <= number_of_tasks);
  17711. EXPECT_TRUE(queued_count >= qlimit);
  17712. }
  17713. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17714. // Use a short idle timeout so a dynamic thread spawns, times out and
  17715. // exits during the test, and the pool keeps working afterwards.
  17716. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17717. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17718. /*idle_timeout_sec=*/1}};
  17719. std::atomic_uint count{0};
  17720. std::condition_variable cv;
  17721. std::mutex mtx;
  17722. bool release = false;
  17723. // Block the base thread so the second task spawns a dynamic thread.
  17724. EXPECT_TRUE(task_queue->enqueue([&] {
  17725. std::unique_lock<std::mutex> lock(mtx);
  17726. while (!release) {
  17727. cv.wait(lock);
  17728. }
  17729. count++;
  17730. }));
  17731. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17732. // Let the dynamic thread finish its task and exceed the idle timeout.
  17733. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17734. {
  17735. std::unique_lock<std::mutex> lock(mtx);
  17736. release = true;
  17737. }
  17738. cv.notify_all();
  17739. // The pool must still accept and run tasks after the dynamic thread exited.
  17740. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17741. task_queue->shutdown();
  17742. EXPECT_EQ(3u, count.load());
  17743. }
  17744. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17745. static constexpr size_t number_of_tasks{32};
  17746. std::unique_ptr<TaskQueue> task_queue{
  17747. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17748. // Let the base threads go idle so the burst below finds them waiting.
  17749. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17750. std::mutex mtx;
  17751. std::condition_variable cv;
  17752. size_t running = 0;
  17753. bool release = false;
  17754. for (size_t i = 0; i < number_of_tasks; i++) {
  17755. EXPECT_TRUE(task_queue->enqueue([&] {
  17756. std::unique_lock<std::mutex> lock(mtx);
  17757. running++;
  17758. cv.notify_all();
  17759. cv.wait(lock, [&] { return release; });
  17760. }));
  17761. }
  17762. {
  17763. std::unique_lock<std::mutex> lock(mtx);
  17764. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17765. [&] { return running == number_of_tasks; }));
  17766. release = true;
  17767. }
  17768. cv.notify_all();
  17769. task_queue->shutdown();
  17770. }
  17771. TEST(TaskQueueTest, MaxQueuedRequests) {
  17772. static constexpr unsigned int qlimit{3};
  17773. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17774. std::condition_variable sem_cv;
  17775. std::mutex sem_mtx;
  17776. int credits = 0;
  17777. bool queued;
  17778. /* Fill up the queue with tasks that will block until we give them credits to
  17779. * complete. */
  17780. for (unsigned int n = 0; n <= qlimit;) {
  17781. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17782. std::unique_lock<std::mutex> lock(sem_mtx);
  17783. while (credits <= 0) {
  17784. sem_cv.wait(lock);
  17785. }
  17786. /* Consume the credit and signal the test code if they are all gone. */
  17787. if (--credits == 0) { sem_cv.notify_one(); }
  17788. });
  17789. if (n < qlimit) {
  17790. /* The first qlimit enqueues must succeed. */
  17791. EXPECT_TRUE(queued);
  17792. } else {
  17793. /* The last one will succeed only when the worker thread
  17794. * starts and dequeues the first blocking task. Although
  17795. * not necessary for the correctness of this test, we sleep for
  17796. * a short while to avoid busy waiting. */
  17797. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17798. }
  17799. if (queued) { n++; }
  17800. }
  17801. /* Further enqueues must fail since the queue is full. */
  17802. for (auto i = 0; i < 4; i++) {
  17803. queued = task_queue->enqueue([] {});
  17804. EXPECT_FALSE(queued);
  17805. }
  17806. /* Give the credits to allow the previous tasks to complete. */
  17807. {
  17808. std::unique_lock<std::mutex> lock(sem_mtx);
  17809. credits += qlimit + 1;
  17810. }
  17811. sem_cv.notify_all();
  17812. /* Wait for all the credits to be consumed. */
  17813. {
  17814. std::unique_lock<std::mutex> lock(sem_mtx);
  17815. while (credits > 0) {
  17816. sem_cv.wait(lock);
  17817. }
  17818. }
  17819. /* Check that we are able again to enqueue at least qlimit tasks. */
  17820. for (unsigned int i = 0; i < qlimit; i++) {
  17821. queued = task_queue->enqueue([] {});
  17822. EXPECT_TRUE(queued);
  17823. }
  17824. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17825. task_queue->shutdown();
  17826. #else
  17827. EXPECT_NO_THROW(task_queue->shutdown());
  17828. #endif
  17829. }
  17830. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17831. Server svr;
  17832. std::string method;
  17833. std::string body;
  17834. auto has_content_length = false;
  17835. auto has_transfer_encoding = false;
  17836. std::atomic<int> bad_requests{0};
  17837. // Leftover body bytes get parsed as a malformed request and answered with
  17838. // 400
  17839. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17840. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17841. });
  17842. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17843. res.set_redirect("/down", StatusCode::SeeOther_303);
  17844. });
  17845. svr.Get("/down", [&](const Request &req, Response &res) {
  17846. method = req.method;
  17847. body = req.body;
  17848. has_content_length = req.has_header("Content-Length");
  17849. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17850. res.set_content("ok", "text/plain");
  17851. });
  17852. auto port = svr.bind_to_any_port(HOST);
  17853. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17854. auto se = detail::scope_exit([&] {
  17855. svr.stop();
  17856. thread.join();
  17857. ASSERT_FALSE(svr.is_running());
  17858. });
  17859. svr.wait_until_ready();
  17860. const std::string payload = "SECRET-BODY";
  17861. auto check = [&](Client &cli, const Result &res) {
  17862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17863. EXPECT_EQ(StatusCode::OK_200, res->status);
  17864. EXPECT_EQ("ok", res->body);
  17865. EXPECT_EQ("GET", method);
  17866. EXPECT_TRUE(body.empty());
  17867. EXPECT_FALSE(has_content_length);
  17868. EXPECT_FALSE(has_transfer_encoding);
  17869. // Nothing of the original body may be left on the connection
  17870. auto res2 = cli.Get("/down");
  17871. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17872. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17873. EXPECT_EQ("ok", res2->body);
  17874. EXPECT_EQ(0, bad_requests);
  17875. };
  17876. // With content length
  17877. {
  17878. Client cli(HOST, port);
  17879. cli.set_keep_alive(true);
  17880. cli.set_follow_location(true);
  17881. auto res = cli.Post(
  17882. "/up", payload.size(),
  17883. [&](size_t offset, size_t length, DataSink &sink) {
  17884. return sink.write(payload.data() + offset, length);
  17885. },
  17886. "text/plain");
  17887. check(cli, res);
  17888. }
  17889. // Without content length (chunked)
  17890. {
  17891. Client cli(HOST, port);
  17892. cli.set_keep_alive(true);
  17893. cli.set_follow_location(true);
  17894. auto res = cli.Post(
  17895. "/up",
  17896. [&](size_t /*offset*/, DataSink &sink) {
  17897. sink.write(payload.data(), payload.size());
  17898. sink.done();
  17899. return true;
  17900. },
  17901. "text/plain");
  17902. check(cli, res);
  17903. }
  17904. }
  17905. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17906. Server svr;
  17907. std::string target;
  17908. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17909. // Echo the still-encoded name back in the Location
  17910. const std::string prefix = "/start/";
  17911. res.status = StatusCode::Found_302;
  17912. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17913. });
  17914. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17915. target = req.target;
  17916. res.set_content("ok", "text/plain");
  17917. });
  17918. auto port = svr.bind_to_any_port(HOST);
  17919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17920. auto se = detail::scope_exit([&] {
  17921. svr.stop();
  17922. thread.join();
  17923. ASSERT_FALSE(svr.is_running());
  17924. });
  17925. svr.wait_until_ready();
  17926. // Decoding the Location path would turn the first four into a path
  17927. // separator, a query delimiter, a fragment delimiter and a different
  17928. // percent-encoded octet. The rest must keep reaching the server as they are.
  17929. const std::vector<std::string> names = {
  17930. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17931. };
  17932. for (auto path_encode : {true, false}) {
  17933. Client cli(HOST, port);
  17934. cli.set_follow_location(true);
  17935. cli.set_path_encode(path_encode);
  17936. for (const auto &name : names) {
  17937. target.clear();
  17938. auto res = cli.Get("/start/" + name);
  17939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17940. EXPECT_EQ(StatusCode::OK_200, res->status);
  17941. EXPECT_EQ("/dest/" + name, target);
  17942. }
  17943. }
  17944. }
  17945. TEST(RedirectTest, NotModifiedIsReturned) {
  17946. Server svr;
  17947. svr.Get("/cached", [](const Request &, Response &res) {
  17948. res.status = StatusCode::NotModified_304;
  17949. });
  17950. auto port = svr.bind_to_any_port(HOST);
  17951. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17952. auto se = detail::scope_exit([&] {
  17953. svr.stop();
  17954. thread.join();
  17955. ASSERT_FALSE(svr.is_running());
  17956. });
  17957. svr.wait_until_ready();
  17958. Client cli(HOST, port);
  17959. cli.set_follow_location(true);
  17960. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17962. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17963. }
  17964. TEST(RedirectTest, NoLocationIsReturned) {
  17965. Server svr;
  17966. svr.Get("/no-location", [](const Request &, Response &res) {
  17967. res.status = StatusCode::Found_302;
  17968. res.set_content("no location", "text/plain");
  17969. });
  17970. auto port = svr.bind_to_any_port(HOST);
  17971. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17972. auto se = detail::scope_exit([&] {
  17973. svr.stop();
  17974. thread.join();
  17975. ASSERT_FALSE(svr.is_running());
  17976. });
  17977. svr.wait_until_ready();
  17978. Client cli(HOST, port);
  17979. cli.set_follow_location(true);
  17980. auto res = cli.Get("/no-location");
  17981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17982. EXPECT_EQ(StatusCode::Found_302, res->status);
  17983. EXPECT_EQ("no location", res->body);
  17984. // The callbacks see the body of the response that is returned
  17985. auto handler_called = false;
  17986. auto progress_called = false;
  17987. std::string body;
  17988. auto res2 = cli.Get(
  17989. "/no-location",
  17990. [&](const Response &) {
  17991. handler_called = true;
  17992. return true;
  17993. },
  17994. [&](const char *data, size_t data_length) {
  17995. body.append(data, data_length);
  17996. return true;
  17997. },
  17998. [&](size_t, size_t) {
  17999. progress_called = true;
  18000. return true;
  18001. });
  18002. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18003. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18004. EXPECT_TRUE(handler_called);
  18005. EXPECT_TRUE(progress_called);
  18006. EXPECT_EQ("no location", body);
  18007. }
  18008. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18009. Server svr;
  18010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18011. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18012. });
  18013. svr.Get("/hello", [](const Request &req, Response &res) {
  18014. res.set_content(req.get_param_value("key"), "text/plain");
  18015. });
  18016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18017. auto se = detail::scope_exit([&] {
  18018. svr.stop();
  18019. thread.join();
  18020. ASSERT_FALSE(svr.is_running());
  18021. });
  18022. svr.wait_until_ready();
  18023. {
  18024. Client cli(HOST, PORT);
  18025. cli.set_follow_location(true);
  18026. auto res = cli.Get("/");
  18027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18028. EXPECT_EQ(StatusCode::OK_200, res->status);
  18029. EXPECT_EQ("val&key2=val2", res->body);
  18030. }
  18031. }
  18032. #endif
  18033. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18034. Server svr;
  18035. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18036. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18037. });
  18038. svr.Get("/hello", [](const Request &req, Response &res) {
  18039. res.set_content(req.get_param_value("key"), "text/plain");
  18040. });
  18041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18042. auto se = detail::scope_exit([&] {
  18043. svr.stop();
  18044. thread.join();
  18045. ASSERT_FALSE(svr.is_running());
  18046. });
  18047. svr.wait_until_ready();
  18048. {
  18049. Client cli(HOST, PORT);
  18050. cli.set_follow_location(true);
  18051. auto res = cli.Get("/");
  18052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18053. EXPECT_EQ(StatusCode::OK_200, res->status);
  18054. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18055. }
  18056. }
  18057. TEST(RedirectTest, RedirectWithPlusInPath) {
  18058. Server svr;
  18059. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18060. res.set_redirect("/a+b");
  18061. });
  18062. // Route pattern uses regex; escape + as \\+
  18063. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18064. res.set_content(req.path, "text/plain");
  18065. });
  18066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18067. auto se = detail::scope_exit([&] {
  18068. svr.stop();
  18069. thread.join();
  18070. ASSERT_FALSE(svr.is_running());
  18071. });
  18072. svr.wait_until_ready();
  18073. {
  18074. Client cli(HOST, PORT);
  18075. cli.set_follow_location(true);
  18076. auto res = cli.Get("/");
  18077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18078. EXPECT_EQ(StatusCode::OK_200, res->status);
  18079. EXPECT_EQ("/a+b", res->body);
  18080. }
  18081. }
  18082. TEST(RedirectTest, ResolveRelativeLocation) {
  18083. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18084. const std::vector<std::pair<std::string, std::string>> cases = {
  18085. {"g", "/b/c/g"},
  18086. {"./g", "/b/c/g"},
  18087. {"g/", "/b/c/g/"},
  18088. {"?y", "/b/c/d;p?y"},
  18089. {"g?y", "/b/c/g?y"},
  18090. {"#s", "/b/c/d;p?q#s"},
  18091. {"g#s", "/b/c/g#s"},
  18092. {"g?y#s", "/b/c/g?y#s"},
  18093. {";x", "/b/c/;x"},
  18094. {"g;x", "/b/c/g;x"},
  18095. {".", "/b/c/"},
  18096. {"./", "/b/c/"},
  18097. {"..", "/b/"},
  18098. {"../", "/b/"},
  18099. {"../g", "/b/g"},
  18100. {"../..", "/"},
  18101. {"../../", "/"},
  18102. {"../../g", "/g"},
  18103. {"../../../g", "/g"},
  18104. {"g.", "/b/c/g."},
  18105. {".g", "/b/c/.g"},
  18106. {"g..", "/b/c/g.."},
  18107. {"..g", "/b/c/..g"},
  18108. {"./../g", "/b/g"},
  18109. {"./g/.", "/b/c/g/"},
  18110. {"g/./h", "/b/c/g/h"},
  18111. {"g/../h", "/b/c/h"},
  18112. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18113. {"g;x=1/../y", "/b/c/y"},
  18114. {"g?y/./x", "/b/c/g?y/./x"},
  18115. {"g#s/../x", "/b/c/g#s/../x"},
  18116. // Not relative-path references, so left for parse_url.
  18117. {"/g", "/g"},
  18118. {"//g", "//g"},
  18119. {"http://g/x", "http://g/x"},
  18120. {"g:h", "g:h"},
  18121. };
  18122. for (const auto &c : cases) {
  18123. EXPECT_EQ(c.second,
  18124. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18125. << c.first;
  18126. }
  18127. // A result starting with "//" is still a path, not a network-path reference
  18128. EXPECT_EQ("/.//g",
  18129. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18130. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18131. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18132. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18133. }
  18134. TEST(RedirectTest, RemoveDotSegments) {
  18135. // RFC 3986 section 5.2.4
  18136. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18137. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18138. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18139. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18140. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18141. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18142. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18143. }
  18144. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18145. Server svr;
  18146. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18147. res.set_redirect("/dir/../target?x=1");
  18148. });
  18149. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18150. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18151. "/dir/./../target");
  18152. });
  18153. svr.Get("/target", [](const Request &req, Response &res) {
  18154. res.set_content(req.path, "text/plain");
  18155. });
  18156. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18157. auto se = detail::scope_exit([&] {
  18158. svr.stop();
  18159. th.join();
  18160. ASSERT_FALSE(svr.is_running());
  18161. });
  18162. svr.wait_until_ready();
  18163. Client cli("localhost", PORT);
  18164. cli.set_follow_location(true);
  18165. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18166. auto res = cli.Get(path);
  18167. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18168. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18169. EXPECT_EQ("/target", res->body) << path;
  18170. }
  18171. }
  18172. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18173. Server svr;
  18174. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18175. res.set_redirect(req.get_param_value("to"));
  18176. });
  18177. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18178. res.set_content(req.target, "text/plain");
  18179. });
  18180. svr.Get("/other", [](const Request &req, Response &res) {
  18181. res.set_content(req.target, "text/plain");
  18182. });
  18183. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18184. auto se = detail::scope_exit([&] {
  18185. svr.stop();
  18186. thread.join();
  18187. ASSERT_FALSE(svr.is_running());
  18188. });
  18189. svr.wait_until_ready();
  18190. const std::vector<std::pair<std::string, std::string>> cases = {
  18191. {"next", "/dir/next"},
  18192. {"./next?x=1", "/dir/next?x=1"},
  18193. {"../other", "/other"},
  18194. };
  18195. for (const auto &c : cases) {
  18196. Client cli(HOST, PORT);
  18197. cli.set_follow_location(true);
  18198. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18199. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18200. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18201. EXPECT_EQ(c.second, res->body) << c.first;
  18202. }
  18203. }
  18204. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18205. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18206. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18207. Server other;
  18208. std::atomic<int> other_hits{0};
  18209. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18210. other_hits++;
  18211. res.set_content("other", "text/plain");
  18212. });
  18213. auto other_port = other.bind_to_any_port("127.0.0.1");
  18214. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18215. Server svr;
  18216. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18217. res.set_redirect(req.get_param_value("to"));
  18218. });
  18219. svr.Get(".*", [](const Request &req, Response &res) {
  18220. res.set_content(req.path, "text/plain");
  18221. });
  18222. auto port = svr.bind_to_any_port(HOST);
  18223. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18224. auto se = detail::scope_exit([&] {
  18225. svr.stop();
  18226. thread.join();
  18227. other.stop();
  18228. other_thread.join();
  18229. ASSERT_FALSE(svr.is_running());
  18230. ASSERT_FALSE(other.is_running());
  18231. });
  18232. svr.wait_until_ready();
  18233. other.wait_until_ready();
  18234. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18235. for (const auto &to :
  18236. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18237. Client cli(HOST, port);
  18238. cli.set_follow_location(true);
  18239. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18240. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18241. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18242. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18243. }
  18244. EXPECT_EQ(0, other_hits.load());
  18245. }
  18246. #ifdef CPPHTTPLIB_SSL_ENABLED
  18247. TEST(RedirectTest, Issue2185_Online) {
  18248. SSLClient client("github.com");
  18249. client.set_follow_location(true);
  18250. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18251. "Coollab-Windows.zip");
  18252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18253. EXPECT_EQ(StatusCode::OK_200, res->status);
  18254. EXPECT_EQ(9920427U, res->body.size());
  18255. }
  18256. #endif
  18257. TEST(VulnerabilityTest, CRLFInjection) {
  18258. Server svr;
  18259. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18260. res.set_content("Hello 1", "text/plain");
  18261. });
  18262. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18263. res.set_content("Hello 2", "text/plain");
  18264. });
  18265. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18266. res.set_content("Hello 3", "text/plain");
  18267. });
  18268. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18269. res.set_content("Hello 4", "text/plain");
  18270. });
  18271. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18272. for (const auto &x : req.headers) {
  18273. auto key = x.first;
  18274. EXPECT_STRNE("evil", key.c_str());
  18275. }
  18276. });
  18277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18278. auto se = detail::scope_exit([&] {
  18279. svr.stop();
  18280. thread.join();
  18281. ASSERT_FALSE(svr.is_running());
  18282. });
  18283. svr.wait_until_ready();
  18284. {
  18285. Client cli(HOST, PORT);
  18286. cli.Post("/test1", "A=B",
  18287. "application/x-www-form-urlencoded\r\nevil: hello1");
  18288. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18289. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18290. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18291. }
  18292. }
  18293. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18294. auto server_thread = std::thread([] {
  18295. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18296. default_socket_options(srv);
  18297. sockaddr_in addr{};
  18298. addr.sin_family = AF_INET;
  18299. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18300. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18301. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18302. ::listen(srv, 1);
  18303. sockaddr_in cli_addr{};
  18304. socklen_t cli_len = sizeof(cli_addr);
  18305. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18306. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18307. std::string buf_all;
  18308. char buf[2048];
  18309. ssize_t n;
  18310. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18311. buf_all.append(buf, static_cast<size_t>(n));
  18312. size_t pos;
  18313. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18314. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18315. auto e = request_block.find("\r\n");
  18316. if (e != std::string::npos) {
  18317. auto request_line = request_block.substr(0, e);
  18318. std::string msg =
  18319. "CRLF injection detected in request line: '" + request_line + "'";
  18320. EXPECT_FALSE(true) << msg;
  18321. }
  18322. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18323. ::send(cli,
  18324. #ifdef _WIN32
  18325. static_cast<const char *>(resp.c_str()),
  18326. static_cast<int>(resp.size()),
  18327. #else
  18328. resp.c_str(), resp.size(),
  18329. #endif
  18330. 0);
  18331. buf_all.erase(0, pos + 4);
  18332. }
  18333. }
  18334. detail::close_socket(cli);
  18335. detail::close_socket(srv);
  18336. });
  18337. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18338. auto cli = Client("127.0.0.1", PORT + 1);
  18339. auto headers = Headers{
  18340. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18341. {"Connection", "keep-alive"}};
  18342. auto res = cli.Get("/hi", headers);
  18343. EXPECT_FALSE(res);
  18344. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18345. server_thread.join();
  18346. }
  18347. // A request rejected before any byte reaches the socket must fail right away
  18348. // instead of waiting for a response the server will never send.
  18349. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18350. // The kernel completes the TCP handshake from the listen backlog, so the
  18351. // client connects, but nothing ever reads, responds or closes.
  18352. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18353. default_socket_options(srv);
  18354. sockaddr_in addr{};
  18355. addr.sin_family = AF_INET;
  18356. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18357. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18358. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18359. ASSERT_EQ(0, ::listen(srv, 8));
  18360. auto cli = Client("127.0.0.1", PORT + 1);
  18361. cli.set_read_timeout(10, 0);
  18362. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18363. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18364. std::chrono::steady_clock::now() - start)
  18365. .count();
  18366. };
  18367. {
  18368. Request req;
  18369. req.method = "GE T";
  18370. req.path = "/";
  18371. auto start = std::chrono::steady_clock::now();
  18372. auto res = cli.send(req);
  18373. EXPECT_FALSE(res);
  18374. EXPECT_EQ(Error::Write, res.error());
  18375. EXPECT_LT(elapsed_ms(start), 1000);
  18376. }
  18377. {
  18378. auto start = std::chrono::steady_clock::now();
  18379. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18380. EXPECT_FALSE(res);
  18381. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18382. EXPECT_LT(elapsed_ms(start), 1000);
  18383. }
  18384. EXPECT_FALSE(cli.is_socket_open());
  18385. detail::close_socket(srv);
  18386. }
  18387. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18388. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18389. default_socket_options(srv);
  18390. sockaddr_in addr{};
  18391. addr.sin_family = AF_INET;
  18392. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18393. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18394. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18395. ASSERT_EQ(0, ::listen(srv, 1));
  18396. std::string received;
  18397. auto server_thread = std::thread([&] {
  18398. auto sock = ::accept(srv, nullptr, nullptr);
  18399. if (sock == INVALID_SOCKET) { return; }
  18400. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18401. char buf[2048];
  18402. ssize_t n;
  18403. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18404. received.append(buf, static_cast<size_t>(n));
  18405. }
  18406. detail::close_socket(sock);
  18407. });
  18408. {
  18409. auto cli = Client("127.0.0.1", PORT + 1);
  18410. // "Z" sorts after the default headers, so writing straight to the socket
  18411. // would have sent the request line and those headers before the rejection.
  18412. auto handle =
  18413. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18414. EXPECT_FALSE(handle.is_valid());
  18415. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18416. }
  18417. server_thread.join();
  18418. detail::close_socket(srv);
  18419. EXPECT_TRUE(received.empty()) << received;
  18420. }
  18421. TEST(PathParamsTest, StaticMatch) {
  18422. const auto pattern = "/users/all";
  18423. detail::PathParamsMatcher matcher(pattern);
  18424. Request request;
  18425. request.path = "/users/all";
  18426. ASSERT_TRUE(matcher.match(request));
  18427. std::unordered_map<std::string, std::string> expected_params = {};
  18428. EXPECT_EQ(request.path_params, expected_params);
  18429. }
  18430. TEST(PathParamsTest, StaticMismatch) {
  18431. const auto pattern = "/users/all";
  18432. detail::PathParamsMatcher matcher(pattern);
  18433. Request request;
  18434. request.path = "/users/1";
  18435. ASSERT_FALSE(matcher.match(request));
  18436. }
  18437. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18438. const auto pattern = "/users/:id/subscriptions";
  18439. detail::PathParamsMatcher matcher(pattern);
  18440. Request request;
  18441. request.path = "/users/42/subscriptions";
  18442. ASSERT_TRUE(matcher.match(request));
  18443. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18444. EXPECT_EQ(request.path_params, expected_params);
  18445. }
  18446. TEST(PathParamsTest, SingleParamInTheEnd) {
  18447. const auto pattern = "/users/:id";
  18448. detail::PathParamsMatcher matcher(pattern);
  18449. Request request;
  18450. request.path = "/users/24";
  18451. ASSERT_TRUE(matcher.match(request));
  18452. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18453. EXPECT_EQ(request.path_params, expected_params);
  18454. }
  18455. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18456. const auto pattern = "/users/:id/";
  18457. detail::PathParamsMatcher matcher(pattern);
  18458. Request request;
  18459. request.path = "/users/42/";
  18460. ASSERT_TRUE(matcher.match(request));
  18461. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18462. EXPECT_EQ(request.path_params, expected_params);
  18463. }
  18464. TEST(PathParamsTest, EmptyParam) {
  18465. const auto pattern = "/users/:id/";
  18466. detail::PathParamsMatcher matcher(pattern);
  18467. Request request;
  18468. request.path = "/users//";
  18469. ASSERT_TRUE(matcher.match(request));
  18470. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18471. EXPECT_EQ(request.path_params, expected_params);
  18472. }
  18473. TEST(PathParamsTest, FragmentMismatch) {
  18474. const auto pattern = "/users/:id/";
  18475. detail::PathParamsMatcher matcher(pattern);
  18476. Request request;
  18477. request.path = "/admins/24/";
  18478. ASSERT_FALSE(matcher.match(request));
  18479. }
  18480. TEST(PathParamsTest, ExtraFragments) {
  18481. const auto pattern = "/users/:id";
  18482. detail::PathParamsMatcher matcher(pattern);
  18483. Request request;
  18484. request.path = "/users/42/subscriptions";
  18485. ASSERT_FALSE(matcher.match(request));
  18486. }
  18487. TEST(PathParamsTest, MissingTrailingParam) {
  18488. const auto pattern = "/users/:id";
  18489. detail::PathParamsMatcher matcher(pattern);
  18490. Request request;
  18491. request.path = "/users";
  18492. ASSERT_FALSE(matcher.match(request));
  18493. }
  18494. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18495. const auto pattern = "/users/:id/subscriptions";
  18496. detail::PathParamsMatcher matcher(pattern);
  18497. Request request;
  18498. request.path = "/users/subscriptions";
  18499. ASSERT_FALSE(matcher.match(request));
  18500. }
  18501. TEST(PathParamsTest, MultipleParams) {
  18502. const auto pattern = "/users/:userid/subscriptions/:subid";
  18503. detail::PathParamsMatcher matcher(pattern);
  18504. Request request;
  18505. request.path = "/users/42/subscriptions/2";
  18506. ASSERT_TRUE(matcher.match(request));
  18507. std::unordered_map<std::string, std::string> expected_params = {
  18508. {"userid", "42"}, {"subid", "2"}};
  18509. EXPECT_EQ(request.path_params, expected_params);
  18510. }
  18511. TEST(PathParamsTest, SequenceOfParams) {
  18512. const auto pattern = "/values/:x/:y/:z";
  18513. detail::PathParamsMatcher matcher(pattern);
  18514. Request request;
  18515. request.path = "/values/1/2/3";
  18516. ASSERT_TRUE(matcher.match(request));
  18517. std::unordered_map<std::string, std::string> expected_params = {
  18518. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18519. EXPECT_EQ(request.path_params, expected_params);
  18520. }
  18521. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18522. const auto pattern = "/prefix:suffix";
  18523. detail::PathParamsMatcher matcher(pattern);
  18524. Request request;
  18525. request.path = "/prefix:suffix";
  18526. ASSERT_TRUE(matcher.match(request));
  18527. const std::unordered_map<std::string, std::string> expected_params = {};
  18528. EXPECT_EQ(request.path_params, expected_params);
  18529. }
  18530. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18531. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18532. // calling thread's stack on a long enough path for a quantified pattern;
  18533. // RegexMatcher must refuse to run regex matching on paths beyond
  18534. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18535. detail::RegexMatcher matcher("/files/(.*)");
  18536. Request within_limit;
  18537. within_limit.path = "/files/" + std::string(10, 'A');
  18538. EXPECT_TRUE(matcher.match(within_limit));
  18539. Request over_limit;
  18540. over_limit.path =
  18541. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18542. EXPECT_FALSE(matcher.match(over_limit));
  18543. }
  18544. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18545. Server svr;
  18546. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18547. res.set_content("ok", "text/plain");
  18548. });
  18549. auto port = svr.bind_to_any_port(HOST);
  18550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18551. auto se = detail::scope_exit([&] {
  18552. svr.stop();
  18553. thread.join();
  18554. ASSERT_FALSE(svr.is_running());
  18555. });
  18556. svr.wait_until_ready();
  18557. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18558. // request URI limit; this used to be able to crash the process.
  18559. std::string path =
  18560. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18561. std::string req = "GET " + path +
  18562. " HTTP/1.1\r\n"
  18563. "Host: " +
  18564. std::string(HOST) + ":" + std::to_string(port) +
  18565. "\r\n"
  18566. "Connection: close\r\n"
  18567. "\r\n";
  18568. std::string response;
  18569. ASSERT_TRUE(send_request(5, req, &response, port));
  18570. EXPECT_NE(std::string::npos, response.find("404"));
  18571. }
  18572. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18573. Server svr;
  18574. auto handler = [](const Request & /*req*/, Response &res) {
  18575. res.set_content("hit", "text/plain");
  18576. };
  18577. // No regex metacharacter, so this one is compared literally
  18578. svr.Get("/literal/route", handler);
  18579. // '.' is a regex metacharacter, so this one must keep regex semantics
  18580. svr.Get("/a.c", handler);
  18581. auto port = svr.bind_to_any_port(HOST);
  18582. std::thread t([&]() { svr.listen_after_bind(); });
  18583. auto se = detail::scope_exit([&] {
  18584. svr.stop();
  18585. t.join();
  18586. ASSERT_FALSE(svr.is_running());
  18587. });
  18588. svr.wait_until_ready();
  18589. Client cli(HOST, port);
  18590. struct {
  18591. const char *path;
  18592. int status;
  18593. } cases[] = {
  18594. {"/literal/route", StatusCode::OK_200},
  18595. {"/literal/routes", StatusCode::NotFound_404},
  18596. {"/literal/rout", StatusCode::NotFound_404},
  18597. {"/abc", StatusCode::OK_200},
  18598. {"/a.c", StatusCode::OK_200},
  18599. };
  18600. for (const auto &x : cases) {
  18601. auto res = cli.Get(x.path);
  18602. ASSERT_TRUE(res) << x.path;
  18603. EXPECT_EQ(x.status, res->status) << x.path;
  18604. }
  18605. }
  18606. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18607. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18608. // from exhausting the stack, so it must only constrain routes that actually
  18609. // run a regular expression. A literal route is matched by comparison and
  18610. // stays usable at any length.
  18611. Server svr;
  18612. const std::string pattern =
  18613. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18614. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18615. res.set_content("hit", "text/plain");
  18616. });
  18617. auto port = svr.bind_to_any_port(HOST);
  18618. std::thread t([&]() { svr.listen_after_bind(); });
  18619. auto se = detail::scope_exit([&] {
  18620. svr.stop();
  18621. t.join();
  18622. ASSERT_FALSE(svr.is_running());
  18623. });
  18624. svr.wait_until_ready();
  18625. Client cli(HOST, port);
  18626. auto res = cli.Get(pattern);
  18627. ASSERT_TRUE(res);
  18628. EXPECT_EQ(StatusCode::OK_200, res->status);
  18629. }
  18630. TEST(ParseUrlTest, VariousPatterns) {
  18631. {
  18632. detail::UrlComponents uc;
  18633. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18634. EXPECT_EQ("http", uc.scheme);
  18635. EXPECT_EQ("example.com", uc.host);
  18636. EXPECT_EQ("8080", uc.port);
  18637. EXPECT_EQ("/path", uc.path);
  18638. EXPECT_EQ("?q=1", uc.query);
  18639. }
  18640. {
  18641. detail::UrlComponents uc;
  18642. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18643. EXPECT_EQ("https", uc.scheme);
  18644. EXPECT_EQ("example.com", uc.host);
  18645. EXPECT_TRUE(uc.port.empty());
  18646. EXPECT_EQ("/path", uc.path);
  18647. }
  18648. {
  18649. detail::UrlComponents uc;
  18650. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18651. EXPECT_EQ("::1", uc.host);
  18652. EXPECT_EQ("8080", uc.port);
  18653. EXPECT_EQ("/path", uc.path);
  18654. }
  18655. {
  18656. detail::UrlComponents uc;
  18657. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18658. }
  18659. {
  18660. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18661. // the path while the connection still targets the bracketed host.
  18662. detail::UrlComponents uc;
  18663. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18664. }
  18665. {
  18666. detail::UrlComponents uc;
  18667. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18668. }
  18669. {
  18670. detail::UrlComponents uc;
  18671. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18672. EXPECT_EQ("::1", uc.host);
  18673. EXPECT_TRUE(uc.port.empty());
  18674. EXPECT_EQ("/path", uc.path);
  18675. }
  18676. {
  18677. detail::UrlComponents uc;
  18678. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18679. EXPECT_TRUE(uc.scheme.empty());
  18680. EXPECT_EQ("example.com", uc.host);
  18681. EXPECT_EQ("/path", uc.path);
  18682. EXPECT_EQ("?q=1", uc.query);
  18683. }
  18684. {
  18685. detail::UrlComponents uc;
  18686. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18687. EXPECT_TRUE(uc.host.empty());
  18688. EXPECT_EQ("/path", uc.path);
  18689. EXPECT_EQ("?q=1", uc.query);
  18690. }
  18691. {
  18692. detail::UrlComponents uc;
  18693. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18694. EXPECT_EQ("example.com", uc.host);
  18695. EXPECT_EQ("8080", uc.port);
  18696. }
  18697. {
  18698. // Unix socket path — must not be parsed as host
  18699. detail::UrlComponents uc;
  18700. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18701. EXPECT_TRUE(uc.host.empty());
  18702. }
  18703. {
  18704. detail::UrlComponents uc;
  18705. ASSERT_TRUE(detail::parse_url("", uc));
  18706. EXPECT_TRUE(uc.host.empty());
  18707. EXPECT_TRUE(uc.path.empty());
  18708. }
  18709. {
  18710. detail::UrlComponents uc;
  18711. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18712. EXPECT_EQ("http", uc.scheme);
  18713. }
  18714. {
  18715. detail::UrlComponents uc;
  18716. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18717. }
  18718. {
  18719. // Accepted by parse_url; callers restrict to http/https
  18720. detail::UrlComponents uc;
  18721. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18722. EXPECT_EQ("ftp", uc.scheme);
  18723. }
  18724. {
  18725. detail::UrlComponents uc;
  18726. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18727. }
  18728. {
  18729. detail::UrlComponents uc;
  18730. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18731. }
  18732. }
  18733. TEST(ParseUrlTest, FragmentHandling) {
  18734. {
  18735. detail::UrlComponents uc;
  18736. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18737. EXPECT_EQ("/path", uc.path);
  18738. EXPECT_TRUE(uc.query.empty());
  18739. }
  18740. {
  18741. detail::UrlComponents uc;
  18742. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18743. EXPECT_TRUE(uc.path.empty());
  18744. EXPECT_TRUE(uc.query.empty());
  18745. }
  18746. }
  18747. TEST(ParseUrlTest, UserinfoHandling) {
  18748. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18749. // parsers would see evil.com as the host.
  18750. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18751. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18752. for (auto url : urls) {
  18753. detail::UrlComponents uc;
  18754. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18755. }
  18756. }
  18757. TEST(ParseUrlTest, IPv6EdgeCases) {
  18758. {
  18759. detail::UrlComponents uc;
  18760. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18761. EXPECT_TRUE(uc.scheme.empty());
  18762. EXPECT_EQ("::1", uc.host);
  18763. EXPECT_EQ("8080", uc.port);
  18764. }
  18765. {
  18766. // Zone ID '%25' is not in [a-fA-F0-9:]
  18767. detail::UrlComponents uc;
  18768. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18769. }
  18770. }
  18771. TEST(ParseUrlTest, SchemeEdgeCases) {
  18772. {
  18773. detail::UrlComponents uc;
  18774. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18775. }
  18776. {
  18777. detail::UrlComponents uc;
  18778. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18779. }
  18780. {
  18781. detail::UrlComponents uc;
  18782. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18783. }
  18784. {
  18785. detail::UrlComponents uc;
  18786. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18787. EXPECT_EQ("https", uc.scheme);
  18788. }
  18789. }
  18790. TEST(ParseUrlTest, PortEdgeCases) {
  18791. {
  18792. detail::UrlComponents uc;
  18793. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18794. EXPECT_TRUE(uc.port.empty());
  18795. EXPECT_EQ("/path", uc.path);
  18796. }
  18797. {
  18798. // parse_url accepts any port string; validation is done by parse_port
  18799. detail::UrlComponents uc;
  18800. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18801. EXPECT_EQ("abc", uc.port);
  18802. }
  18803. }
  18804. TEST(ParseUrlTest, WebSocketPatterns) {
  18805. {
  18806. detail::UrlComponents uc;
  18807. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18808. EXPECT_EQ("ws", uc.scheme);
  18809. EXPECT_EQ("echo.example.com", uc.host);
  18810. EXPECT_EQ("8080", uc.port);
  18811. EXPECT_EQ("/ws", uc.path);
  18812. }
  18813. {
  18814. detail::UrlComponents uc;
  18815. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18816. EXPECT_EQ("wss", uc.scheme);
  18817. EXPECT_EQ("echo.example.com", uc.host);
  18818. EXPECT_TRUE(uc.port.empty());
  18819. EXPECT_EQ("/ws", uc.path);
  18820. }
  18821. }
  18822. TEST(ParseUrlTest, QueryOnly) {
  18823. detail::UrlComponents uc;
  18824. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18825. EXPECT_TRUE(uc.host.empty());
  18826. EXPECT_TRUE(uc.path.empty());
  18827. EXPECT_EQ("?q=1&r=2", uc.query);
  18828. }
  18829. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18830. detail::UrlComponents uc;
  18831. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18832. EXPECT_TRUE(uc.scheme.empty());
  18833. EXPECT_EQ("example.com", uc.host);
  18834. EXPECT_EQ("443", uc.port);
  18835. EXPECT_EQ("/path", uc.path);
  18836. }
  18837. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18838. // If ipv6 regex working, regex match codepath is taken.
  18839. // else port will default to 80 in Client impl
  18840. int clientImplMagicPort = 80;
  18841. int port = 4321;
  18842. // above ports must be different to avoid false negative
  18843. EXPECT_NE(clientImplMagicPort, port);
  18844. std::string ipV6TestURL = "http://[ff06::c3]";
  18845. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18846. CLIENT_PRIVATE_KEY_FILE);
  18847. EXPECT_EQ(cli.port(), port);
  18848. }
  18849. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18850. auto file_path = "./www/dir/index.html";
  18851. auto dir_path = "./www/dir";
  18852. detail::FileStat stat_file(file_path);
  18853. EXPECT_TRUE(stat_file.is_file());
  18854. EXPECT_FALSE(stat_file.is_dir());
  18855. detail::FileStat stat_dir(dir_path);
  18856. EXPECT_FALSE(stat_dir.is_file());
  18857. EXPECT_TRUE(stat_dir.is_dir());
  18858. }
  18859. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18860. // IPv4 with default HTTP port (80)
  18861. EXPECT_EQ("example.com",
  18862. detail::make_host_and_port_string("example.com", 80, false));
  18863. // IPv4 with default HTTPS port (443)
  18864. EXPECT_EQ("example.com",
  18865. detail::make_host_and_port_string("example.com", 443, true));
  18866. // IPv4 with non-default HTTP port
  18867. EXPECT_EQ("example.com:8080",
  18868. detail::make_host_and_port_string("example.com", 8080, false));
  18869. // IPv4 with non-default HTTPS port
  18870. EXPECT_EQ("example.com:8443",
  18871. detail::make_host_and_port_string("example.com", 8443, true));
  18872. // IPv6 with default HTTP port (80)
  18873. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18874. // IPv6 with default HTTPS port (443)
  18875. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18876. // IPv6 with non-default HTTP port
  18877. EXPECT_EQ("[::1]:8080",
  18878. detail::make_host_and_port_string("::1", 8080, false));
  18879. // IPv6 with non-default HTTPS port
  18880. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18881. // IPv6 full address with default port
  18882. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18883. detail::make_host_and_port_string(
  18884. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18885. // IPv6 full address with non-default port
  18886. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18887. detail::make_host_and_port_string(
  18888. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18889. // IPv6 localhost with non-default port
  18890. EXPECT_EQ("[::1]:3000",
  18891. detail::make_host_and_port_string("::1", 3000, false));
  18892. // IPv6 with zone ID (link-local address) with default port
  18893. EXPECT_EQ("[fe80::1%eth0]",
  18894. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18895. // IPv6 with zone ID (link-local address) with non-default port
  18896. EXPECT_EQ("[fe80::1%eth0]:8080",
  18897. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18898. // Edge case: Port 443 with is_ssl=false (should add port)
  18899. EXPECT_EQ("example.com:443",
  18900. detail::make_host_and_port_string("example.com", 443, false));
  18901. // Edge case: Port 80 with is_ssl=true (should add port)
  18902. EXPECT_EQ("example.com:80",
  18903. detail::make_host_and_port_string("example.com", 80, true));
  18904. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18905. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18906. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18907. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18908. // Security fix: Already bracketed IPv6 should not get double brackets
  18909. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18910. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18911. EXPECT_EQ("[::1]:8080",
  18912. detail::make_host_and_port_string("[::1]", 8080, false));
  18913. EXPECT_EQ("[2001:db8::1]:8080",
  18914. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18915. EXPECT_EQ("[fe80::1%eth0]",
  18916. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18917. EXPECT_EQ("[fe80::1%eth0]:8080",
  18918. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18919. // Edge case: Empty host (should return as-is)
  18920. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18921. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18922. // This is a known limitation but shouldn't crash
  18923. EXPECT_EQ("[host:name]",
  18924. detail::make_host_and_port_string("host:name", 80, false));
  18925. // Port number edge cases (no validation, but should not crash)
  18926. EXPECT_EQ("example.com:0",
  18927. detail::make_host_and_port_string("example.com", 0, false));
  18928. EXPECT_EQ("example.com:-1",
  18929. detail::make_host_and_port_string("example.com", -1, false));
  18930. EXPECT_EQ("example.com:65535",
  18931. detail::make_host_and_port_string("example.com", 65535, false));
  18932. EXPECT_EQ("example.com:65536",
  18933. detail::make_host_and_port_string("example.com", 65536, false));
  18934. }
  18935. namespace httplib {
  18936. namespace detail {
  18937. std::string
  18938. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18939. const std::string &host, int port);
  18940. } // namespace detail
  18941. } // namespace httplib
  18942. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18943. std::map<std::string, std::string> addr_map = {
  18944. {"ipv4.example", "192.0.2.10"},
  18945. {"ipv6.example", "2001:db8::1"},
  18946. {"name.example", "internal.example.lan"},
  18947. {"empty.example", ""}};
  18948. EXPECT_EQ("192.0.2.10:443",
  18949. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18950. EXPECT_EQ("[2001:db8::1]:443",
  18951. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18952. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18953. addr_map, "name.example", 8443));
  18954. // An empty or absent mapping keeps the hostname as the target
  18955. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18956. addr_map, "empty.example", 443));
  18957. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18958. addr_map, "other.example", 443));
  18959. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18960. }
  18961. #ifdef CPPHTTPLIB_SSL_ENABLED
  18962. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18963. httplib::SSLClient cli("roblox.com", 443);
  18964. cli.set_follow_location(true);
  18965. auto res = cli.Get("/");
  18966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18967. EXPECT_EQ(StatusCode::OK_200, res->status);
  18968. }
  18969. #endif
  18970. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18971. Server svr;
  18972. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18973. EXPECT_EQ(res.status, 400);
  18974. });
  18975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18976. auto se = detail::scope_exit([&] {
  18977. svr.stop();
  18978. thread.join();
  18979. ASSERT_FALSE(svr.is_running());
  18980. });
  18981. svr.wait_until_ready();
  18982. Client cli(HOST, PORT);
  18983. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18984. }
  18985. TEST(InvalidHeaderCharsTest, is_field_name) {
  18986. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18987. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18988. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18989. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18990. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18991. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18992. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18993. EXPECT_FALSE(detail::fields::is_field_name(""));
  18994. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18995. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18996. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18997. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18998. }
  18999. TEST(InvalidHeaderCharsTest, is_field_value) {
  19000. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19001. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19002. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19003. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19004. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19005. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19006. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19007. EXPECT_TRUE(detail::fields::is_field_value(""));
  19008. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19009. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19010. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19011. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19012. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19013. }
  19014. TEST(InvalidHeaderCharsTest, OnServer) {
  19015. Server svr;
  19016. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19017. std::string header = "Not Set";
  19018. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19019. res.set_header(header, "value");
  19020. res.set_content("Page Content Page Content", "text/plain");
  19021. });
  19022. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19023. std::string header = "Not Set";
  19024. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19025. res.set_header("X-Test", header);
  19026. res.set_content("Page Content Page Content", "text/plain");
  19027. });
  19028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19029. auto se = detail::scope_exit([&] {
  19030. svr.stop();
  19031. thread.join();
  19032. ASSERT_FALSE(svr.is_running());
  19033. });
  19034. svr.wait_until_ready();
  19035. Client cli(HOST, PORT);
  19036. {
  19037. auto res = cli.Get(
  19038. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19040. EXPECT_EQ("Page Content Page Content", res->body);
  19041. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19042. }
  19043. {
  19044. auto res = cli.Get(
  19045. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19047. EXPECT_EQ("Page Content Page Content", res->body);
  19048. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19049. }
  19050. }
  19051. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19052. auto handled = false;
  19053. Server svr;
  19054. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19055. thread t = thread([&] { svr.listen(HOST, PORT); });
  19056. auto se = detail::scope_exit([&] {
  19057. svr.stop();
  19058. t.join();
  19059. ASSERT_FALSE(svr.is_running());
  19060. ASSERT_FALSE(handled);
  19061. });
  19062. svr.wait_until_ready();
  19063. auto req = "POST /test HTTP/1.1\r\n"
  19064. "Content-Length: x\r\n"
  19065. "\r\n";
  19066. std::string response;
  19067. ASSERT_TRUE(send_request(1, req, &response));
  19068. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19069. response.substr(0, response.find("\r\n")));
  19070. }
  19071. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19072. // case-insensitive, and a server that receives a 100-continue expectation in
  19073. // an HTTP/1.0 request MUST ignore it.
  19074. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19075. std::string response;
  19076. ASSERT_TRUE(send_request(1, req, &response, port));
  19077. *got_100 = response.find("100 Continue") != std::string::npos;
  19078. }
  19079. class ExpectTokenTest : public ::testing::Test {
  19080. protected:
  19081. void SetUp() override {
  19082. svr_.Post("/p", [](const Request &, Response &res) {
  19083. res.set_content("ok", "text/plain");
  19084. });
  19085. port_ = svr_.bind_to_any_port(HOST);
  19086. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19087. svr_.wait_until_ready();
  19088. }
  19089. void TearDown() override {
  19090. svr_.stop();
  19091. if (thread_.joinable()) { thread_.join(); }
  19092. }
  19093. std::string request(const char *version, const char *expect_value) const {
  19094. return std::string("POST /p ") + version +
  19095. "\r\n"
  19096. "Host: localhost\r\n"
  19097. "Content-Length: 2\r\n"
  19098. "Connection: close\r\n"
  19099. "Expect: " +
  19100. expect_value +
  19101. "\r\n"
  19102. "\r\n"
  19103. "hi";
  19104. }
  19105. Server svr_;
  19106. int port_ = 0;
  19107. thread thread_;
  19108. };
  19109. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19110. bool got_100 = false;
  19111. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19112. EXPECT_TRUE(got_100);
  19113. }
  19114. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19115. bool got_100 = true;
  19116. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19117. EXPECT_FALSE(got_100);
  19118. }
  19119. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19120. bool got_100 = false;
  19121. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19122. EXPECT_TRUE(got_100);
  19123. }
  19124. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19125. bool got_100 = false;
  19126. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19127. EXPECT_TRUE(got_100);
  19128. }
  19129. // `100 Continue` is sent only when the server starts reading the body, so a
  19130. // request rejected before that never invites the client to send it. The
  19131. // requests below carry the expectation but withhold the body, as a client
  19132. // waiting for `100 Continue` would.
  19133. // A POST that expects `100 Continue` and withholds its two-byte body.
  19134. static std::string expect_headers_only(const std::string &path) {
  19135. return "POST " + path +
  19136. " HTTP/1.1\r\n"
  19137. "Host: localhost\r\n"
  19138. "Content-Length: 2\r\n"
  19139. "Expect: 100-continue\r\n"
  19140. "\r\n";
  19141. }
  19142. class ExpectLazyContinueTest : public ::testing::Test {
  19143. protected:
  19144. void SetUp() override {
  19145. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19146. if (req.path == "/pre-routing") {
  19147. res.status = StatusCode::Unauthorized_401;
  19148. return Server::HandlerResponse::Handled;
  19149. }
  19150. return Server::HandlerResponse::Unhandled;
  19151. });
  19152. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19153. if (req.matched_route == "/pre-request") {
  19154. res.status = StatusCode::Forbidden_403;
  19155. return Server::HandlerResponse::Handled;
  19156. }
  19157. return Server::HandlerResponse::Unhandled;
  19158. });
  19159. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19160. res.set_content("ok", "text/plain");
  19161. });
  19162. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19163. res.set_content("ok", "text/plain");
  19164. });
  19165. svr_.Post("/reader-used", [](const Request &, Response &res,
  19166. const ContentReader &content_reader) {
  19167. std::string body;
  19168. content_reader([&](const char *data, size_t len) {
  19169. body.append(data, len);
  19170. return true;
  19171. });
  19172. res.set_content(body, "text/plain");
  19173. });
  19174. svr_.Post("/reader-unused",
  19175. [](const Request &, Response &res, const ContentReader &) {
  19176. res.set_content("ignored", "text/plain");
  19177. });
  19178. port_ = svr_.bind_to_any_port(HOST);
  19179. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19180. svr_.wait_until_ready();
  19181. }
  19182. void TearDown() override {
  19183. svr_.stop();
  19184. if (thread_.joinable()) { thread_.join(); }
  19185. }
  19186. // Sends `req` and reads until the server closes the connection. Returns
  19187. // false if the read had to wait for the client-side timeout instead.
  19188. bool send_until_closed(const std::string &req, std::string *resp) const {
  19189. auto start = std::chrono::steady_clock::now();
  19190. if (!send_request(3, req, resp, port_)) { return false; }
  19191. auto elapsed = std::chrono::steady_clock::now() - start;
  19192. return elapsed < std::chrono::seconds(2);
  19193. }
  19194. // The final response comes without `100 Continue`, and the server closes
  19195. // the connection since the body may or may not follow.
  19196. void expect_final_without_interim(const std::string &path,
  19197. const char *status_line) const {
  19198. std::string resp;
  19199. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19200. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19201. EXPECT_EQ(0u, resp.find(status_line));
  19202. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19203. }
  19204. Server svr_;
  19205. int port_ = 0;
  19206. thread thread_;
  19207. };
  19208. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19209. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19210. }
  19211. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19212. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19213. }
  19214. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19215. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19216. }
  19217. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19218. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19219. }
  19220. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19221. // The body follows once `100 Continue` has had time to arrive.
  19222. auto req = expect_headers_only("/reader-used");
  19223. req.insert(req.size() - 2, "Connection: close\r\n");
  19224. std::string resp;
  19225. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19226. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19227. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19228. EXPECT_NE(std::string::npos, resp.find("hi"));
  19229. }
  19230. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19231. // Large enough for the client to add `Expect: 100-continue` itself.
  19232. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19233. std::atomic<bool> body_sent{false};
  19234. Client cli(HOST, port_);
  19235. auto res = cli.Post(
  19236. "/pre-request", length,
  19237. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19238. body_sent = true;
  19239. std::string chunk(len, 'x');
  19240. sink.write(chunk.data(), chunk.size());
  19241. return true;
  19242. },
  19243. "application/octet-stream");
  19244. ASSERT_TRUE(res);
  19245. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19246. EXPECT_FALSE(body_sent);
  19247. }
  19248. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19249. Server svr;
  19250. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19251. return StatusCode::ExpectationFailed_417;
  19252. });
  19253. svr.Post("/p", [](const Request &, Response &res) {
  19254. res.set_content("ok", "text/plain");
  19255. });
  19256. auto port = svr.bind_to_any_port(HOST);
  19257. thread t = thread([&] { svr.listen_after_bind(); });
  19258. auto se = detail::scope_exit([&] {
  19259. svr.stop();
  19260. t.join();
  19261. });
  19262. svr.wait_until_ready();
  19263. std::string resp;
  19264. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19265. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19266. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19267. // Exactly one response: the route handler must not run after the 417.
  19268. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19269. }
  19270. #ifndef _WIN32
  19271. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19272. static constexpr char reject[] = "Unauthorized";
  19273. static constexpr char accept[] = "Upload accepted";
  19274. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19275. Server svr;
  19276. svr.set_expect_100_continue_handler(
  19277. [](const Request & /*req*/, Response &res) {
  19278. res.status = StatusCode::Unauthorized_401;
  19279. res.set_content(reject, "text/plain");
  19280. return res.status;
  19281. });
  19282. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19283. res.set_content(accept, "text/plain");
  19284. });
  19285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19286. auto se = detail::scope_exit([&] {
  19287. svr.stop();
  19288. thread.join();
  19289. ASSERT_FALSE(svr.is_running());
  19290. });
  19291. svr.wait_until_ready();
  19292. {
  19293. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19294. curl_easy_init(), &curl_easy_cleanup};
  19295. ASSERT_NE(curl, nullptr);
  19296. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19297. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19298. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19299. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19300. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19301. &curl_slist_free_all};
  19302. ASSERT_NE(list, nullptr);
  19303. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19304. struct read_data {
  19305. uint64_t read_size;
  19306. uint64_t total_size;
  19307. } data = {0, total_size};
  19308. using read_callback_t =
  19309. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19310. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19311. void *userdata) -> size_t {
  19312. read_data *d = (read_data *)userdata;
  19313. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19314. std::fill_n(ptr, size * nmemb, 'A');
  19315. d->read_size += size * nmemb;
  19316. return size * nmemb;
  19317. };
  19318. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19319. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19320. std::vector<char> buffer;
  19321. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19322. using write_callback_t =
  19323. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19324. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19325. void *userdata) -> size_t {
  19326. std::vector<char> *buf = (std::vector<char> *)userdata;
  19327. buf->reserve(buf->size() + size * nmemb + 1);
  19328. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19329. return size * nmemb;
  19330. };
  19331. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19332. {
  19333. const auto res = curl_easy_perform(curl.get());
  19334. ASSERT_EQ(res, CURLE_OK);
  19335. }
  19336. {
  19337. auto response_code = long{};
  19338. const auto res =
  19339. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19340. ASSERT_EQ(res, CURLE_OK);
  19341. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19342. }
  19343. {
  19344. auto dl = curl_off_t{};
  19345. const auto res =
  19346. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19347. ASSERT_EQ(res, CURLE_OK);
  19348. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19349. }
  19350. {
  19351. buffer.push_back('\0');
  19352. ASSERT_STRCASEEQ(buffer.data(), reject);
  19353. }
  19354. }
  19355. }
  19356. #endif
  19357. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19358. // Regression test for #2458.
  19359. //
  19360. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19361. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19362. // ticket can make the client socket spuriously readable during the
  19363. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19364. // the client withholds the body and then blocks reading a response that never
  19365. // comes, failing with `Failed to read connection`.
  19366. //
  19367. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19368. // within the timeout. This raw OpenSSL server deliberately never sends
  19369. // `100 Continue`; the client must still deliver the body and receive 200.
  19370. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19371. signal(SIGPIPE, SIG_IGN);
  19372. const auto port = PORT + 4;
  19373. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19374. ASSERT_NE(srv, INVALID_SOCKET);
  19375. int opt = 1;
  19376. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19377. sockaddr_in addr{};
  19378. addr.sin_family = AF_INET;
  19379. addr.sin_port = htons(static_cast<uint16_t>(port));
  19380. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19381. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19382. ASSERT_EQ(0, ::listen(srv, 1));
  19383. std::atomic<size_t> server_body_bytes{0};
  19384. auto server_thread = std::thread([&] {
  19385. sockaddr_in cli_addr{};
  19386. socklen_t cli_len = sizeof(cli_addr);
  19387. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19388. if (cli == INVALID_SOCKET) { return; }
  19389. // Bound the lifetime of the server side so a buggy client (which never
  19390. // sends the body) cannot make this thread block forever on join.
  19391. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19392. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19393. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19394. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19395. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19396. SSL *ssl = SSL_new(ctx);
  19397. SSL_set_fd(ssl, static_cast<int>(cli));
  19398. if (SSL_accept(ssl) > 0) {
  19399. // Read the request headers. Reading here also flushes the TLS 1.3
  19400. // session tickets to the client. Deliberately do NOT send
  19401. // `100 Continue`.
  19402. std::string buf;
  19403. char tmp[1024];
  19404. while (buf.find("\r\n\r\n") == std::string::npos) {
  19405. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19406. if (n <= 0) { break; }
  19407. buf.append(tmp, static_cast<size_t>(n));
  19408. }
  19409. // A correct client sends the body now; count what arrives.
  19410. auto pos = buf.find("\r\n\r\n");
  19411. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19412. while (body < 4096) {
  19413. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19414. if (n <= 0) { break; }
  19415. body += static_cast<size_t>(n);
  19416. }
  19417. server_body_bytes = body;
  19418. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19419. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19420. SSL_shutdown(ssl);
  19421. }
  19422. SSL_free(ssl);
  19423. detail::close_socket(cli);
  19424. SSL_CTX_free(ctx);
  19425. });
  19426. auto se = detail::scope_exit([&] {
  19427. server_thread.join();
  19428. detail::close_socket(srv);
  19429. });
  19430. SSLClient cli("127.0.0.1", port);
  19431. cli.enable_server_certificate_verification(false);
  19432. cli.set_connection_timeout(5, 0);
  19433. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19434. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19435. std::string body(4096, 'A');
  19436. auto res = cli.Put("/api/test", body, "application/json");
  19437. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19438. EXPECT_EQ(StatusCode::OK_200, res->status);
  19439. EXPECT_EQ(body.size(), server_body_bytes.load());
  19440. }
  19441. #endif
  19442. template <typename S, typename C>
  19443. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19444. svr.Get("/stream", [&](const Request &, Response &res) {
  19445. auto data = new std::string("01234567890123456789");
  19446. res.set_content_provider(
  19447. data->size(), "text/plain",
  19448. [&, data](size_t offset, size_t length, DataSink &sink) {
  19449. const size_t DATA_CHUNK_SIZE = 4;
  19450. const auto &d = *data;
  19451. std::this_thread::sleep_for(std::chrono::seconds(1));
  19452. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19453. return true;
  19454. },
  19455. [data](bool success) {
  19456. EXPECT_FALSE(success);
  19457. delete data;
  19458. });
  19459. });
  19460. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19461. auto i = new size_t(0);
  19462. res.set_content_provider(
  19463. "text/plain",
  19464. [i](size_t, DataSink &sink) {
  19465. if (*i < 5) {
  19466. std::this_thread::sleep_for(std::chrono::seconds(1));
  19467. sink.write("abcd", 4);
  19468. (*i)++;
  19469. } else {
  19470. sink.done();
  19471. }
  19472. return true;
  19473. },
  19474. [i](bool success) {
  19475. EXPECT_FALSE(success);
  19476. delete i;
  19477. });
  19478. });
  19479. svr.Get("/chunked", [&](const Request &, Response &res) {
  19480. auto i = new size_t(0);
  19481. res.set_chunked_content_provider(
  19482. "text/plain",
  19483. [i](size_t, DataSink &sink) {
  19484. if (*i < 5) {
  19485. std::this_thread::sleep_for(std::chrono::seconds(1));
  19486. sink.os << "abcd";
  19487. (*i)++;
  19488. } else {
  19489. sink.done();
  19490. }
  19491. return true;
  19492. },
  19493. [i](bool success) {
  19494. EXPECT_FALSE(success);
  19495. delete i;
  19496. });
  19497. });
  19498. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19499. auto se = detail::scope_exit([&] {
  19500. svr.stop();
  19501. listen_thread.join();
  19502. ASSERT_FALSE(svr.is_running());
  19503. });
  19504. svr.wait_until_ready();
  19505. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19506. {
  19507. auto start = std::chrono::steady_clock::now();
  19508. auto res = cli.Get("/stream");
  19509. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19510. std::chrono::steady_clock::now() - start)
  19511. .count();
  19512. ASSERT_FALSE(res);
  19513. EXPECT_EQ(Error::Read, res.error());
  19514. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19515. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19516. }
  19517. {
  19518. auto start = std::chrono::steady_clock::now();
  19519. auto res = cli.Get("/stream_without_length");
  19520. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19521. std::chrono::steady_clock::now() - start)
  19522. .count();
  19523. ASSERT_FALSE(res);
  19524. EXPECT_EQ(Error::Read, res.error());
  19525. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19526. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19527. }
  19528. {
  19529. auto start = std::chrono::steady_clock::now();
  19530. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19531. EXPECT_EQ("abcd", string(data, data_length));
  19532. return true;
  19533. });
  19534. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19535. std::chrono::steady_clock::now() - start)
  19536. .count();
  19537. ASSERT_FALSE(res);
  19538. EXPECT_EQ(Error::Read, res.error());
  19539. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19540. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19541. }
  19542. }
  19543. TEST(MaxTimeoutTest, ContentStream) {
  19544. time_t timeout = 2000;
  19545. time_t threshold = 200;
  19546. Server svr;
  19547. Client cli("localhost", PORT);
  19548. max_timeout_test(svr, cli, timeout, threshold);
  19549. }
  19550. #ifdef CPPHTTPLIB_SSL_ENABLED
  19551. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19552. time_t timeout = 2000;
  19553. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19555. SSLClient cli("localhost", PORT);
  19556. cli.enable_server_certificate_verification(false);
  19557. max_timeout_test(svr, cli, timeout, threshold);
  19558. }
  19559. #endif
  19560. class EventDispatcher {
  19561. public:
  19562. EventDispatcher() {}
  19563. bool wait_event(DataSink *sink) {
  19564. unique_lock<mutex> lk(m_);
  19565. int id = id_;
  19566. // Wait with timeout to prevent hanging if client disconnects
  19567. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19568. [&] { return cid_ == id; })) {
  19569. return false; // Timeout occurred
  19570. }
  19571. sink->write(message_.data(), message_.size());
  19572. return true;
  19573. }
  19574. void send_event(const string &message) {
  19575. lock_guard<mutex> lk(m_);
  19576. cid_ = id_++;
  19577. message_ = message;
  19578. cv_.notify_all();
  19579. }
  19580. private:
  19581. mutex m_;
  19582. condition_variable cv_;
  19583. atomic_int id_{0};
  19584. atomic_int cid_{-1};
  19585. string message_;
  19586. };
  19587. TEST(ClientInThreadTest, Issue2068) {
  19588. EventDispatcher ed;
  19589. Server svr;
  19590. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19591. res.set_chunked_content_provider("text/event-stream",
  19592. [&](size_t /*offset*/, DataSink &sink) {
  19593. return ed.wait_event(&sink);
  19594. });
  19595. });
  19596. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19597. svr.wait_until_ready();
  19598. thread event_thread([&] {
  19599. int id = 0;
  19600. while (svr.is_running()) {
  19601. this_thread::sleep_for(chrono::milliseconds(500));
  19602. std::stringstream ss;
  19603. ss << "data: " << id << "\n\n";
  19604. ed.send_event(ss.str());
  19605. id++;
  19606. }
  19607. });
  19608. auto se = detail::scope_exit([&] {
  19609. svr.stop();
  19610. listen_thread.join();
  19611. event_thread.join();
  19612. ASSERT_FALSE(svr.is_running());
  19613. });
  19614. {
  19615. auto client = detail::make_unique<Client>(HOST, PORT);
  19616. client->set_read_timeout(std::chrono::minutes(10));
  19617. std::atomic<bool> stop{false};
  19618. std::thread t([&] {
  19619. client->Get("/event1",
  19620. [&](const char *, size_t) -> bool { return !stop; });
  19621. });
  19622. std::this_thread::sleep_for(std::chrono::seconds(2));
  19623. stop = true;
  19624. client->stop();
  19625. t.join();
  19626. // Reset client after thread has finished
  19627. client.reset();
  19628. }
  19629. }
  19630. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19631. auto handled = false;
  19632. Server svr;
  19633. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19635. auto se = detail::scope_exit([&] {
  19636. svr.stop();
  19637. t.join();
  19638. ASSERT_FALSE(svr.is_running());
  19639. ASSERT_FALSE(handled);
  19640. });
  19641. svr.wait_until_ready();
  19642. // Two Content-Length headers with different values — must be rejected
  19643. auto req = "POST /test HTTP/1.1\r\n"
  19644. "Content-Length: 5\r\n"
  19645. "Content-Length: 10\r\n"
  19646. "\r\n"
  19647. "hello";
  19648. std::string response;
  19649. ASSERT_TRUE(send_request(1, req, &response));
  19650. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19651. response.substr(0, response.find("\r\n")));
  19652. }
  19653. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19654. auto handled = false;
  19655. Server svr;
  19656. svr.Post("/test", [&](const Request &, Response &res) {
  19657. handled = true;
  19658. res.set_content("ok", "text/plain");
  19659. });
  19660. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19661. auto se = detail::scope_exit([&] {
  19662. svr.stop();
  19663. t.join();
  19664. ASSERT_FALSE(svr.is_running());
  19665. ASSERT_TRUE(handled);
  19666. });
  19667. svr.wait_until_ready();
  19668. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19669. auto req = "POST /test HTTP/1.1\r\n"
  19670. "Host: localhost\r\n"
  19671. "Content-Length: 5\r\n"
  19672. "Content-Length: 5\r\n"
  19673. "\r\n"
  19674. "hello";
  19675. std::string response;
  19676. ASSERT_TRUE(send_request(1, req, &response));
  19677. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19678. }
  19679. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19680. Server svr;
  19681. svr.Get("/test", [](const Request &, Response &res) {
  19682. res.set_content("ok", "text/plain");
  19683. });
  19684. auto port = svr.bind_to_any_port(HOST);
  19685. thread t = thread([&] { svr.listen_after_bind(); });
  19686. auto se = detail::scope_exit([&] {
  19687. svr.stop();
  19688. t.join();
  19689. ASSERT_FALSE(svr.is_running());
  19690. });
  19691. svr.wait_until_ready();
  19692. auto status_line = [&](const std::string &host_lines) {
  19693. std::string res;
  19694. send_request(
  19695. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19696. &res, port);
  19697. return res.substr(0, res.find("\r\n"));
  19698. };
  19699. const char *accepted[] = {
  19700. "Host: localhost\r\n",
  19701. "Host: a.example:8080\r\n",
  19702. "Host: my_service\r\n",
  19703. "Host: [::1]:8080\r\n",
  19704. "Host: [fe80::1%25eth0]\r\n",
  19705. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19706. };
  19707. for (auto host_lines : accepted) {
  19708. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19709. }
  19710. const char *rejected[] = {
  19711. "Host: a.example\r\nHost: b.example\r\n",
  19712. "Host: a.example\r\nHost: a.example\r\n",
  19713. "Host: a@b.example\r\n",
  19714. "Host: a.example/b\r\n",
  19715. "Host: a.example\\b\r\n",
  19716. "Host: a.example?b\r\n",
  19717. "Host: a.example#b\r\n",
  19718. "Host: a.example b.example\r\n",
  19719. };
  19720. for (auto host_lines : rejected) {
  19721. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19722. << host_lines;
  19723. }
  19724. }
  19725. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19726. Server svr;
  19727. svr.Get("/", [](const Request &req, Response &res) {
  19728. EXPECT_EQ(2U, req.trailers.size());
  19729. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19730. // Denied
  19731. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19732. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19733. // Accepted
  19734. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19735. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19736. EXPECT_TRUE(req.has_trailer("X-World"));
  19737. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19738. res.set_content("ok", "text/plain");
  19739. });
  19740. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19741. auto se = detail::scope_exit([&] {
  19742. svr.stop();
  19743. t.join();
  19744. ASSERT_FALSE(svr.is_running());
  19745. });
  19746. svr.wait_until_ready();
  19747. const std::string req = "GET / HTTP/1.1\r\n"
  19748. "Transfer-Encoding: chunked\r\n"
  19749. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19750. "\r\n"
  19751. "0\r\n"
  19752. "Content-Length: 10\r\n"
  19753. "Host: internal.local\r\n"
  19754. "Content-Type: malicious/content\r\n"
  19755. "Cookie: any\r\n"
  19756. "Set-Cookie: any\r\n"
  19757. "X-Forwarded-For: attacker.com\r\n"
  19758. "X-Real-Ip: 1.1.1.1\r\n"
  19759. "X-Hello: hello\r\n"
  19760. "X-World: world\r\n"
  19761. "\r\n";
  19762. std::string res;
  19763. ASSERT_TRUE(send_request(1, req, &res));
  19764. }
  19765. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19766. // several field lines, and the combined value is what has to be parsed. A
  19767. // Trailer field split across lines therefore declares every name it lists;
  19768. // reading only the first line silently drops the trailers the later lines
  19769. // declare. The prohibited-trailer filter still applies to every line.
  19770. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19771. Server svr;
  19772. size_t observed_trailer_count = 0;
  19773. std::string observed_hello;
  19774. std::string observed_world;
  19775. bool observed_content_length = true;
  19776. svr.Get("/", [&](const Request &req, Response &res) {
  19777. observed_trailer_count = req.trailers.size();
  19778. observed_hello = req.get_trailer_value("X-Hello");
  19779. observed_world = req.get_trailer_value("X-World");
  19780. observed_content_length = req.has_trailer("Content-Length");
  19781. res.set_content("ok", "text/plain");
  19782. });
  19783. auto port = svr.bind_to_any_port(HOST);
  19784. thread t = thread([&]() { svr.listen_after_bind(); });
  19785. auto se = detail::scope_exit([&] {
  19786. svr.stop();
  19787. t.join();
  19788. ASSERT_FALSE(svr.is_running());
  19789. });
  19790. svr.wait_until_ready();
  19791. const std::string req = "GET / HTTP/1.1\r\n"
  19792. "Host: localhost\r\n"
  19793. "Transfer-Encoding: chunked\r\n"
  19794. "Trailer: X-Hello\r\n"
  19795. "Trailer: X-World, Content-Length\r\n"
  19796. "\r\n"
  19797. "0\r\n"
  19798. "X-Hello: hello\r\n"
  19799. "X-World: world\r\n"
  19800. "Content-Length: 10\r\n"
  19801. "\r\n";
  19802. std::string res;
  19803. ASSERT_TRUE(send_request(1, req, &res, port));
  19804. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19805. // Accepted: both field lines contribute to the declared set
  19806. EXPECT_EQ(2U, observed_trailer_count);
  19807. EXPECT_EQ(observed_hello, "hello");
  19808. EXPECT_EQ(observed_world, "world");
  19809. // Denied: a prohibited name stays prohibited on a later field line
  19810. EXPECT_FALSE(observed_content_length);
  19811. }
  19812. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19813. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19814. // unbounded run of fields that are never declared, because the counter would
  19815. // only advance for declared fields.
  19816. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19817. Server svr;
  19818. bool handler_called = false;
  19819. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19820. handler_called = true;
  19821. res.set_content("ok", "text/plain");
  19822. });
  19823. auto port = svr.bind_to_any_port(HOST);
  19824. thread t = thread([&]() { svr.listen_after_bind(); });
  19825. auto se = detail::scope_exit([&] {
  19826. svr.stop();
  19827. t.join();
  19828. ASSERT_FALSE(svr.is_running());
  19829. });
  19830. svr.wait_until_ready();
  19831. // Declare nothing, then send far more undeclared trailer fields than the
  19832. // header-count limit. Parsing must stop and reject the request rather than
  19833. // read every line.
  19834. std::string req = "GET / HTTP/1.1\r\n"
  19835. "Transfer-Encoding: chunked\r\n"
  19836. "\r\n"
  19837. "0\r\n";
  19838. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19839. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19840. }
  19841. req += "\r\n";
  19842. std::string res;
  19843. ASSERT_TRUE(send_request(1, req, &res, port));
  19844. // The request is rejected before the handler runs.
  19845. EXPECT_FALSE(handler_called);
  19846. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19847. }
  19848. // The set of declared trailer names is capped so a peer cannot grow it without
  19849. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19850. // declared past the cap is not honored, even if the field is actually sent.
  19851. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19852. Server svr;
  19853. // One name inside the cap and one past it, so the test tracks the cap rather
  19854. // than a fixed count.
  19855. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19856. const std::string within_cap_name = "X-T-0";
  19857. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19858. bool observed_within_cap = false;
  19859. bool observed_past_cap = false;
  19860. svr.Get("/", [&](const Request &req, Response &res) {
  19861. observed_within_cap = req.has_trailer(within_cap_name);
  19862. observed_past_cap = req.has_trailer(past_cap_name);
  19863. res.set_content("ok", "text/plain");
  19864. });
  19865. auto port = svr.bind_to_any_port(HOST);
  19866. thread t = thread([&]() { svr.listen_after_bind(); });
  19867. auto se = detail::scope_exit([&] {
  19868. svr.stop();
  19869. t.join();
  19870. ASSERT_FALSE(svr.is_running());
  19871. });
  19872. svr.wait_until_ready();
  19873. // Declare more trailer names than the cap in a single Trailer field, then
  19874. // actually send the first (within the cap) and the last (past it).
  19875. std::string trailer_decl = "Trailer: ";
  19876. for (int i = 0; i < declared_count; i++) {
  19877. if (i != 0) { trailer_decl += ", "; }
  19878. trailer_decl += "X-T-" + std::to_string(i);
  19879. }
  19880. trailer_decl += "\r\n";
  19881. const std::string req = "GET / HTTP/1.1\r\n"
  19882. "Host: localhost\r\n"
  19883. "Transfer-Encoding: chunked\r\n" +
  19884. trailer_decl +
  19885. "\r\n"
  19886. "0\r\n" +
  19887. within_cap_name + ": a\r\n" + past_cap_name +
  19888. ": b\r\n"
  19889. "\r\n";
  19890. std::string res;
  19891. ASSERT_TRUE(send_request(1, req, &res, port));
  19892. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19893. // A name within the cap is honored; one declared past the cap is dropped.
  19894. EXPECT_TRUE(observed_within_cap);
  19895. EXPECT_FALSE(observed_past_cap);
  19896. }
  19897. // A direct client that is not listed in trusted_proxies must not be able to
  19898. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19899. // the peer address on the actual TCP connection determines whether the
  19900. // header is honored.
  19901. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19902. Server svr;
  19903. // Deliberately does NOT include the loopback address the test client
  19904. // actually connects from, so the direct connection is not a trusted proxy.
  19905. svr.set_trusted_proxies({"203.0.113.66"});
  19906. std::string observed_remote_addr;
  19907. svr.Get("/ip", [&](const Request &req, Response &res) {
  19908. observed_remote_addr = req.remote_addr;
  19909. res.set_content("ok", "text/plain");
  19910. });
  19911. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19912. auto se = detail::scope_exit([&] {
  19913. svr.stop();
  19914. t.join();
  19915. ASSERT_FALSE(svr.is_running());
  19916. });
  19917. svr.wait_until_ready();
  19918. Client cli(HOST, PORT);
  19919. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19921. EXPECT_EQ(StatusCode::OK_200, res->status);
  19922. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19923. // ignored entirely and the real connection-level address retained.
  19924. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19925. observed_remote_addr == "127.0.0.1");
  19926. }
  19927. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19928. Server svr;
  19929. std::string observed_remote_addr;
  19930. std::string observed_xff;
  19931. svr.Get("/ip", [&](const Request &req, Response &res) {
  19932. observed_remote_addr = req.remote_addr;
  19933. observed_xff = req.get_header_value("X-Forwarded-For");
  19934. res.set_content("ok", "text/plain");
  19935. });
  19936. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19937. auto se = detail::scope_exit([&] {
  19938. svr.stop();
  19939. t.join();
  19940. ASSERT_FALSE(svr.is_running());
  19941. });
  19942. svr.wait_until_ready();
  19943. Client cli(HOST, PORT);
  19944. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19946. EXPECT_EQ(StatusCode::OK_200, res->status);
  19947. EXPECT_EQ(observed_xff, "203.0.113.66");
  19948. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19949. observed_remote_addr == "127.0.0.1");
  19950. }
  19951. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19952. Server svr;
  19953. svr.set_trusted_proxies({"203.0.113.66"});
  19954. std::string observed_remote_addr;
  19955. std::string observed_xff;
  19956. svr.Get("/ip", [&](const Request &req, Response &res) {
  19957. observed_remote_addr = req.remote_addr;
  19958. observed_xff = req.get_header_value("X-Forwarded-For");
  19959. res.set_content("ok", "text/plain");
  19960. });
  19961. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19962. auto se = detail::scope_exit([&] {
  19963. svr.stop();
  19964. t.join();
  19965. ASSERT_FALSE(svr.is_running());
  19966. });
  19967. svr.wait_until_ready();
  19968. Client cli(HOST, PORT);
  19969. auto res = cli.Get("/ip");
  19970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19971. EXPECT_EQ(StatusCode::OK_200, res->status);
  19972. EXPECT_EQ(observed_xff, "");
  19973. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19974. observed_remote_addr == "127.0.0.1");
  19975. }
  19976. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19977. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19978. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19979. Server svr;
  19980. svr.set_trusted_proxies({"127.0.0.1"});
  19981. svr.Get("/ip", [](const Request &req, Response &res) {
  19982. res.set_content(req.remote_addr, "text/plain");
  19983. });
  19984. auto port = svr.bind_to_any_port("::");
  19985. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19986. thread t = thread([&] { svr.listen_after_bind(); });
  19987. auto se = detail::scope_exit([&] {
  19988. svr.stop();
  19989. t.join();
  19990. ASSERT_FALSE(svr.is_running());
  19991. });
  19992. svr.wait_until_ready();
  19993. Client cli("127.0.0.1", port);
  19994. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19996. EXPECT_EQ("198.51.100.23", res->body);
  19997. }
  19998. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19999. Server svr;
  20000. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20001. svr.Get("/ip", [](const Request &req, Response &res) {
  20002. res.set_content(req.remote_addr, "text/plain");
  20003. });
  20004. auto port = svr.bind_to_any_port(HOST);
  20005. ASSERT_GT(port, 0);
  20006. thread t = thread([&] { svr.listen_after_bind(); });
  20007. auto se = detail::scope_exit([&] {
  20008. svr.stop();
  20009. t.join();
  20010. ASSERT_FALSE(svr.is_running());
  20011. });
  20012. svr.wait_until_ready();
  20013. Client cli(HOST, port);
  20014. auto res = cli.Get(
  20015. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20017. EXPECT_EQ("198.51.100.23", res->body);
  20018. }
  20019. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20020. Server svr;
  20021. // Include the loopback address the test client actually connects from, so
  20022. // the direct connection itself is recognized as the trusted proxy hop.
  20023. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20024. std::string observed_remote_addr;
  20025. std::string observed_xff;
  20026. svr.Get("/ip", [&](const Request &req, Response &res) {
  20027. observed_remote_addr = req.remote_addr;
  20028. observed_xff = req.get_header_value("X-Forwarded-For");
  20029. res.set_content("ok", "text/plain");
  20030. });
  20031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20032. auto se = detail::scope_exit([&] {
  20033. svr.stop();
  20034. t.join();
  20035. ASSERT_FALSE(svr.is_running());
  20036. });
  20037. svr.wait_until_ready();
  20038. Client cli(HOST, PORT);
  20039. auto res = cli.Get(
  20040. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20042. EXPECT_EQ(StatusCode::OK_200, res->status);
  20043. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20044. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20045. }
  20046. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20047. Server svr;
  20048. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20049. std::string observed_remote_addr;
  20050. std::string observed_xff;
  20051. svr.Get("/ip", [&](const Request &req, Response &res) {
  20052. observed_remote_addr = req.remote_addr;
  20053. observed_xff = req.get_header_value("X-Forwarded-For");
  20054. res.set_content("ok", "text/plain");
  20055. });
  20056. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20057. auto se = detail::scope_exit([&] {
  20058. svr.stop();
  20059. t.join();
  20060. ASSERT_FALSE(svr.is_running());
  20061. });
  20062. svr.wait_until_ready();
  20063. Client cli(HOST, PORT);
  20064. auto res = cli.Get(
  20065. "/ip",
  20066. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20068. EXPECT_EQ(StatusCode::OK_200, res->status);
  20069. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20070. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20071. }
  20072. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20073. Server svr;
  20074. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20075. std::string observed_remote_addr;
  20076. std::string observed_xff;
  20077. svr.Get("/ip", [&](const Request &req, Response &res) {
  20078. observed_remote_addr = req.remote_addr;
  20079. observed_xff = req.get_header_value("X-Forwarded-For");
  20080. res.set_content("ok", "text/plain");
  20081. });
  20082. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20083. auto se = detail::scope_exit([&] {
  20084. svr.stop();
  20085. t.join();
  20086. ASSERT_FALSE(svr.is_running());
  20087. });
  20088. svr.wait_until_ready();
  20089. Client cli(HOST, PORT);
  20090. auto res = cli.Get(
  20091. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20093. EXPECT_EQ(StatusCode::OK_200, res->status);
  20094. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20095. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20096. // and must not be selected.
  20097. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20098. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20099. }
  20100. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20101. Server svr;
  20102. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20103. std::string observed_remote_addr;
  20104. svr.Get("/ip", [&](const Request &req, Response &res) {
  20105. observed_remote_addr = req.remote_addr;
  20106. res.set_content("ok", "text/plain");
  20107. });
  20108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20109. auto se = detail::scope_exit([&] {
  20110. svr.stop();
  20111. t.join();
  20112. ASSERT_FALSE(svr.is_running());
  20113. });
  20114. svr.wait_until_ready();
  20115. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20116. // a forged address and the trusted proxy's own address; the forged value must
  20117. // not win over the address the trusted proxy actually recorded.
  20118. Client cli(HOST, PORT);
  20119. auto res = cli.Get(
  20120. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20122. EXPECT_EQ(StatusCode::OK_200, res->status);
  20123. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20124. }
  20125. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20126. Server svr;
  20127. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20128. std::string observed_remote_addr;
  20129. std::string observed_xff;
  20130. svr.Get("/ip", [&](const Request &req, Response &res) {
  20131. observed_remote_addr = req.remote_addr;
  20132. observed_xff = req.get_header_value("X-Forwarded-For");
  20133. res.set_content("ok", "text/plain");
  20134. });
  20135. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20136. auto se = detail::scope_exit([&] {
  20137. svr.stop();
  20138. t.join();
  20139. ASSERT_FALSE(svr.is_running());
  20140. });
  20141. svr.wait_until_ready();
  20142. Client cli(HOST, PORT);
  20143. auto res = cli.Get(
  20144. "/ip",
  20145. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20147. EXPECT_EQ(StatusCode::OK_200, res->status);
  20148. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20149. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20150. }
  20151. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20152. Server svr;
  20153. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20154. std::string observed_remote_addr;
  20155. std::string observed_xff;
  20156. svr.Get("/ip", [&](const Request &req, Response &res) {
  20157. observed_remote_addr = req.remote_addr;
  20158. observed_xff = req.get_header_value("X-Forwarded-For");
  20159. res.set_content("ok", "text/plain");
  20160. });
  20161. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20162. auto se = detail::scope_exit([&] {
  20163. svr.stop();
  20164. t.join();
  20165. ASSERT_FALSE(svr.is_running());
  20166. });
  20167. svr.wait_until_ready();
  20168. std::string raw_req =
  20169. "GET /ip HTTP/1.1\r\n"
  20170. "Host: localhost\r\n"
  20171. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20172. "Connection: close\r\n"
  20173. "\r\n";
  20174. std::string out;
  20175. ASSERT_TRUE(send_request(5, raw_req, &out));
  20176. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20177. // Header parser trims surrounding whitespace of the header value
  20178. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20179. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20180. }
  20181. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20182. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20183. // their own X-Forwarded-For as a separate field line rather than extending the
  20184. // one the client sent, so every occurrence has to be taken into account.
  20185. // Reading only the first one hands back the address the client chose.
  20186. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20187. Server svr;
  20188. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20189. std::string observed_remote_addr;
  20190. size_t observed_xff_count = 0;
  20191. svr.Get("/ip", [&](const Request &req, Response &res) {
  20192. observed_remote_addr = req.remote_addr;
  20193. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20194. res.set_content("ok", "text/plain");
  20195. });
  20196. auto port = svr.bind_to_any_port(HOST);
  20197. thread t = thread([&]() { svr.listen_after_bind(); });
  20198. auto se = detail::scope_exit([&] {
  20199. svr.stop();
  20200. t.join();
  20201. ASSERT_FALSE(svr.is_running());
  20202. });
  20203. svr.wait_until_ready();
  20204. // The client supplies the first field line; the trusted proxy appends the
  20205. // address it observed as a second one.
  20206. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20207. "Host: localhost\r\n"
  20208. "X-Forwarded-For: 1.2.3.4\r\n"
  20209. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20210. "Connection: close\r\n"
  20211. "\r\n";
  20212. std::string out;
  20213. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20214. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20215. EXPECT_EQ(observed_xff_count, 2U);
  20216. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20217. // The same chain spread over one field line per hop derives the same client
  20218. // address, i.e. the split and the comma-joined representations agree.
  20219. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20220. "Host: localhost\r\n"
  20221. "X-Forwarded-For: 1.2.3.4\r\n"
  20222. "X-Forwarded-For: 198.51.100.23\r\n"
  20223. "X-Forwarded-For: 192.0.2.45\r\n"
  20224. "Connection: close\r\n"
  20225. "\r\n";
  20226. out.clear();
  20227. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20228. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20229. EXPECT_EQ(observed_xff_count, 3U);
  20230. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20231. }
  20232. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20233. // crash the server (it used to call front() on an empty vector inside
  20234. // get_client_ip). The connection-level remote address must be retained instead.
  20235. static void run_malformed_xff_test(const std::string &xff_value) {
  20236. Server svr;
  20237. svr.set_trusted_proxies({"192.0.2.45"});
  20238. std::string observed_remote_addr;
  20239. svr.Get("/ip", [&](const Request &req, Response &res) {
  20240. observed_remote_addr = req.remote_addr;
  20241. res.set_content("ok", "text/plain");
  20242. });
  20243. int port = 0;
  20244. thread t = thread([&]() {
  20245. port = svr.bind_to_any_port(HOST);
  20246. svr.listen_after_bind();
  20247. });
  20248. auto se = detail::scope_exit([&] {
  20249. svr.stop();
  20250. t.join();
  20251. ASSERT_FALSE(svr.is_running());
  20252. });
  20253. svr.wait_until_ready();
  20254. Client cli(HOST, port);
  20255. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20257. EXPECT_EQ(StatusCode::OK_200, res->status);
  20258. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20259. observed_remote_addr == "127.0.0.1");
  20260. }
  20261. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20262. run_malformed_xff_test("");
  20263. }
  20264. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20265. run_malformed_xff_test(",");
  20266. }
  20267. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20268. run_malformed_xff_test(", , ,");
  20269. }
  20270. // The same rule applies to Accept: a request whose acceptable types are spread
  20271. // over several field lines must be negotiated against all of them.
  20272. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20273. // case-insensitive connection options. Comparing the whole field value against
  20274. // one option misses a client that sends several of them, and misses every
  20275. // casing but the one written in the comparison.
  20276. //
  20277. // Sends req, reads the response, then reuses the same socket for a second
  20278. // request to find out whether the server kept the connection.
  20279. static void probe_connection_reuse(int port, const std::string &req,
  20280. bool *announced_close, bool *reusable) {
  20281. auto error = Error::Success;
  20282. auto sock = detail::create_client_socket(
  20283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20284. /*connection_timeout_sec=*/5, 0,
  20285. /*read_timeout_sec=*/1, 0,
  20286. /*write_timeout_sec=*/5, 0, std::string(), error);
  20287. ASSERT_NE(sock, INVALID_SOCKET);
  20288. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20289. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20290. "Host: localhost\r\n"
  20291. "Connection: close\r\n"
  20292. "\r\n";
  20293. std::string first_response;
  20294. std::string second_response;
  20295. detail::process_client_socket(
  20296. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20297. [&](Stream &strm) {
  20298. if (strm.write(req.data(), req.size()) !=
  20299. static_cast<ssize_t>(req.size())) {
  20300. return false;
  20301. }
  20302. char buf[512];
  20303. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20304. // Headers plus the two-byte body of the handler below
  20305. while (reader.getline()) {
  20306. first_response += reader.ptr();
  20307. if (first_response.find("ok") != std::string::npos) { break; }
  20308. }
  20309. if (strm.write(second.data(), second.size()) !=
  20310. static_cast<ssize_t>(second.size())) {
  20311. return true;
  20312. }
  20313. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20314. while (reader2.getline()) {
  20315. second_response += reader2.ptr();
  20316. if (second_response.find("ok") != std::string::npos) { break; }
  20317. }
  20318. return true;
  20319. });
  20320. *announced_close =
  20321. first_response.find("Connection: close") != std::string::npos;
  20322. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20323. }
  20324. class ConnectionTokenTest : public ::testing::Test {
  20325. protected:
  20326. void SetUp() override {
  20327. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20328. res.set_content("ok", "text/plain");
  20329. });
  20330. port_ = svr_.bind_to_any_port(HOST);
  20331. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20332. svr_.wait_until_ready();
  20333. }
  20334. void TearDown() override {
  20335. svr_.stop();
  20336. if (thread_.joinable()) { thread_.join(); }
  20337. }
  20338. Server svr_;
  20339. int port_ = 0;
  20340. thread thread_;
  20341. };
  20342. // "close" alongside another option still closes the connection, and the
  20343. // response says so rather than leaving the peer to discover it.
  20344. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20345. bool announced_close = false;
  20346. bool reusable = true;
  20347. probe_connection_reuse(port_,
  20348. "GET /keepalive HTTP/1.1\r\n"
  20349. "Host: localhost\r\n"
  20350. "Connection: keep-alive, close\r\n"
  20351. "\r\n",
  20352. &announced_close, &reusable);
  20353. EXPECT_TRUE(announced_close);
  20354. EXPECT_FALSE(reusable);
  20355. }
  20356. // "close" split over two field lines is the same list, so it is honored too.
  20357. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20358. bool announced_close = false;
  20359. bool reusable = true;
  20360. probe_connection_reuse(port_,
  20361. "GET /keepalive HTTP/1.1\r\n"
  20362. "Host: localhost\r\n"
  20363. "Connection: keep-alive\r\n"
  20364. "Connection: close\r\n"
  20365. "\r\n",
  20366. &announced_close, &reusable);
  20367. EXPECT_TRUE(announced_close);
  20368. EXPECT_FALSE(reusable);
  20369. }
  20370. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20371. // keep-alive in the spelling everyone actually sends keeps its connection.
  20372. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20373. bool announced_close = false;
  20374. bool reusable = false;
  20375. probe_connection_reuse(port_,
  20376. "GET /keepalive HTTP/1.0\r\n"
  20377. "Host: localhost\r\n"
  20378. "Connection: keep-alive\r\n"
  20379. "\r\n",
  20380. &announced_close, &reusable);
  20381. EXPECT_FALSE(announced_close);
  20382. EXPECT_TRUE(reusable);
  20383. }
  20384. // A token the value merely contains is not the token itself.
  20385. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20386. bool announced_close = false;
  20387. bool reusable = false;
  20388. probe_connection_reuse(port_,
  20389. "GET /keepalive HTTP/1.1\r\n"
  20390. "Host: localhost\r\n"
  20391. "Connection: notclose\r\n"
  20392. "\r\n",
  20393. &announced_close, &reusable);
  20394. EXPECT_FALSE(announced_close);
  20395. EXPECT_TRUE(reusable);
  20396. }
  20397. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20398. Server svr;
  20399. std::vector<std::string> observed_types;
  20400. svr.Get("/", [&](const Request &req, Response &res) {
  20401. observed_types = req.accept_content_types;
  20402. res.set_content("ok", "text/plain");
  20403. });
  20404. auto port = svr.bind_to_any_port(HOST);
  20405. thread t = thread([&]() { svr.listen_after_bind(); });
  20406. auto se = detail::scope_exit([&] {
  20407. svr.stop();
  20408. t.join();
  20409. ASSERT_FALSE(svr.is_running());
  20410. });
  20411. svr.wait_until_ready();
  20412. Client cli(HOST, port);
  20413. Headers headers;
  20414. headers.emplace("Accept", "text/plain;q=0.5");
  20415. headers.emplace("Accept", "application/json");
  20416. auto res = cli.Get("/", headers);
  20417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20418. EXPECT_EQ(StatusCode::OK_200, res->status);
  20419. // Sorted by q-value, so the second field line's type comes first
  20420. ASSERT_EQ(2U, observed_types.size());
  20421. EXPECT_EQ("application/json", observed_types[0]);
  20422. EXPECT_EQ("text/plain", observed_types[1]);
  20423. }
  20424. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20425. // empty field line must not contribute a bare comma to the combined value.
  20426. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20427. Server svr;
  20428. std::vector<std::string> observed_types;
  20429. svr.Get("/", [&](const Request &req, Response &res) {
  20430. observed_types = req.accept_content_types;
  20431. res.set_content("ok", "text/plain");
  20432. });
  20433. auto port = svr.bind_to_any_port(HOST);
  20434. thread t = thread([&]() { svr.listen_after_bind(); });
  20435. auto se = detail::scope_exit([&] {
  20436. svr.stop();
  20437. t.join();
  20438. ASSERT_FALSE(svr.is_running());
  20439. });
  20440. svr.wait_until_ready();
  20441. // Empty first field line, then a real one
  20442. std::string raw_req = "GET / HTTP/1.1\r\n"
  20443. "Host: localhost\r\n"
  20444. "Accept:\r\n"
  20445. "Accept: application/json\r\n"
  20446. "Connection: close\r\n"
  20447. "\r\n";
  20448. std::string out;
  20449. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20450. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20451. ASSERT_EQ(1U, observed_types.size());
  20452. EXPECT_EQ("application/json", observed_types[0]);
  20453. }
  20454. // The skip in get_combined_header_value() is what keeps an empty field line
  20455. // from contributing a bare comma. Only a trailing empty field line exercises
  20456. // it: a leading one is already covered by the "combined is still empty" check,
  20457. // and parse_accept_header() now ignores the empty element either way, so the
  20458. // request-level test above can no longer tell the two apart.
  20459. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20460. Headers headers;
  20461. headers.emplace("Accept", "text/html");
  20462. headers.emplace("Accept", "");
  20463. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20464. headers.clear();
  20465. headers.emplace("Accept", "");
  20466. headers.emplace("Accept", "application/json");
  20467. EXPECT_EQ("application/json",
  20468. detail::get_combined_header_value(headers, "Accept"));
  20469. }
  20470. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20471. // An encoding offered on a later Accept-Encoding field line is still offered.
  20472. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20473. Server svr;
  20474. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20475. res.set_content(std::string(1024, 'x'), "text/plain");
  20476. });
  20477. auto port = svr.bind_to_any_port(HOST);
  20478. thread t = thread([&]() { svr.listen_after_bind(); });
  20479. auto se = detail::scope_exit([&] {
  20480. svr.stop();
  20481. t.join();
  20482. ASSERT_FALSE(svr.is_running());
  20483. });
  20484. svr.wait_until_ready();
  20485. Client cli(HOST, port);
  20486. cli.set_decompress(false);
  20487. Headers headers;
  20488. headers.emplace("Accept-Encoding", "identity");
  20489. headers.emplace("Accept-Encoding", "gzip");
  20490. auto res = cli.Get("/", headers);
  20491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20492. EXPECT_EQ(StatusCode::OK_200, res->status);
  20493. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20494. }
  20495. #endif
  20496. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20497. // Transfer-Encoding is not its body.
  20498. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20499. Server svr;
  20500. svr.set_payload_max_length(8);
  20501. svr.Post("/test", [](const Request &, Response &res) {
  20502. res.set_content("ok", "text/plain");
  20503. });
  20504. auto port = svr.bind_to_any_port(HOST);
  20505. ASSERT_GT(port, 0);
  20506. thread t = thread([&] { svr.listen_after_bind(); });
  20507. auto se = detail::scope_exit([&] {
  20508. svr.stop();
  20509. t.join();
  20510. ASSERT_FALSE(svr.is_running());
  20511. });
  20512. svr.wait_until_ready();
  20513. std::string resp;
  20514. ASSERT_TRUE(send_request(1,
  20515. "POST /test HTTP/1.1\r\n"
  20516. "Host: localhost\r\n"
  20517. "Connection: close\r\n"
  20518. "\r\n" +
  20519. std::string(16, 'X'),
  20520. &resp, port));
  20521. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20522. }
  20523. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20524. Server svr;
  20525. svr.Post("/post", [&](const Request &req, Response &res) {
  20526. res.set_content(req.body, "text/plain");
  20527. });
  20528. svr.Put("/put", [&](const Request &req, Response &res) {
  20529. res.set_content(req.body, "text/plain");
  20530. });
  20531. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20532. res.set_content(req.body, "text/plain");
  20533. });
  20534. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20535. res.set_content(req.body, "text/plain");
  20536. });
  20537. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20538. auto se = detail::scope_exit([&] {
  20539. svr.stop();
  20540. t.join();
  20541. ASSERT_FALSE(svr.is_running());
  20542. });
  20543. svr.wait_until_ready();
  20544. std::string resp;
  20545. // POST without Content-Length
  20546. ASSERT_TRUE(send_request(5,
  20547. "POST /post HTTP/1.1\r\n"
  20548. "Host: localhost\r\n"
  20549. "Connection: close\r\n"
  20550. "\r\n",
  20551. &resp));
  20552. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20553. // PUT without Content-Length
  20554. resp.clear();
  20555. ASSERT_TRUE(send_request(5,
  20556. "PUT /put HTTP/1.1\r\n"
  20557. "Host: localhost\r\n"
  20558. "Connection: close\r\n"
  20559. "\r\n",
  20560. &resp));
  20561. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20562. // PATCH without Content-Length
  20563. resp.clear();
  20564. ASSERT_TRUE(send_request(5,
  20565. "PATCH /patch HTTP/1.1\r\n"
  20566. "Host: localhost\r\n"
  20567. "Connection: close\r\n"
  20568. "\r\n",
  20569. &resp));
  20570. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20571. // DELETE without Content-Length
  20572. resp.clear();
  20573. ASSERT_TRUE(send_request(5,
  20574. "DELETE /delete HTTP/1.1\r\n"
  20575. "Host: localhost\r\n"
  20576. "Connection: close\r\n"
  20577. "\r\n",
  20578. &resp));
  20579. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20580. }
  20581. //==============================================================================
  20582. // open_stream() Tests
  20583. //==============================================================================
  20584. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20585. std::string result;
  20586. char buf[8192];
  20587. ssize_t n;
  20588. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20589. result.append(buf, static_cast<size_t>(n));
  20590. }
  20591. return result;
  20592. }
  20593. // Mock stream for unit tests
  20594. class MockStream : public Stream {
  20595. public:
  20596. std::string data;
  20597. size_t pos = 0;
  20598. ssize_t error_after = -1; // -1 = no error
  20599. explicit MockStream(const std::string &d, ssize_t err = -1)
  20600. : data(d), error_after(err) {}
  20601. bool is_readable() const override { return true; }
  20602. bool wait_readable() const override { return true; }
  20603. bool wait_writable() const override { return true; }
  20604. ssize_t read(char *ptr, size_t size) override {
  20605. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20606. if (pos >= data.size()) return 0;
  20607. size_t limit =
  20608. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20609. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20610. std::memcpy(ptr, data.data() + pos, to_read);
  20611. pos += to_read;
  20612. return static_cast<ssize_t>(to_read);
  20613. }
  20614. ssize_t write(const char *, size_t) override { return -1; }
  20615. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20616. ip = "127.0.0.1";
  20617. port = 0;
  20618. }
  20619. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20620. ip = "127.0.0.1";
  20621. port = 0;
  20622. }
  20623. socket_t socket() const override { return INVALID_SOCKET; }
  20624. time_t duration() const override { return 0; }
  20625. };
  20626. TEST(StreamHandleTest, Basic) {
  20627. ClientImpl::StreamHandle handle;
  20628. EXPECT_FALSE(handle.is_valid());
  20629. handle.response = detail::make_unique<Response>();
  20630. handle.error = Error::Connection;
  20631. EXPECT_FALSE(handle.is_valid());
  20632. handle.error = Error::Success;
  20633. EXPECT_TRUE(handle.is_valid());
  20634. }
  20635. TEST(BodyReaderTest, Basic) {
  20636. MockStream stream("Hello, World!");
  20637. detail::BodyReader reader;
  20638. reader.stream = &stream;
  20639. reader.content_length = 13;
  20640. char buf[32];
  20641. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20642. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20643. EXPECT_TRUE(reader.eof);
  20644. }
  20645. TEST(BodyReaderTest, NoStream) {
  20646. detail::BodyReader reader;
  20647. char buf[32];
  20648. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20649. EXPECT_EQ(Error::Connection, reader.last_error);
  20650. }
  20651. TEST(BodyReaderTest, Error) {
  20652. MockStream stream("Hello, World!", 5);
  20653. detail::BodyReader reader;
  20654. reader.stream = &stream;
  20655. reader.content_length = 13;
  20656. char buf[32];
  20657. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20658. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20659. EXPECT_EQ(Error::Read, reader.last_error);
  20660. }
  20661. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20662. // Mock-based StreamHandle tests relying on private internals are removed.
  20663. class OpenStreamTest : public ::testing::Test {
  20664. protected:
  20665. void SetUp() override {
  20666. svr_.Get("/hello", [](const Request &, Response &res) {
  20667. res.set_content("Hello World!", "text/plain");
  20668. });
  20669. svr_.Get("/large", [](const Request &, Response &res) {
  20670. res.set_content(std::string(10000, 'X'), "text/plain");
  20671. });
  20672. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20673. res.set_content("Hello World!", "image/jpeg");
  20674. res.set_header("Content-Encoding", "UTF-8");
  20675. });
  20676. svr_.Get("/chunked", [](const Request &, Response &res) {
  20677. res.set_chunked_content_provider("text/plain",
  20678. [](size_t offset, DataSink &sink) {
  20679. if (offset < 15) {
  20680. sink.write("chunk", 5);
  20681. return true;
  20682. }
  20683. sink.done();
  20684. return true;
  20685. });
  20686. });
  20687. svr_.Get("/compressible", [](const Request &, Response &res) {
  20688. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20689. DataSink &sink) {
  20690. if (offset < 100 * 1024) {
  20691. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20692. sink.write(chunk.data(), chunk.size());
  20693. return true;
  20694. }
  20695. sink.done();
  20696. return true;
  20697. });
  20698. });
  20699. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20700. [](const Request & /*req*/, Response &res) {
  20701. auto i = new int(0);
  20702. res.set_header("Trailer", "Content-Length, X-Allowed");
  20703. res.set_chunked_content_provider(
  20704. "text/plain",
  20705. [i](size_t /*offset*/, DataSink &sink) {
  20706. switch (*i) {
  20707. case 0: sink.os << "123"; break;
  20708. case 1: sink.os << "456"; break;
  20709. case 2: sink.os << "789"; break;
  20710. case 3: {
  20711. sink.done_with_trailer(
  20712. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20713. } break;
  20714. }
  20715. (*i)++;
  20716. return true;
  20717. },
  20718. [i](bool success) {
  20719. EXPECT_TRUE(success);
  20720. delete i;
  20721. });
  20722. });
  20723. // Echo headers endpoint for header-related tests
  20724. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20725. std::string body;
  20726. for (const auto &h : req.headers) {
  20727. body.append(h.first);
  20728. body.push_back(':');
  20729. body.append(h.second);
  20730. body.push_back('\n');
  20731. }
  20732. res.set_content(body, "text/plain");
  20733. });
  20734. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20735. std::string body;
  20736. for (const auto &h : req.headers) {
  20737. body.append(h.first);
  20738. body.push_back(':');
  20739. body.append(h.second);
  20740. body.push_back('\n');
  20741. }
  20742. res.set_content(body, "text/plain");
  20743. });
  20744. port_ = svr_.bind_to_any_port("127.0.0.1");
  20745. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20746. svr_.wait_until_ready();
  20747. }
  20748. void TearDown() override {
  20749. svr_.stop();
  20750. if (thread_.joinable()) thread_.join();
  20751. }
  20752. Server svr_;
  20753. std::thread thread_;
  20754. int port_ = 0;
  20755. };
  20756. TEST_F(OpenStreamTest, Basic) {
  20757. Client cli("127.0.0.1", port_);
  20758. auto handle = cli.open_stream("GET", "/hello");
  20759. EXPECT_TRUE(handle.is_valid());
  20760. EXPECT_EQ("Hello World!", read_all(handle));
  20761. }
  20762. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20763. Client cli("127.0.0.1", port_);
  20764. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20765. ASSERT_TRUE(handle.is_valid());
  20766. EXPECT_EQ("Hello World!", read_all(handle));
  20767. }
  20768. TEST_F(OpenStreamTest, SmallBuffer) {
  20769. Client cli("127.0.0.1", port_);
  20770. auto handle = cli.open_stream("GET", "/hello");
  20771. std::string result;
  20772. char buf[4];
  20773. ssize_t n;
  20774. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20775. result.append(buf, static_cast<size_t>(n));
  20776. EXPECT_EQ("Hello World!", result);
  20777. }
  20778. TEST_F(OpenStreamTest, DefaultHeaders) {
  20779. Client cli("127.0.0.1", port_);
  20780. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20781. {
  20782. auto handle = cli.open_stream("GET", "/echo-headers");
  20783. ASSERT_TRUE(handle.is_valid());
  20784. auto body = read_all(handle);
  20785. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20786. std::string::npos);
  20787. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20788. std::string::npos);
  20789. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20790. }
  20791. // open_stream POST with body and no explicit content_type should NOT add
  20792. // text/plain Content-Type (behavior differs from non-streaming path), but
  20793. // should include Content-Length
  20794. {
  20795. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20796. ASSERT_TRUE(handle.is_valid());
  20797. auto body = read_all(handle);
  20798. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20799. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20800. }
  20801. // open_stream POST with explicit Content-Type should preserve it
  20802. {
  20803. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20804. {{"Content-Type", "application/custom"}},
  20805. "{}", "application/custom");
  20806. ASSERT_TRUE(handle.is_valid());
  20807. auto body = read_all(handle);
  20808. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20809. }
  20810. // User-specified User-Agent must not be overwritten for stream API
  20811. {
  20812. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20813. {{"User-Agent", "MyAgent/1.2"}});
  20814. ASSERT_TRUE(handle.is_valid());
  20815. auto body = read_all(handle);
  20816. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20817. }
  20818. }
  20819. TEST_F(OpenStreamTest, Large) {
  20820. Client cli("127.0.0.1", port_);
  20821. auto handle = cli.open_stream("GET", "/large");
  20822. EXPECT_EQ(10000u, read_all(handle).size());
  20823. }
  20824. TEST_F(OpenStreamTest, ConnectionError) {
  20825. Client cli("127.0.0.1", 9999);
  20826. auto handle = cli.open_stream("GET", "/hello");
  20827. EXPECT_FALSE(handle.is_valid());
  20828. }
  20829. TEST_F(OpenStreamTest, Chunked) {
  20830. Client cli("127.0.0.1", port_);
  20831. auto handle = cli.open_stream("GET", "/chunked");
  20832. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20833. "Transfer-Encoding") == "chunked");
  20834. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20835. }
  20836. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20837. Client cli("127.0.0.1", port_);
  20838. auto handle =
  20839. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20840. ASSERT_TRUE(handle.is_valid());
  20841. // Consume body to allow trailers to be received/parsed
  20842. auto body = read_all(handle);
  20843. // Explicitly parse trailers (ensure trailers are available for assertion)
  20844. handle.parse_trailers_if_needed();
  20845. EXPECT_EQ(std::string("123456789"), body);
  20846. // The response should include a Trailer header declaring both names
  20847. ASSERT_TRUE(handle.response);
  20848. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20849. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20850. handle.response->get_header_value("Trailer"));
  20851. // Prohibited trailer must not be present
  20852. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20853. // Allowed trailer should be present
  20854. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20855. EXPECT_EQ(std::string("yes"),
  20856. handle.response->get_trailer_value("X-Allowed"));
  20857. // Verify trailers are NOT present as regular headers
  20858. EXPECT_EQ(std::string(""),
  20859. handle.response->get_header_value("Content-Length"));
  20860. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20861. }
  20862. // Accepts one connection on an OS-assigned port, which it hands over through
  20863. // port_promise, reads the request head and sends back response. after_send,
  20864. // if given, runs on the connection before it is closed.
  20865. static std::thread
  20866. serve_single_response(std::promise<int> &port_promise,
  20867. const std::string &response,
  20868. std::function<void(socket_t)> after_send = nullptr) {
  20869. return std::thread([&port_promise, response, after_send] {
  20870. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20871. default_socket_options(srv);
  20872. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20874. sockaddr_in addr{};
  20875. addr.sin_family = AF_INET;
  20876. addr.sin_port = htons(0); // Let OS assign a free port
  20877. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20878. int opt = 1;
  20879. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20880. #ifdef _WIN32
  20881. reinterpret_cast<const char *>(&opt),
  20882. #else
  20883. &opt,
  20884. #endif
  20885. sizeof(opt));
  20886. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20887. ::listen(srv, 1) != 0) {
  20888. port_promise.set_value(-1);
  20889. detail::close_socket(srv);
  20890. return;
  20891. }
  20892. socklen_t addr_len = sizeof(addr);
  20893. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20894. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20895. sockaddr_in cli_addr{};
  20896. socklen_t cli_len = sizeof(cli_addr);
  20897. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20898. if (cli != INVALID_SOCKET) {
  20899. // Read the complete HTTP request (until the blank line that terminates
  20900. // headers) before sending the response. If the server closes the socket
  20901. // while the client's request data is still unread in the kernel receive
  20902. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20903. // connection on both sides: it discards the client's receive buffer
  20904. // (which already holds our response) and causes any in-progress write on
  20905. // the client to fail with ECONNRESET. Reading all request data first
  20906. // ensures close() emits a graceful FIN.
  20907. {
  20908. char rbuf[256];
  20909. std::string req;
  20910. while (req.find("\r\n\r\n") == std::string::npos) {
  20911. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20912. if (n <= 0) { break; }
  20913. req.append(rbuf, static_cast<size_t>(n));
  20914. }
  20915. }
  20916. ::send(cli,
  20917. #ifdef _WIN32
  20918. static_cast<const char *>(response.c_str()),
  20919. static_cast<int>(response.size()),
  20920. #else
  20921. response.c_str(), response.size(),
  20922. #endif
  20923. 0);
  20924. if (after_send) { after_send(cli); }
  20925. detail::close_socket(cli);
  20926. }
  20927. detail::close_socket(srv);
  20928. });
  20929. }
  20930. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20931. #ifndef _WIN32
  20932. signal(SIGPIPE, SIG_IGN);
  20933. #endif
  20934. std::promise<int> port_promise;
  20935. auto port_future = port_promise.get_future();
  20936. auto server_thread =
  20937. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20938. "Content-Type: text/plain\r\n"
  20939. "Content-Length: not-a-number\r\n"
  20940. "Connection: close\r\n"
  20941. "\r\n"
  20942. "hello");
  20943. auto port = port_future.get();
  20944. ASSERT_GT(port, 0);
  20945. Client cli("127.0.0.1", port);
  20946. auto handle = cli.open_stream("GET", "/");
  20947. EXPECT_FALSE(handle.is_valid());
  20948. server_thread.join();
  20949. }
  20950. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20951. #ifndef _WIN32
  20952. signal(SIGPIPE, SIG_IGN);
  20953. #endif
  20954. std::promise<int> port_promise;
  20955. auto port_future = port_promise.get_future();
  20956. auto server_thread = serve_single_response(
  20957. port_promise, "HTTP/1.1 200 OK\r\n"
  20958. "Content-Type: text/plain\r\n"
  20959. "Content-Length: 99999999999999999999999999\r\n"
  20960. "Connection: close\r\n"
  20961. "\r\n"
  20962. "hello");
  20963. auto port = port_future.get();
  20964. ASSERT_GT(port, 0);
  20965. // Historically std::stoull would throw std::out_of_range here and crash
  20966. // the process, then parsing silently clamped to a bogus framing length and
  20967. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20968. // so the stream fails to open, matching the not-a-number case above. The
  20969. // process still must NOT terminate.
  20970. Client cli("127.0.0.1", port);
  20971. auto handle = cli.open_stream("GET", "/");
  20972. EXPECT_FALSE(handle.is_valid());
  20973. server_thread.join();
  20974. }
  20975. #ifndef _WIN32
  20976. // As above for the body of a streamed request: a send() cut short by the write
  20977. // timeout must not leave the rest of the body unsent.
  20978. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20979. signal(SIGPIPE, SIG_IGN);
  20980. Server svr;
  20981. svr.set_socket_options([](socket_t sock) {
  20982. int size = 8192;
  20983. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20984. reinterpret_cast<const char *>(&size), sizeof(size));
  20985. });
  20986. svr.Post("/size", [](const Request &, Response &res,
  20987. const ContentReader &content_reader) {
  20988. // Outlast the client's write timeout before reading the body.
  20989. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20990. size_t received = 0;
  20991. content_reader([&](const char *, size_t len) {
  20992. received += len;
  20993. return true;
  20994. });
  20995. res.set_content(std::to_string(received), "text/plain");
  20996. });
  20997. auto port = svr.bind_to_any_port(HOST);
  20998. std::thread t([&]() { svr.listen_after_bind(); });
  20999. auto se = detail::scope_exit([&] {
  21000. svr.stop();
  21001. t.join();
  21002. });
  21003. svr.wait_until_ready();
  21004. Client cli(HOST, port);
  21005. cli.set_write_timeout(0, 500000);
  21006. cli.set_socket_options([](socket_t sock) {
  21007. int size = 8192;
  21008. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21009. reinterpret_cast<const char *>(&size), sizeof(size));
  21010. });
  21011. const std::string body(4 * 1024 * 1024, 'A');
  21012. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21013. "application/octet-stream");
  21014. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21015. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21016. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21017. }
  21018. #endif
  21019. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21020. std::promise<void> slow_started;
  21021. auto slow_started_future = slow_started.get_future();
  21022. Server svr;
  21023. svr.Get("/slow", [&](const Request &, Response &res) {
  21024. slow_started.set_value();
  21025. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21026. res.set_content("slow", "text/plain");
  21027. });
  21028. svr.Get("/fast", [](const Request &, Response &res) {
  21029. res.set_content("fast", "text/plain");
  21030. });
  21031. auto port = svr.bind_to_any_port(HOST);
  21032. std::thread t([&]() { svr.listen_after_bind(); });
  21033. auto se = detail::scope_exit([&] {
  21034. svr.stop();
  21035. t.join();
  21036. });
  21037. svr.wait_until_ready();
  21038. Client cli(HOST, port);
  21039. std::string slow_body;
  21040. std::thread slow_thread([&] {
  21041. auto res = cli.Get("/slow");
  21042. if (res) { slow_body = res->body; }
  21043. });
  21044. slow_started_future.wait();
  21045. auto result = stream::Get(cli, "/fast");
  21046. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21047. slow_thread.join();
  21048. EXPECT_EQ("slow", slow_body);
  21049. EXPECT_EQ("fast", fast_body);
  21050. }
  21051. // Serves `response` to the single request `fn` makes with a fresh client.
  21052. template <typename Fn>
  21053. static void with_single_response(const std::string &response, Fn fn) {
  21054. #ifndef _WIN32
  21055. signal(SIGPIPE, SIG_IGN);
  21056. #endif
  21057. std::promise<int> port_promise;
  21058. auto port_future = port_promise.get_future();
  21059. auto server_thread = serve_single_response(port_promise, response);
  21060. auto se = detail::scope_exit([&] { server_thread.join(); });
  21061. auto port = port_future.get();
  21062. ASSERT_GT(port, 0);
  21063. Client cli("127.0.0.1", port);
  21064. fn(cli);
  21065. }
  21066. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21067. // too, also in a build without the decoder for the advertised coding.
  21068. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21069. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21070. const auto response = "HTTP/1.1 200 OK\r\n"
  21071. "Content-Encoding: gzip\r\n"
  21072. "Content-Length: " +
  21073. std::to_string(gzipped.size()) +
  21074. "\r\n"
  21075. "Connection: close\r\n\r\n" +
  21076. gzipped;
  21077. with_single_response(response, [&](Client &cli) {
  21078. cli.set_decompress(false);
  21079. auto handle = cli.open_stream("GET", "/");
  21080. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21081. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21082. EXPECT_EQ(gzipped, read_all(handle));
  21083. EXPECT_FALSE(handle.has_read_error());
  21084. });
  21085. with_single_response(response, [&](Client &cli) {
  21086. cli.set_decompress(false);
  21087. auto res = stream::Get(cli, "/", 7);
  21088. ASSERT_TRUE(res) << to_string(res.error());
  21089. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21090. EXPECT_EQ(gzipped, res.read_all());
  21091. EXPECT_FALSE(res.has_read_error());
  21092. });
  21093. }
  21094. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21095. // Neither Content-Length nor chunked: the body ends at the close
  21096. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21097. "Connection: close\r\n"
  21098. "\r\n"
  21099. "hello";
  21100. with_single_response(close_delimited, [](Client &cli) {
  21101. auto handle = cli.open_stream("GET", "/");
  21102. ASSERT_TRUE(handle.is_valid());
  21103. EXPECT_EQ("hello", read_all(handle));
  21104. EXPECT_FALSE(handle.has_read_error());
  21105. });
  21106. // A close before the end of the Content-Length is still an error
  21107. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21108. "Content-Length: 10\r\n"
  21109. "\r\n"
  21110. "hello";
  21111. with_single_response(short_content_length, [](Client &cli) {
  21112. auto handle = cli.open_stream("GET", "/");
  21113. ASSERT_TRUE(handle.is_valid());
  21114. read_all(handle);
  21115. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21116. });
  21117. // So is a close before the last chunk
  21118. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21119. "Transfer-Encoding: chunked\r\n"
  21120. "\r\n"
  21121. "5\r\nhello\r\n";
  21122. with_single_response(short_chunked, [](Client &cli) {
  21123. auto handle = cli.open_stream("GET", "/");
  21124. ASSERT_TRUE(handle.is_valid());
  21125. read_all(handle);
  21126. EXPECT_TRUE(handle.has_read_error());
  21127. });
  21128. }
  21129. #ifdef CPPHTTPLIB_SSL_ENABLED
  21130. // Serves `response` to one request, then closes with or without a close_notify
  21131. template <typename Fn>
  21132. static void with_single_tls_response(const std::string &response,
  21133. bool close_notify, Fn fn) {
  21134. #ifndef _WIN32
  21135. signal(SIGPIPE, SIG_IGN);
  21136. #endif
  21137. std::promise<int> port_promise;
  21138. auto port_future = port_promise.get_future();
  21139. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21140. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21141. default_socket_options(srv);
  21142. sockaddr_in addr{};
  21143. addr.sin_family = AF_INET;
  21144. addr.sin_port = htons(0);
  21145. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21146. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21147. ::listen(srv, 1) != 0) {
  21148. port_promise.set_value(-1);
  21149. detail::close_socket(srv);
  21150. return;
  21151. }
  21152. socklen_t addr_len = sizeof(addr);
  21153. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21154. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21155. auto cli = ::accept(srv, nullptr, nullptr);
  21156. if (cli != INVALID_SOCKET) {
  21157. auto ctx = tls::create_server_context();
  21158. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21159. nullptr);
  21160. auto session = tls::create_session(ctx, cli);
  21161. tls::TlsError err;
  21162. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21163. // The request head first, so that closing the socket sends a FIN
  21164. // rather than an RST for the unread bytes.
  21165. std::string req;
  21166. char buf[256];
  21167. while (req.find("\r\n\r\n") == std::string::npos) {
  21168. auto n = tls::read(session, buf, sizeof(buf), err);
  21169. if (n <= 0) { break; }
  21170. req.append(buf, static_cast<size_t>(n));
  21171. }
  21172. size_t sent = 0;
  21173. while (sent < response.size()) {
  21174. auto n = tls::write(session, response.data() + sent,
  21175. response.size() - sent, err);
  21176. if (n <= 0) { break; }
  21177. sent += static_cast<size_t>(n);
  21178. }
  21179. if (close_notify) { tls::shutdown(session, true); }
  21180. }
  21181. tls::free_session(session);
  21182. detail::close_socket(cli);
  21183. tls::free_context(ctx);
  21184. }
  21185. detail::close_socket(srv);
  21186. });
  21187. auto se = detail::scope_exit([&] { server_thread.join(); });
  21188. auto port = port_future.get();
  21189. ASSERT_GT(port, 0);
  21190. SSLClient cli("127.0.0.1", port);
  21191. cli.enable_server_certificate_verification(false);
  21192. fn(cli);
  21193. }
  21194. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21195. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21196. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21197. "Connection: close\r\n"
  21198. "\r\n"
  21199. "hello";
  21200. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21201. auto res = cli.Get("/");
  21202. ASSERT_TRUE(res) << to_string(res.error());
  21203. EXPECT_EQ("hello", res->body);
  21204. });
  21205. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21206. auto res = cli.Get("/");
  21207. ASSERT_FALSE(res);
  21208. EXPECT_EQ(Error::Read, res.error());
  21209. });
  21210. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21211. auto handle = cli.open_stream("GET", "/");
  21212. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21213. read_all(handle);
  21214. EXPECT_TRUE(handle.has_read_error());
  21215. });
  21216. // A framed body ends where its framing says, with or without the alert
  21217. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21218. "Content-Length: 5\r\n"
  21219. "Connection: close\r\n"
  21220. "\r\n"
  21221. "hello";
  21222. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21223. auto res = cli.Get("/");
  21224. ASSERT_TRUE(res) << to_string(res.error());
  21225. EXPECT_EQ("hello", res->body);
  21226. });
  21227. }
  21228. #endif
  21229. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21230. const char *responses[] = {
  21231. "HTTP/1.1 103 Early Hints\r\n"
  21232. "Link: </style.css>; rel=preload\r\n"
  21233. "\r\n"
  21234. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21235. "HTTP/1.1 100 Continue\r\n"
  21236. "X-Note: interim\r\n"
  21237. "\r\n"
  21238. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21239. };
  21240. for (auto response : responses) {
  21241. with_single_response(response, [](Client &cli) {
  21242. auto res = cli.Get("/");
  21243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21244. EXPECT_EQ(StatusCode::OK_200, res->status);
  21245. EXPECT_EQ("ok", res->body);
  21246. });
  21247. }
  21248. }
  21249. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21250. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21251. const std::string final_response =
  21252. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21253. std::string interims;
  21254. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21255. interims += interim;
  21256. }
  21257. with_single_response(interims + final_response, [](Client &cli) {
  21258. auto res = cli.Get("/");
  21259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21260. EXPECT_EQ("ok", res->body);
  21261. });
  21262. with_single_response(interims + interim + final_response, [](Client &cli) {
  21263. auto res = cli.Get("/");
  21264. ASSERT_FALSE(res);
  21265. EXPECT_EQ(Error::Read, res.error());
  21266. });
  21267. }
  21268. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21269. #ifndef _WIN32
  21270. signal(SIGPIPE, SIG_IGN);
  21271. #endif
  21272. // The server answers the head without asking for the body. Bytes it then
  21273. // reads on the connection would be taken for the body the request declared.
  21274. auto closed_by_client = false;
  21275. std::promise<int> port_promise;
  21276. auto server_thread = serve_single_response(
  21277. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21278. [&](socket_t sock) {
  21279. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21280. char buf[256];
  21281. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21282. });
  21283. Client cli("127.0.0.1", port_promise.get_future().get());
  21284. cli.set_keep_alive(true);
  21285. cli.set_read_timeout(1, 0);
  21286. // Long enough for the client to send Expect: 100-continue.
  21287. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21289. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21290. cli.Get("/second");
  21291. server_thread.join();
  21292. EXPECT_TRUE(closed_by_client);
  21293. }
  21294. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21295. // Long enough for the client to send Expect: 100-continue
  21296. with_single_response(
  21297. "HTTP/1.1 103 Early Hints\r\n"
  21298. "Link: </style.css>; rel=preload\r\n"
  21299. "\r\n"
  21300. "HTTP/1.1 401 Unauthorized\r\n"
  21301. "Content-Length: 0\r\n\r\n",
  21302. [](Client &cli) {
  21303. cli.set_read_timeout(2, 0);
  21304. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21306. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21307. });
  21308. }
  21309. #ifdef CPPHTTPLIB_SSL_ENABLED
  21310. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21311. #ifndef _WIN32
  21312. signal(SIGPIPE, SIG_IGN);
  21313. #endif
  21314. auto reused = false;
  21315. std::promise<int> port_promise;
  21316. auto server_thread = serve_single_response(
  21317. port_promise,
  21318. "HTTP/1.1 401 Unauthorized\r\n"
  21319. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21320. "Content-Length: 0\r\n\r\n",
  21321. [&](socket_t sock) {
  21322. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21323. char buf[256];
  21324. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21325. });
  21326. Client cli("127.0.0.1", port_promise.get_future().get());
  21327. cli.set_keep_alive(true);
  21328. cli.set_digest_auth("user", "pass");
  21329. cli.set_read_timeout(1, 0);
  21330. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21331. server_thread.join();
  21332. EXPECT_FALSE(reused);
  21333. }
  21334. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21335. // Any other answer to CONNECT would read as the origin's response.
  21336. struct {
  21337. const char *response;
  21338. bool passed_on;
  21339. } cases[] = {
  21340. {"HTTP/1.1 201 Created\r\n"
  21341. "Set-Cookie: session=from-proxy\r\n"
  21342. "Content-Length: 0\r\n\r\n",
  21343. false},
  21344. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21345. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21346. "Content-Length: 0\r\n\r\n",
  21347. true},
  21348. };
  21349. for (const auto &c : cases) {
  21350. std::promise<int> port_promise;
  21351. auto server_thread = serve_single_response(port_promise, c.response);
  21352. SSLClient cli("example.com", 443);
  21353. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21354. auto res = cli.Get("/");
  21355. server_thread.join();
  21356. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21357. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21358. if (res) {
  21359. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21360. }
  21361. }
  21362. }
  21363. #endif
  21364. // Records the client's error logger calls as "error METHOD path", or
  21365. // "error null" for a call without a request
  21366. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21367. return [&log](const Error &err, const Request *req) {
  21368. log.push_back(to_string(err) + " " +
  21369. (req ? req->method + " " + req->path : "null"));
  21370. };
  21371. }
  21372. // A failed request is reported once, with the request the caller made
  21373. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21374. Server svr;
  21375. svr.Get("/big", [](const Request &, Response &res) {
  21376. res.set_content(std::string(100000, 'b'), "text/plain");
  21377. });
  21378. auto port = svr.bind_to_any_port(HOST);
  21379. std::thread t([&]() { svr.listen_after_bind(); });
  21380. auto se = detail::scope_exit([&] {
  21381. svr.stop();
  21382. t.join();
  21383. });
  21384. svr.wait_until_ready();
  21385. Client cli(HOST, port);
  21386. std::vector<std::string> log;
  21387. cli.set_error_logger(record_errors(log));
  21388. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21389. cli.Get("/big", [](const char *, size_t) { return false; });
  21390. EXPECT_EQ(expected, log);
  21391. log.clear();
  21392. cli.Get("/big", [](size_t, size_t) { return false; });
  21393. EXPECT_EQ(expected, log);
  21394. }
  21395. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21396. // Fails while the body is read
  21397. auto broken = [](const Request &, Response &res) {
  21398. res.set_content_provider(10, "text/plain",
  21399. [](size_t, size_t, DataSink &) { return false; });
  21400. };
  21401. Server other;
  21402. other.Get("/broken", broken);
  21403. auto other_port = other.bind_to_any_port(HOST);
  21404. std::thread other_t([&]() { other.listen_after_bind(); });
  21405. auto other_se = detail::scope_exit([&] {
  21406. other.stop();
  21407. other_t.join();
  21408. });
  21409. other.wait_until_ready();
  21410. Server svr;
  21411. svr.Get("/broken", broken);
  21412. svr.Get("/same-origin",
  21413. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21414. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21415. res.set_redirect("http://" + std::string(HOST) + ":" +
  21416. std::to_string(other_port) + "/broken");
  21417. });
  21418. auto port = svr.bind_to_any_port(HOST);
  21419. std::thread t([&]() { svr.listen_after_bind(); });
  21420. auto se = detail::scope_exit([&] {
  21421. svr.stop();
  21422. t.join();
  21423. });
  21424. svr.wait_until_ready();
  21425. Client cli(HOST, port);
  21426. cli.set_follow_location(true);
  21427. std::vector<std::string> log;
  21428. cli.set_error_logger(record_errors(log));
  21429. for (auto path : {"/same-origin", "/cross-origin"}) {
  21430. log.clear();
  21431. auto res = cli.Get(path);
  21432. ASSERT_FALSE(res);
  21433. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21434. log);
  21435. }
  21436. }
  21437. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21438. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21439. std::vector<std::string> log;
  21440. cli.set_error_logger(record_errors(log));
  21441. auto handle = cli.open_stream("GET", "/x");
  21442. EXPECT_FALSE(handle.is_valid());
  21443. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21444. log);
  21445. });
  21446. }
  21447. #ifdef CPPHTTPLIB_SSL_ENABLED
  21448. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21449. // Not a TLS server, so the handshake fails. It waits for a request line in
  21450. // the handshake bytes, so a short read timeout lets it close quickly.
  21451. Server svr;
  21452. svr.set_read_timeout(0, 100000);
  21453. svr.Get("/x", [](const Request &, Response &res) {
  21454. res.set_content("x", "text/plain");
  21455. });
  21456. auto port = svr.bind_to_any_port(HOST);
  21457. std::thread t([&]() { svr.listen_after_bind(); });
  21458. auto se = detail::scope_exit([&] {
  21459. svr.stop();
  21460. t.join();
  21461. });
  21462. svr.wait_until_ready();
  21463. std::vector<std::string> log;
  21464. SSLClient cli(HOST, port);
  21465. cli.enable_server_certificate_verification(false);
  21466. cli.set_error_logger(record_errors(log));
  21467. auto res = cli.Get("/x");
  21468. ASSERT_FALSE(res);
  21469. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21470. log.clear();
  21471. auto handle = cli.open_stream("GET", "/x");
  21472. EXPECT_FALSE(handle.is_valid());
  21473. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21474. log.clear();
  21475. SSLClient no_ca(HOST, port);
  21476. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21477. no_ca.set_error_logger(record_errors(log));
  21478. res = no_ca.Get("/x");
  21479. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21480. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21481. }
  21482. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21483. #ifndef _WIN32
  21484. signal(SIGPIPE, SIG_IGN);
  21485. #endif
  21486. // Refused, answered with a challenge, or closed without an answer
  21487. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21488. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21489. "Content-Length: 0\r\n\r\n",
  21490. ""}) {
  21491. std::promise<int> port_promise;
  21492. auto server_thread = serve_single_response(port_promise, response);
  21493. SSLClient cli("example.com", 443);
  21494. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21495. std::vector<std::string> log;
  21496. cli.set_error_logger(record_errors(log));
  21497. auto res = cli.Get("/");
  21498. server_thread.join();
  21499. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21500. << response;
  21501. }
  21502. }
  21503. #endif
  21504. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21505. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21506. // the chunked coding and drop Content-Length, so a front-end that trusts
  21507. // Content-Length would disagree about where the body ends (response
  21508. // smuggling). The client must reject such a response.
  21509. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21510. for (const char *te : {"chunked", "gzip, chunked"}) {
  21511. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21512. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21513. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21514. "5\r\nhello\r\n0\r\n\r\n";
  21515. with_single_response(response, [&](Client &cli) {
  21516. auto res = cli.Get("/");
  21517. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21518. EXPECT_EQ(Error::Read, res.error()) << te;
  21519. });
  21520. with_single_response(response, [&](Client &cli) {
  21521. auto handle = cli.open_stream("GET", "/");
  21522. EXPECT_FALSE(handle.is_valid()) << te;
  21523. EXPECT_EQ(Error::Read, handle.error) << te;
  21524. });
  21525. }
  21526. }
  21527. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21528. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21529. // closing the connection (unlike a request, which must be rejected).
  21530. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21531. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21532. "Transfer-Encoding: chunked\r\n"
  21533. "Connection: close\r\n"
  21534. "\r\n"
  21535. "5\r\nhello\r\n0\r\n\r\n",
  21536. "HTTP/1.1 200 OK\r\n"
  21537. "Transfer-Encoding: gzip\r\n"
  21538. "Connection: close\r\n"
  21539. "\r\n"
  21540. "hello"}) {
  21541. with_single_response(response, [&](Client &cli) {
  21542. auto res = cli.Get("/");
  21543. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21544. EXPECT_EQ("hello", res->body);
  21545. });
  21546. with_single_response(response, [&](Client &cli) {
  21547. auto handle = cli.open_stream("GET", "/");
  21548. ASSERT_TRUE(handle.is_valid()) << response;
  21549. EXPECT_EQ("hello", read_all(handle));
  21550. });
  21551. }
  21552. }
  21553. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21554. // framing headers describe nothing to read and must not be rejected.
  21555. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21556. const std::string framing = "Content-Length: 5\r\n"
  21557. "Transfer-Encoding: chunked\r\n"
  21558. "Connection: close\r\n"
  21559. "\r\n";
  21560. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21561. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21562. });
  21563. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21564. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21565. });
  21566. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21567. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21568. with_single_response(response, [&](Client &cli) {
  21569. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21570. });
  21571. with_single_response(response, [&](Client &cli) {
  21572. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21573. });
  21574. }
  21575. }
  21576. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21577. // header section, so a stream opened on one has nothing to read, whatever
  21578. // framing or coding headers it carries.
  21579. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21580. struct Case {
  21581. const char *method;
  21582. const char *status;
  21583. };
  21584. // A reader of the declared body reports an early close when nothing
  21585. // follows, and hands back what does.
  21586. struct Framing {
  21587. const char *headers;
  21588. const char *after;
  21589. };
  21590. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21591. Case{"GET", "304 Not Modified"}}) {
  21592. for (const auto &f :
  21593. {Framing{"Content-Length: 5\r\n", ""},
  21594. Framing{"Content-Length: 5\r\n", "hello"},
  21595. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21596. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21597. // Not decoded, so a build without Brotli opens it too
  21598. Framing{"Content-Encoding: br\r\n", ""}}) {
  21599. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21600. "Connection: close\r\n"
  21601. "\r\n" +
  21602. f.after;
  21603. with_single_response(response, [&](Client &cli) {
  21604. auto handle = cli.open_stream(c.method, "/");
  21605. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21606. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21607. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21608. });
  21609. }
  21610. }
  21611. }
  21612. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21613. // response, is faulty framing, so the connection is not reused after it.
  21614. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21615. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21616. "Content-Length: 0\r\n"
  21617. "Transfer-Encoding: chunked\r\n"
  21618. "\r\n"
  21619. "5\r\nhello\r\n0\r\n\r\n",
  21620. "HTTP/1.0 200 Connection established\r\n"
  21621. "Connection: keep-alive\r\n"
  21622. "Transfer-Encoding: chunked\r\n"
  21623. "\r\n"
  21624. "5\r\nhello\r\n0\r\n\r\n"}) {
  21625. with_single_response(response, [&](Client &cli) {
  21626. cli.set_keep_alive(true);
  21627. auto res = cli.Get("/");
  21628. ASSERT_TRUE(res) << response;
  21629. EXPECT_EQ("hello", res->body);
  21630. EXPECT_FALSE(cli.is_socket_open()) << response;
  21631. });
  21632. }
  21633. }
  21634. // A payload max length of 0 means no limit, however the body is framed.
  21635. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21636. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21637. "Transfer-Encoding: chunked\r\n"
  21638. "\r\n"
  21639. "5\r\nhello\r\n0\r\n\r\n",
  21640. "HTTP/1.1 200 OK\r\n"
  21641. "Connection: close\r\n"
  21642. "\r\n"
  21643. "hello"}) {
  21644. with_single_response(response, [&](Client &cli) {
  21645. cli.set_payload_max_length(0);
  21646. auto res = cli.Get("/");
  21647. ASSERT_TRUE(res) << response;
  21648. EXPECT_EQ("hello", res->body) << response;
  21649. });
  21650. }
  21651. }
  21652. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21653. Server svr;
  21654. svr.set_payload_max_length(0);
  21655. svr.Post("/echo", [](const Request &req, Response &res) {
  21656. res.set_content(req.body, "text/plain");
  21657. });
  21658. auto port = svr.bind_to_any_port(HOST);
  21659. thread t = thread([&] { svr.listen_after_bind(); });
  21660. auto se = detail::scope_exit([&] {
  21661. svr.stop();
  21662. t.join();
  21663. ASSERT_FALSE(svr.is_running());
  21664. });
  21665. svr.wait_until_ready();
  21666. Client cli(HOST, port);
  21667. auto res = cli.Post(
  21668. "/echo",
  21669. [](size_t /*offset*/, DataSink &sink) {
  21670. sink.write("hello", 5);
  21671. sink.done();
  21672. return true;
  21673. },
  21674. "text/plain");
  21675. ASSERT_TRUE(res);
  21676. EXPECT_EQ(StatusCode::OK_200, res->status);
  21677. EXPECT_EQ("hello", res->body);
  21678. }
  21679. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21680. TEST_F(OpenStreamTest, Gzip) {
  21681. Client cli("127.0.0.1", port_);
  21682. auto handle = cli.open_stream("GET", "/compressible", {},
  21683. {{"Accept-Encoding", "gzip"}});
  21684. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21685. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21686. }
  21687. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21688. Client cli("127.0.0.1", port_);
  21689. auto handle =
  21690. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21691. {{"Accept-Encoding", "gzip"}});
  21692. ASSERT_TRUE(handle.is_valid());
  21693. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21694. EXPECT_EQ("123456789", read_all(handle));
  21695. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21696. }
  21697. #endif
  21698. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21699. TEST_F(OpenStreamTest, Brotli) {
  21700. Client cli("127.0.0.1", port_);
  21701. auto handle =
  21702. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21703. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21704. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21705. }
  21706. #endif
  21707. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21708. TEST_F(OpenStreamTest, Zstd) {
  21709. Client cli("127.0.0.1", port_);
  21710. auto handle = cli.open_stream("GET", "/compressible", {},
  21711. {{"Accept-Encoding", "zstd"}});
  21712. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21713. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21714. }
  21715. #endif
  21716. #ifdef CPPHTTPLIB_SSL_ENABLED
  21717. class SSLOpenStreamTest : public ::testing::Test {
  21718. protected:
  21719. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21720. void SetUp() override {
  21721. svr_.Get("/hello", [](const Request &, Response &res) {
  21722. res.set_content("Hello SSL World!", "text/plain");
  21723. });
  21724. svr_.Get("/chunked", [](const Request &, Response &res) {
  21725. res.set_chunked_content_provider("text/plain",
  21726. [](size_t offset, DataSink &sink) {
  21727. if (offset < 15) {
  21728. sink.write("chunk", 5);
  21729. return true;
  21730. }
  21731. sink.done();
  21732. return true;
  21733. });
  21734. });
  21735. svr_.Post("/echo", [](const Request &req, Response &res) {
  21736. res.set_content(req.body, req.get_header_value("Content-Type"));
  21737. });
  21738. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21739. std::string body = req.body;
  21740. res.set_chunked_content_provider(
  21741. "text/plain", [body](size_t offset, DataSink &sink) {
  21742. if (offset < body.size()) {
  21743. sink.write(body.data() + offset, body.size() - offset);
  21744. }
  21745. sink.done();
  21746. return true;
  21747. });
  21748. });
  21749. port_ = svr_.bind_to_any_port("127.0.0.1");
  21750. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21751. svr_.wait_until_ready();
  21752. }
  21753. void TearDown() override {
  21754. svr_.stop();
  21755. if (thread_.joinable()) thread_.join();
  21756. }
  21757. SSLServer svr_;
  21758. std::thread thread_;
  21759. int port_ = 0;
  21760. };
  21761. TEST_F(SSLOpenStreamTest, Basic) {
  21762. SSLClient cli("127.0.0.1", port_);
  21763. cli.enable_server_certificate_verification(false);
  21764. auto handle = cli.open_stream("GET", "/hello");
  21765. ASSERT_TRUE(handle.is_valid());
  21766. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21767. }
  21768. TEST_F(SSLOpenStreamTest, Chunked) {
  21769. SSLClient cli("127.0.0.1", port_);
  21770. cli.enable_server_certificate_verification(false);
  21771. auto handle = cli.open_stream("GET", "/chunked");
  21772. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21773. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21774. "Transfer-Encoding") == "chunked");
  21775. auto body = read_all(handle);
  21776. EXPECT_EQ("chunkchunkchunk", body);
  21777. }
  21778. TEST_F(SSLOpenStreamTest, Post) {
  21779. SSLClient cli("127.0.0.1", port_);
  21780. cli.enable_server_certificate_verification(false);
  21781. auto handle =
  21782. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21783. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21784. EXPECT_EQ(200, handle.response->status);
  21785. auto body = read_all(handle);
  21786. EXPECT_EQ("Hello SSL POST", body);
  21787. }
  21788. TEST_F(SSLOpenStreamTest, PostChunked) {
  21789. SSLClient cli("127.0.0.1", port_);
  21790. cli.enable_server_certificate_verification(false);
  21791. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21792. "Chunked SSL Data", "text/plain");
  21793. ASSERT_TRUE(handle.is_valid());
  21794. EXPECT_EQ(200, handle.response->status);
  21795. auto body = read_all(handle);
  21796. EXPECT_EQ("Chunked SSL Data", body);
  21797. }
  21798. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21799. // Content-Length is terminated by the server closing the connection. When the
  21800. // SSL peer sends a close_notify after the body, the client must treat it as a
  21801. // clean EOF and return a successful response rather than an error.
  21802. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21804. ASSERT_TRUE(svr.is_valid());
  21805. svr.set_keep_alive_max_count(1);
  21806. const std::string expected_body = "Hello from connection-close response!";
  21807. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21808. res.set_content_provider("text/plain",
  21809. [&](size_t offset, DataSink &sink) -> bool {
  21810. if (offset < expected_body.size()) {
  21811. sink.write(expected_body.data() + offset,
  21812. expected_body.size() - offset);
  21813. }
  21814. sink.done();
  21815. return true;
  21816. });
  21817. });
  21818. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21819. auto se = detail::scope_exit([&] {
  21820. svr.stop();
  21821. listen_thread.join();
  21822. ASSERT_FALSE(svr.is_running());
  21823. });
  21824. svr.wait_until_ready();
  21825. SSLClient cli(HOST, PORT);
  21826. cli.enable_server_certificate_verification(false);
  21827. auto res = cli.Get("/no-content-length");
  21828. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21829. EXPECT_EQ(StatusCode::OK_200, res->status);
  21830. EXPECT_EQ(expected_body, res->body);
  21831. }
  21832. // Without Content-Length, the full buffer size reaches tls::read().
  21833. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21834. if (sizeof(size_t) <= sizeof(int)) {
  21835. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21836. }
  21837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21838. ASSERT_TRUE(svr.is_valid());
  21839. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21840. res.set_content_provider("text/plain",
  21841. [&](size_t offset, DataSink &sink) -> bool {
  21842. if (offset == 0) { sink.write("Hello", 5); }
  21843. sink.done();
  21844. return true;
  21845. });
  21846. });
  21847. auto port = svr.bind_to_any_port(HOST);
  21848. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21849. auto se = detail::scope_exit([&] {
  21850. svr.stop();
  21851. listen_thread.join();
  21852. });
  21853. svr.wait_until_ready();
  21854. SSLClient cli(HOST, port);
  21855. cli.enable_server_certificate_verification(false);
  21856. auto handle = cli.open_stream("GET", "/no-content-length");
  21857. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21858. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21859. std::unique_ptr<char[]> buf(new char[len]);
  21860. std::string body;
  21861. ssize_t n;
  21862. while ((n = handle.read(buf.get(), len)) > 0) {
  21863. body.append(buf.get(), static_cast<size_t>(n));
  21864. }
  21865. EXPECT_EQ(0, n);
  21866. EXPECT_EQ("Hello", body);
  21867. }
  21868. #endif // CPPHTTPLIB_SSL_ENABLED
  21869. //==============================================================================
  21870. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21871. // results for various scenarios.
  21872. //==============================================================================
  21873. TEST(ParityTest, GetVsOpenStream) {
  21874. Server svr;
  21875. const std::string path = "/parity";
  21876. const std::string content = "Parity test content: hello world";
  21877. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21878. res.set_content(content, "text/plain");
  21879. });
  21880. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21881. auto se = detail::scope_exit([&] {
  21882. svr.stop();
  21883. t.join();
  21884. ASSERT_FALSE(svr.is_running());
  21885. });
  21886. svr.wait_until_ready();
  21887. Client cli(HOST, PORT);
  21888. // Non-stream path
  21889. auto r1 = cli.Get(path);
  21890. ASSERT_TRUE(r1);
  21891. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21892. // Stream path
  21893. auto h = cli.open_stream("GET", path);
  21894. ASSERT_TRUE(h.is_valid());
  21895. EXPECT_EQ(r1->body, read_all(h));
  21896. }
  21897. // Helper to compress data with provided compressor type T
  21898. template <typename Compressor>
  21899. static std::string compress_payload_for_parity(const std::string &in) {
  21900. std::string out;
  21901. Compressor compressor;
  21902. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21903. [&](const char *data, size_t n) {
  21904. out.append(data, n);
  21905. return true;
  21906. });
  21907. EXPECT_TRUE(ok);
  21908. return out;
  21909. }
  21910. // Helper function for compression parity tests
  21911. template <typename Compressor>
  21912. static void test_compression_parity(const std::string &original,
  21913. const std::string &path,
  21914. const std::string &encoding) {
  21915. const std::string compressed =
  21916. compress_payload_for_parity<Compressor>(original);
  21917. Server svr;
  21918. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21919. res.set_content(compressed, "application/octet-stream");
  21920. res.set_header("Content-Encoding", encoding);
  21921. });
  21922. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21923. auto se = detail::scope_exit([&] {
  21924. svr.stop();
  21925. t.join();
  21926. ASSERT_FALSE(svr.is_running());
  21927. });
  21928. svr.wait_until_ready();
  21929. Client cli(HOST, PORT);
  21930. // Non-streaming
  21931. {
  21932. auto res = cli.Get(path);
  21933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21934. EXPECT_EQ(StatusCode::OK_200, res->status);
  21935. EXPECT_EQ(original, res->body);
  21936. }
  21937. // Streaming
  21938. {
  21939. auto h = cli.open_stream("GET", path);
  21940. ASSERT_TRUE(h.is_valid());
  21941. EXPECT_EQ(original, read_all(h));
  21942. }
  21943. }
  21944. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21945. TEST(ParityTest, Gzip) {
  21946. test_compression_parity<detail::gzip_compressor>(
  21947. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21948. }
  21949. #endif
  21950. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21951. TEST(ParityTest, Brotli) {
  21952. test_compression_parity<detail::brotli_compressor>(
  21953. "Hello, brotli parity test payload", "/parity-br", "br");
  21954. }
  21955. #endif
  21956. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21957. TEST(ParityTest, Zstd) {
  21958. test_compression_parity<detail::zstd_compressor>(
  21959. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21960. }
  21961. #endif
  21962. //==============================================================================
  21963. // New Stream API Tests
  21964. //==============================================================================
  21965. inline std::string read_body(httplib::stream::Result &result) {
  21966. std::string body;
  21967. while (result.next()) {
  21968. body.append(result.data(), result.size());
  21969. }
  21970. return body;
  21971. }
  21972. TEST(ClientConnectionTest, Basic) {
  21973. httplib::ClientConnection conn;
  21974. EXPECT_FALSE(conn.is_open());
  21975. conn.sock = 1;
  21976. EXPECT_TRUE(conn.is_open());
  21977. httplib::ClientConnection conn2(std::move(conn));
  21978. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21979. conn2.sock = INVALID_SOCKET;
  21980. }
  21981. // Unified test server for all stream::* tests
  21982. class StreamApiTest : public ::testing::Test {
  21983. protected:
  21984. void SetUp() override {
  21985. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21986. res.set_content("Hello World!", "text/plain");
  21987. });
  21988. svr_.Get("/echo-params",
  21989. [](const httplib::Request &req, httplib::Response &res) {
  21990. std::string r;
  21991. for (const auto &p : req.params) {
  21992. if (!r.empty()) r += "&";
  21993. r += p.first + "=" + p.second;
  21994. }
  21995. res.set_content(r, "text/plain");
  21996. });
  21997. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21998. res.set_content(req.body, req.get_header_value("Content-Type"));
  21999. });
  22000. svr_.Post("/echo-headers",
  22001. [](const httplib::Request &req, httplib::Response &res) {
  22002. std::string r;
  22003. for (const auto &h : req.headers)
  22004. r += h.first + ": " + h.second + "\n";
  22005. res.set_content(r, "text/plain");
  22006. });
  22007. svr_.Post("/echo-params",
  22008. [](const httplib::Request &req, httplib::Response &res) {
  22009. std::string r = "params:";
  22010. for (const auto &p : req.params)
  22011. r += p.first + "=" + p.second + ";";
  22012. res.set_content(r + " body:" + req.body, "text/plain");
  22013. });
  22014. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22015. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22016. });
  22017. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22018. res.set_content("PUT:" + req.body, "text/plain");
  22019. });
  22020. svr_.Patch("/echo",
  22021. [](const httplib::Request &req, httplib::Response &res) {
  22022. res.set_content("PATCH:" + req.body, "text/plain");
  22023. });
  22024. svr_.Delete(
  22025. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22026. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22027. "text/plain");
  22028. });
  22029. svr_.Get("/head-test",
  22030. [](const httplib::Request &, httplib::Response &res) {
  22031. res.set_content("body for HEAD", "text/plain");
  22032. });
  22033. svr_.Options("/options",
  22034. [](const httplib::Request &, httplib::Response &res) {
  22035. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22036. });
  22037. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22038. svr_.wait_until_ready();
  22039. }
  22040. void TearDown() override {
  22041. svr_.stop();
  22042. if (thread_.joinable()) thread_.join();
  22043. }
  22044. httplib::Server svr_;
  22045. std::thread thread_;
  22046. };
  22047. // stream::Get tests
  22048. TEST_F(StreamApiTest, GetBasic) {
  22049. httplib::Client cli(HOST, PORT);
  22050. auto result = httplib::stream::Get(cli, "/hello");
  22051. ASSERT_TRUE(result.is_valid());
  22052. EXPECT_EQ(200, result.status());
  22053. EXPECT_EQ("Hello World!", read_body(result));
  22054. }
  22055. TEST_F(StreamApiTest, GetWithParams) {
  22056. httplib::Client cli(HOST, PORT);
  22057. httplib::Params params{{"foo", "bar"}};
  22058. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22059. ASSERT_TRUE(result.is_valid());
  22060. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22061. }
  22062. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22063. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22064. httplib::Client cli(HOST, PORT);
  22065. cli.set_payload_max_length(0);
  22066. auto result = httplib::stream::Get(cli, "/hello");
  22067. ASSERT_TRUE(result.is_valid());
  22068. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22069. EXPECT_EQ("Hello World!", read_body(result));
  22070. }
  22071. #endif
  22072. TEST_F(StreamApiTest, GetConnectionError) {
  22073. httplib::Client cli(HOST, 9999);
  22074. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22075. }
  22076. TEST_F(StreamApiTest, Get404) {
  22077. httplib::Client cli(HOST, PORT);
  22078. auto result = httplib::stream::Get(cli, "/nonexistent");
  22079. EXPECT_TRUE(result.is_valid());
  22080. EXPECT_EQ(404, result.status());
  22081. }
  22082. // stream::Post tests
  22083. TEST_F(StreamApiTest, PostBasic) {
  22084. httplib::Client cli(HOST, PORT);
  22085. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22086. "application/json");
  22087. ASSERT_TRUE(result.is_valid());
  22088. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22089. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22090. }
  22091. TEST_F(StreamApiTest, PostWithHeaders) {
  22092. httplib::Client cli(HOST, PORT);
  22093. httplib::Headers headers{{"X-Custom", "value"}};
  22094. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22095. "text/plain");
  22096. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22097. }
  22098. TEST_F(StreamApiTest, PostWithParams) {
  22099. httplib::Client cli(HOST, PORT);
  22100. httplib::Params params{{"k", "v"}};
  22101. auto result =
  22102. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22103. auto body = read_body(result);
  22104. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22105. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22106. }
  22107. TEST_F(StreamApiTest, PostLarge) {
  22108. httplib::Client cli(HOST, PORT);
  22109. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22110. size_t total = 0;
  22111. while (result.next()) {
  22112. total += result.size();
  22113. }
  22114. EXPECT_EQ(100u * 1024u, total);
  22115. }
  22116. // stream::Put/Patch tests
  22117. TEST_F(StreamApiTest, PutAndPatch) {
  22118. httplib::Client cli(HOST, PORT);
  22119. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22120. EXPECT_EQ("PUT:test", read_body(put));
  22121. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22122. EXPECT_EQ("PATCH:test", read_body(patch));
  22123. }
  22124. // stream::Delete tests
  22125. TEST_F(StreamApiTest, Delete) {
  22126. httplib::Client cli(HOST, PORT);
  22127. auto del1 = httplib::stream::Delete(cli, "/resource");
  22128. EXPECT_EQ("Deleted", read_body(del1));
  22129. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22130. EXPECT_EQ("Deleted:data", read_body(del2));
  22131. }
  22132. // stream::Head/Options tests
  22133. TEST_F(StreamApiTest, HeadAndOptions) {
  22134. httplib::Client cli(HOST, PORT);
  22135. auto head = httplib::stream::Head(cli, "/head-test");
  22136. EXPECT_TRUE(head.is_valid());
  22137. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22138. auto opts = httplib::stream::Options(cli, "/options");
  22139. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22140. }
  22141. // SSL stream::* tests
  22142. #ifdef CPPHTTPLIB_SSL_ENABLED
  22143. class SSLStreamApiTest : public ::testing::Test {
  22144. protected:
  22145. void SetUp() override {
  22146. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22147. res.set_content("Hello SSL!", "text/plain");
  22148. });
  22149. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22150. res.set_content(req.body, "text/plain");
  22151. });
  22152. port_ = svr_.bind_to_any_port("127.0.0.1");
  22153. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22154. svr_.wait_until_ready();
  22155. }
  22156. void TearDown() override {
  22157. svr_.stop();
  22158. if (thread_.joinable()) thread_.join();
  22159. }
  22160. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22161. std::thread thread_;
  22162. int port_ = 0;
  22163. };
  22164. TEST_F(SSLStreamApiTest, GetAndPost) {
  22165. httplib::SSLClient cli("127.0.0.1", port_);
  22166. cli.enable_server_certificate_verification(false);
  22167. auto get = httplib::stream::Get(cli, "/hello");
  22168. EXPECT_EQ("Hello SSL!", read_body(get));
  22169. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22170. EXPECT_EQ("test", read_body(post));
  22171. }
  22172. #endif
  22173. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22174. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22175. // BodyReader
  22176. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22177. // Test that read timeout during streaming is detected
  22178. // Use a large content-length response where server delays mid-stream
  22179. Server svr;
  22180. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22181. // Send a large response with delay in the middle
  22182. res.set_content_provider(
  22183. 1000, // content_length
  22184. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22185. if (offset < 100) {
  22186. // Send first 100 bytes immediately
  22187. std::string data(100, 'A');
  22188. sink.write(data.c_str(), data.size());
  22189. return true;
  22190. }
  22191. // Then delay longer than client timeout
  22192. std::this_thread::sleep_for(std::chrono::seconds(3));
  22193. std::string data(900, 'B');
  22194. sink.write(data.c_str(), data.size());
  22195. return true;
  22196. });
  22197. });
  22198. auto port = 8091;
  22199. std::thread t([&]() { svr.listen("localhost", port); });
  22200. svr.wait_until_ready();
  22201. Client cli("localhost", port);
  22202. cli.set_read_timeout(1, 0); // 1 second timeout
  22203. auto handle = cli.open_stream("GET", "/slow-stream");
  22204. ASSERT_TRUE(handle.is_valid());
  22205. char buf[256];
  22206. ssize_t total = 0;
  22207. ssize_t n;
  22208. bool got_error = false;
  22209. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22210. total += n;
  22211. }
  22212. if (n < 0) {
  22213. got_error = true;
  22214. // Should be timeout or read error
  22215. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22216. handle.get_read_error() == Error::Read)
  22217. << "Actual error: " << to_string(handle.get_read_error());
  22218. }
  22219. // Either we got an error, or we got less data than expected
  22220. EXPECT_TRUE(got_error || total < 1000)
  22221. << "Expected timeout but got all " << total << " bytes";
  22222. svr.stop();
  22223. t.join();
  22224. }
  22225. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22226. // Test connection closed detection via BodyReader
  22227. Server svr;
  22228. std::atomic<bool> close_now{false};
  22229. svr.Get("/will-close", [&](const Request &, Response &res) {
  22230. res.set_content_provider(
  22231. 10000, // Large content_length that we won't fully send
  22232. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22233. if (offset < 100) {
  22234. std::string data(100, 'X');
  22235. sink.write(data.c_str(), data.size());
  22236. return true;
  22237. }
  22238. // Wait for signal then abort
  22239. while (!close_now) {
  22240. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22241. }
  22242. return false; // Abort - server will close connection
  22243. });
  22244. });
  22245. auto port = 8092;
  22246. std::thread t([&]() { svr.listen("localhost", port); });
  22247. svr.wait_until_ready();
  22248. Client cli("localhost", port);
  22249. auto handle = cli.open_stream("GET", "/will-close");
  22250. ASSERT_TRUE(handle.is_valid());
  22251. char buf[256];
  22252. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22253. EXPECT_GT(n, 0) << "First read should succeed";
  22254. // Signal server to close
  22255. close_now = true;
  22256. // Keep reading until error or EOF
  22257. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22258. // Keep reading
  22259. }
  22260. // Should get an error since content_length wasn't satisfied
  22261. if (n < 0) {
  22262. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22263. handle.get_read_error() == Error::Read)
  22264. << "Actual error: " << to_string(handle.get_read_error());
  22265. }
  22266. svr.stop();
  22267. t.join();
  22268. }
  22269. #ifdef CPPHTTPLIB_SSL_ENABLED
  22270. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22271. // Test that read timeout during SSL streaming is detected
  22272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22273. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22274. res.set_content_provider(
  22275. 1000, "text/plain",
  22276. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22277. if (offset < 100) {
  22278. std::string data(100, 'A');
  22279. sink.write(data.c_str(), data.size());
  22280. return true;
  22281. }
  22282. std::this_thread::sleep_for(std::chrono::seconds(3));
  22283. std::string data(900, 'B');
  22284. sink.write(data.c_str(), data.size());
  22285. return true;
  22286. });
  22287. });
  22288. auto port = 8093;
  22289. std::thread t([&]() { svr.listen("localhost", port); });
  22290. svr.wait_until_ready();
  22291. SSLClient cli("localhost", port);
  22292. cli.enable_server_certificate_verification(false);
  22293. cli.set_read_timeout(1, 0); // 1 second timeout
  22294. auto handle = cli.open_stream("GET", "/slow-stream");
  22295. ASSERT_TRUE(handle.is_valid());
  22296. char buf[256];
  22297. ssize_t total = 0;
  22298. ssize_t n;
  22299. bool got_error = false;
  22300. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22301. total += n;
  22302. }
  22303. if (n < 0) {
  22304. got_error = true;
  22305. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22306. handle.get_read_error() == Error::Read)
  22307. << "Actual error: " << to_string(handle.get_read_error());
  22308. }
  22309. EXPECT_TRUE(got_error || total < 1000)
  22310. << "Expected timeout but got all " << total << " bytes";
  22311. svr.stop();
  22312. t.join();
  22313. }
  22314. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22315. // Test SSL connection closed detection
  22316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22317. std::atomic<bool> close_now{false};
  22318. svr.Get("/will-close", [&](const Request &, Response &res) {
  22319. res.set_content_provider(
  22320. 10000, "text/plain",
  22321. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22322. if (offset < 100) {
  22323. std::string data(100, 'X');
  22324. sink.write(data.c_str(), data.size());
  22325. return true;
  22326. }
  22327. while (!close_now) {
  22328. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22329. }
  22330. return false;
  22331. });
  22332. });
  22333. auto port = 8094;
  22334. std::thread t([&]() { svr.listen("localhost", port); });
  22335. svr.wait_until_ready();
  22336. SSLClient cli("localhost", port);
  22337. cli.enable_server_certificate_verification(false);
  22338. auto handle = cli.open_stream("GET", "/will-close");
  22339. ASSERT_TRUE(handle.is_valid());
  22340. char buf[256];
  22341. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22342. EXPECT_GT(n, 0);
  22343. // Signal server to close
  22344. close_now = true;
  22345. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22346. // Keep reading
  22347. }
  22348. if (n < 0) {
  22349. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22350. handle.get_read_error() == Error::Read)
  22351. << "Actual error: " << to_string(handle.get_read_error());
  22352. }
  22353. svr.stop();
  22354. t.join();
  22355. }
  22356. #endif
  22357. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22358. using namespace httplib;
  22359. // Create a test file
  22360. const char *fname = "etag_testfile.txt";
  22361. const char *content = "etag-content";
  22362. {
  22363. std::ofstream ofs(fname);
  22364. ofs << content;
  22365. ASSERT_TRUE(ofs.good());
  22366. }
  22367. Server svr;
  22368. svr.set_mount_point("/static", ".");
  22369. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22370. svr.wait_until_ready();
  22371. Client cli(HOST, PORT);
  22372. // First request: should get 200 with ETag header
  22373. auto res1 = cli.Get("/static/etag_testfile.txt");
  22374. ASSERT_TRUE(res1);
  22375. ASSERT_EQ(200, res1->status);
  22376. ASSERT_TRUE(res1->has_header("ETag"));
  22377. std::string etag = res1->get_header_value("ETag");
  22378. EXPECT_FALSE(etag.empty());
  22379. // Verify ETag format: W/"hex-hex"
  22380. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22381. EXPECT_EQ('W', etag[0]);
  22382. EXPECT_EQ('/', etag[1]);
  22383. EXPECT_EQ('"', etag[2]);
  22384. EXPECT_EQ('"', etag.back());
  22385. // Exact match: expect 304 Not Modified
  22386. Headers h2 = {{"If-None-Match", etag}};
  22387. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22388. ASSERT_TRUE(res2);
  22389. EXPECT_EQ(304, res2->status);
  22390. // Wildcard match: expect 304 Not Modified
  22391. Headers h3 = {{"If-None-Match", "*"}};
  22392. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22393. ASSERT_TRUE(res3);
  22394. EXPECT_EQ(304, res3->status);
  22395. // Non-matching ETag: expect 200
  22396. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22397. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22398. ASSERT_TRUE(res4);
  22399. EXPECT_EQ(200, res4->status);
  22400. // Multiple ETags with one matching: expect 304
  22401. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22402. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22403. ASSERT_TRUE(res5);
  22404. EXPECT_EQ(304, res5->status);
  22405. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22406. // that equivalent to the single comma-separated list above, so the match on
  22407. // the second line must still be found.
  22408. Headers h6;
  22409. h6.emplace("If-None-Match", "W/\"other\"");
  22410. h6.emplace("If-None-Match", etag);
  22411. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22412. ASSERT_TRUE(res6);
  22413. EXPECT_EQ(304, res6->status);
  22414. svr.stop();
  22415. t.join();
  22416. std::remove(fname);
  22417. }
  22418. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22419. using namespace httplib;
  22420. Server svr;
  22421. svr.set_mount_point("/static", ".");
  22422. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22423. svr.wait_until_ready();
  22424. Client cli(HOST, PORT);
  22425. // Send If-None-Match: * to a non-existent file
  22426. Headers h = {{"If-None-Match", "*"}};
  22427. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22429. EXPECT_EQ(404, res->status);
  22430. svr.stop();
  22431. t.join();
  22432. }
  22433. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22434. using namespace httplib;
  22435. // Create a test file
  22436. const char *fname = "etag_boundary_testfile.txt";
  22437. const char *content = "boundary-test";
  22438. {
  22439. std::ofstream ofs(fname);
  22440. ofs << content;
  22441. ASSERT_TRUE(ofs.good());
  22442. }
  22443. Server svr;
  22444. svr.set_mount_point("/static", ".");
  22445. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22446. svr.wait_until_ready();
  22447. Client cli(HOST, PORT);
  22448. // Get the actual ETag
  22449. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22450. ASSERT_TRUE(res1);
  22451. ASSERT_EQ(200, res1->status);
  22452. ASSERT_TRUE(res1->has_header("ETag"));
  22453. std::string etag = res1->get_header_value("ETag");
  22454. // Test 1: Very long ETag value (longer than actual ETag)
  22455. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22456. Headers h1 = {{"If-None-Match", "W/"
  22457. "\"very-long-etag-value-that-is-much-longer-"
  22458. "than-the-actual-etag-value\""}};
  22459. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22460. ASSERT_TRUE(res2);
  22461. EXPECT_EQ(200, res2->status); // Should not match
  22462. // Test 2: Long string followed by wildcard
  22463. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22464. // string)
  22465. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22466. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22467. ASSERT_TRUE(res3);
  22468. EXPECT_EQ(304, res3->status); // Should match on "*"
  22469. // Test 3: Wildcard followed by long string
  22470. // Should match on "*" immediately and return 304
  22471. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22472. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22473. ASSERT_TRUE(res4);
  22474. EXPECT_EQ(304, res4->status); // Should match on "*"
  22475. // Test 4: Multiple long non-matching values
  22476. // Should NOT match and return 200 (test that all comparisons are safe)
  22477. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22478. "W/\"second-long-non-matching-value\", "
  22479. "W/\"third-long-non-matching-value\""}};
  22480. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22481. ASSERT_TRUE(res5);
  22482. EXPECT_EQ(200, res5->status); // Should not match
  22483. // Test 5: Single character that is not "*" (edge case)
  22484. Headers h5 = {{"If-None-Match", "X"}};
  22485. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22486. ASSERT_TRUE(res6);
  22487. EXPECT_EQ(200, res6->status); // Should not match
  22488. svr.stop();
  22489. t.join();
  22490. std::remove(fname);
  22491. }
  22492. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22493. using namespace httplib;
  22494. // Create a test file
  22495. const char *fname = "ims_testfile.txt";
  22496. const char *content = "if-modified-since-test";
  22497. {
  22498. std::ofstream ofs(fname);
  22499. ofs << content;
  22500. ASSERT_TRUE(ofs.good());
  22501. }
  22502. Server svr;
  22503. svr.set_mount_point("/static", ".");
  22504. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22505. svr.wait_until_ready();
  22506. Client cli(HOST, PORT);
  22507. // First request: should get 200 with Last-Modified header
  22508. auto res1 = cli.Get("/static/ims_testfile.txt");
  22509. ASSERT_TRUE(res1);
  22510. ASSERT_EQ(200, res1->status);
  22511. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22512. std::string last_modified = res1->get_header_value("Last-Modified");
  22513. EXPECT_FALSE(last_modified.empty());
  22514. // If-Modified-Since with same time: expect 304
  22515. Headers h2 = {{"If-Modified-Since", last_modified}};
  22516. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22517. ASSERT_TRUE(res2);
  22518. EXPECT_EQ(304, res2->status);
  22519. // If-Modified-Since with future time: expect 304
  22520. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22521. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22522. ASSERT_TRUE(res3);
  22523. EXPECT_EQ(304, res3->status);
  22524. // If-Modified-Since with past time: expect 200
  22525. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22526. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22527. ASSERT_TRUE(res4);
  22528. EXPECT_EQ(200, res4->status);
  22529. // If-None-Match takes precedence over If-Modified-Since
  22530. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22531. ASSERT_TRUE(res1->has_header("ETag"));
  22532. std::string etag = res1->get_header_value("ETag");
  22533. Headers h5 = {{"If-None-Match", etag},
  22534. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22535. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22536. ASSERT_TRUE(res5);
  22537. EXPECT_EQ(304, res5->status);
  22538. svr.stop();
  22539. t.join();
  22540. std::remove(fname);
  22541. }
  22542. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22543. using namespace httplib;
  22544. Server svr;
  22545. // Endpoint that returns compressible content
  22546. svr.Get("/compressible", [](const Request &, Response &res) {
  22547. // Return a large enough body to trigger compression
  22548. std::string body(1000, 'a');
  22549. res.set_content(body, "text/plain");
  22550. });
  22551. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22552. svr.wait_until_ready();
  22553. Client cli(HOST, PORT);
  22554. // Request with gzip support: should get Vary header when compressed
  22555. cli.set_compress(true);
  22556. auto res1 = cli.Get("/compressible");
  22557. ASSERT_TRUE(res1);
  22558. EXPECT_EQ(200, res1->status);
  22559. // If Content-Encoding is set, Vary should also be set
  22560. if (res1->has_header("Content-Encoding")) {
  22561. EXPECT_TRUE(res1->has_header("Vary"));
  22562. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22563. }
  22564. // Request without Accept-Encoding header: should not have compression
  22565. Headers h_no_compress;
  22566. auto res2 = cli.Get("/compressible", h_no_compress);
  22567. ASSERT_TRUE(res2);
  22568. EXPECT_EQ(200, res2->status);
  22569. // Verify Vary header is present when compression is applied
  22570. // (the exact behavior depends on server configuration)
  22571. svr.stop();
  22572. t.join();
  22573. }
  22574. TEST(ETagTest, IfRangeWithETag) {
  22575. using namespace httplib;
  22576. // Create a test file with known content
  22577. const char *fname = "if_range_testfile.txt";
  22578. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22579. {
  22580. std::ofstream ofs(fname);
  22581. ofs << content;
  22582. ASSERT_TRUE(ofs.good());
  22583. }
  22584. Server svr;
  22585. svr.set_mount_point("/static", ".");
  22586. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22587. svr.wait_until_ready();
  22588. Client cli(HOST, PORT);
  22589. // First request: get ETag
  22590. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22591. ASSERT_TRUE(res1);
  22592. ASSERT_EQ(200, res1->status);
  22593. ASSERT_TRUE(res1->has_header("ETag"));
  22594. std::string etag = res1->get_header_value("ETag");
  22595. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22596. // Since our server generates weak ETags (W/"..."), If-Range with our
  22597. // ETag should NOT result in partial content - it should return full content.
  22598. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22599. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22600. ASSERT_TRUE(res2);
  22601. // Weak ETag in If-Range -> full content (200), not partial (206)
  22602. EXPECT_EQ(200, res2->status);
  22603. EXPECT_EQ(content, res2->body);
  22604. EXPECT_FALSE(res2->has_header("Content-Range"));
  22605. // Range request with non-matching If-Range (ETag): should get 200 (full
  22606. // content)
  22607. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22608. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22609. ASSERT_TRUE(res3);
  22610. EXPECT_EQ(200, res3->status);
  22611. EXPECT_EQ(content, res3->body);
  22612. EXPECT_FALSE(res3->has_header("Content-Range"));
  22613. // Range request with strong ETag (hypothetical - our server doesn't generate
  22614. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22615. // should return full content)
  22616. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22617. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22618. ASSERT_TRUE(res4);
  22619. EXPECT_EQ(200, res4->status);
  22620. EXPECT_EQ(content, res4->body);
  22621. EXPECT_FALSE(res4->has_header("Content-Range"));
  22622. svr.stop();
  22623. t.join();
  22624. std::remove(fname);
  22625. }
  22626. TEST(ETagTest, IfRangeWithDate) {
  22627. using namespace httplib;
  22628. // Create a test file
  22629. const char *fname = "if_range_date_testfile.txt";
  22630. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22631. {
  22632. std::ofstream ofs(fname);
  22633. ofs << content;
  22634. ASSERT_TRUE(ofs.good());
  22635. }
  22636. Server svr;
  22637. svr.set_mount_point("/static", ".");
  22638. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22639. svr.wait_until_ready();
  22640. Client cli(HOST, PORT);
  22641. // First request: get Last-Modified
  22642. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22643. ASSERT_TRUE(res1);
  22644. ASSERT_EQ(200, res1->status);
  22645. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22646. std::string last_modified = res1->get_header_value("Last-Modified");
  22647. // Range request with matching If-Range (date): should get 206
  22648. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22649. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22650. ASSERT_TRUE(res2);
  22651. EXPECT_EQ(206, res2->status);
  22652. EXPECT_EQ("FGHIJ", res2->body);
  22653. // Range request with old If-Range date: should get 200 (full content)
  22654. Headers h3 = {{"Range", "bytes=5-9"},
  22655. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22656. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22657. ASSERT_TRUE(res3);
  22658. EXPECT_EQ(200, res3->status);
  22659. EXPECT_EQ(content, res3->body);
  22660. // Range request with future If-Range date: should get 206
  22661. Headers h4 = {{"Range", "bytes=0-4"},
  22662. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22663. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22664. ASSERT_TRUE(res4);
  22665. EXPECT_EQ(206, res4->status);
  22666. EXPECT_EQ("ABCDE", res4->body);
  22667. svr.stop();
  22668. t.join();
  22669. std::remove(fname);
  22670. }
  22671. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22672. using namespace httplib;
  22673. const char *fname = "etag_malformed.txt";
  22674. const char *content = "malformed-etag";
  22675. {
  22676. std::ofstream ofs(fname);
  22677. ofs << content;
  22678. ASSERT_TRUE(ofs.good());
  22679. }
  22680. Server svr;
  22681. svr.set_mount_point("/static", ".");
  22682. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22683. svr.wait_until_ready();
  22684. Client cli(HOST, PORT);
  22685. // baseline: should get 200 and an ETag
  22686. auto res1 = cli.Get("/static/etag_malformed.txt");
  22687. ASSERT_TRUE(res1);
  22688. ASSERT_EQ(200, res1->status);
  22689. ASSERT_TRUE(res1->has_header("ETag"));
  22690. // Malformed ETag value (missing quotes) should be treated as non-matching
  22691. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22692. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22693. ASSERT_TRUE(res_bad);
  22694. EXPECT_EQ(200, res_bad->status);
  22695. // Whitespace-only header value should be considered invalid / non-matching
  22696. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22697. "Host: localhost\r\n"
  22698. "If-None-Match: \r\n"
  22699. "Connection: close\r\n"
  22700. "\r\n";
  22701. std::string out;
  22702. ASSERT_TRUE(send_request(5, raw_req, &out));
  22703. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22704. svr.stop();
  22705. t.join();
  22706. std::remove(fname);
  22707. }
  22708. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22709. using namespace httplib;
  22710. const char *fname = "ims_invalid_format.txt";
  22711. const char *content = "ims-bad-format";
  22712. {
  22713. std::ofstream ofs(fname);
  22714. ofs << content;
  22715. ASSERT_TRUE(ofs.good());
  22716. }
  22717. Server svr;
  22718. svr.set_mount_point("/static", ".");
  22719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22720. svr.wait_until_ready();
  22721. Client cli(HOST, PORT);
  22722. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22723. ASSERT_TRUE(res1);
  22724. ASSERT_EQ(200, res1->status);
  22725. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22726. // If-Modified-Since with invalid format should not result in 304
  22727. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22728. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22729. ASSERT_TRUE(res_bad);
  22730. EXPECT_EQ(200, res_bad->status);
  22731. // If-Range with invalid date format should be treated as mismatch -> full
  22732. // content (200)
  22733. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22734. {"If-Range", "invalid-date"}};
  22735. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22736. ASSERT_TRUE(res_ifrange);
  22737. EXPECT_EQ(200, res_ifrange->status);
  22738. svr.stop();
  22739. t.join();
  22740. std::remove(fname);
  22741. }
  22742. TEST(ETagTest, IfRangeWithMalformedETag) {
  22743. using namespace httplib;
  22744. const char *fname = "ifrange_malformed.txt";
  22745. const std::string content = "0123456789";
  22746. {
  22747. std::ofstream ofs(fname);
  22748. ofs << content;
  22749. ASSERT_TRUE(ofs.good());
  22750. }
  22751. Server svr;
  22752. svr.set_mount_point("/static", ".");
  22753. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22754. svr.wait_until_ready();
  22755. Client cli(HOST, PORT);
  22756. // First request: get ETag
  22757. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22758. ASSERT_TRUE(res1);
  22759. ASSERT_EQ(200, res1->status);
  22760. ASSERT_TRUE(res1->has_header("ETag"));
  22761. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22762. // full content (200)
  22763. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22764. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22765. ASSERT_TRUE(res2);
  22766. EXPECT_EQ(200, res2->status);
  22767. EXPECT_EQ(content, res2->body);
  22768. svr.stop();
  22769. t.join();
  22770. std::remove(fname);
  22771. }
  22772. TEST(ETagTest, ExtremeLargeDateValues) {
  22773. using namespace httplib;
  22774. const char *fname = "ims_extreme_date.txt";
  22775. const char *content = "ims-extreme-date";
  22776. {
  22777. std::ofstream ofs(fname);
  22778. ofs << content;
  22779. ASSERT_TRUE(ofs.good());
  22780. }
  22781. Server svr;
  22782. svr.set_mount_point("/static", ".");
  22783. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22784. svr.wait_until_ready();
  22785. Client cli(HOST, PORT);
  22786. auto res1 = cli.Get(std::string("/static/") + fname);
  22787. ASSERT_TRUE(res1);
  22788. ASSERT_EQ(200, res1->status);
  22789. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22790. // Extremely large year that may overflow date parsing routines.
  22791. Headers h_large_date = {
  22792. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22793. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22794. ASSERT_TRUE(res_bad);
  22795. // Expect server to treat this as invalid/mismatch and return full content
  22796. EXPECT_EQ(200, res_bad->status);
  22797. // If-Range with extremely large date should be treated as mismatch -> full
  22798. // content (200)
  22799. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22800. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22801. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22802. ASSERT_TRUE(res_ifrange);
  22803. EXPECT_EQ(200, res_ifrange->status);
  22804. svr.stop();
  22805. t.join();
  22806. std::remove(fname);
  22807. }
  22808. TEST(ETagTest, NegativeFileModificationTime) {
  22809. using namespace httplib;
  22810. const char *fname = "ims_negative_mtime.txt";
  22811. const std::string content = "negative-mtime";
  22812. {
  22813. std::ofstream ofs(fname);
  22814. ofs << content;
  22815. ASSERT_TRUE(ofs.good());
  22816. }
  22817. // Try to set file mtime to a negative value. This may fail on some
  22818. // platforms/filesystems; if it fails, the test will still verify server
  22819. // behaves safely by performing a regular conditional request.
  22820. #if defined(__APPLE__) || defined(__linux__)
  22821. bool set_negative = false;
  22822. do {
  22823. struct timeval times[2];
  22824. // access time: now
  22825. times[0].tv_sec = time(nullptr);
  22826. times[0].tv_usec = 0;
  22827. // modification time: negative (e.g., -1)
  22828. times[1].tv_sec = -1;
  22829. times[1].tv_usec = 0;
  22830. if (utimes(fname, times) == 0) { set_negative = true; }
  22831. } while (0);
  22832. #else
  22833. bool set_negative = false;
  22834. #endif
  22835. Server svr;
  22836. svr.set_mount_point("/static", ".");
  22837. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22838. svr.wait_until_ready();
  22839. Client cli(HOST, PORT);
  22840. auto res1 = cli.Get(std::string("/static/") + fname);
  22841. ASSERT_TRUE(res1);
  22842. ASSERT_EQ(200, res1->status);
  22843. bool has_last_modified = res1->has_header("Last-Modified");
  22844. std::string last_modified;
  22845. if (has_last_modified) {
  22846. last_modified = res1->get_header_value("Last-Modified");
  22847. }
  22848. if (set_negative) {
  22849. // If we successfully set a negative mtime, ensure server returns a
  22850. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22851. // with an old date and ensure server handles it without crash.
  22852. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22853. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22854. ASSERT_TRUE(res2);
  22855. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22856. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22857. } else {
  22858. // Could not set negative mtime on this platform; fall back to verifying
  22859. // that normal invalid/malformed dates are treated safely (non-304).
  22860. Headers h_bad_date = {
  22861. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22862. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22863. ASSERT_TRUE(res_bad);
  22864. EXPECT_EQ(200, res_bad->status);
  22865. }
  22866. svr.stop();
  22867. t.join();
  22868. std::remove(fname);
  22869. }
  22870. //==============================================================================
  22871. // Integration Tests with Server
  22872. //==============================================================================
  22873. class SSEIntegrationTest : public ::testing::Test {
  22874. protected:
  22875. void SetUp() override {
  22876. stop_server_.store(false);
  22877. events_.clear();
  22878. server_ = httplib::detail::make_unique<Server>();
  22879. setup_server();
  22880. start_server();
  22881. }
  22882. void TearDown() override {
  22883. stop_server_.store(true);
  22884. event_cv_.notify_all();
  22885. server_->stop();
  22886. if (server_thread_.joinable()) { server_thread_.join(); }
  22887. }
  22888. void setup_server() {
  22889. // Simple SSE endpoint
  22890. server_->Get("/events", [this](const Request &req, Response &res) {
  22891. auto last_id = req.get_header_value("Last-Event-ID");
  22892. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22893. res.set_chunked_content_provider(
  22894. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22895. std::unique_lock<std::mutex> lock(event_mutex_);
  22896. if (event_cv_.wait_for(
  22897. lock, std::chrono::milliseconds(200), [this] {
  22898. return !events_.empty() || stop_server_.load();
  22899. })) {
  22900. if (stop_server_.load()) { return false; }
  22901. if (!events_.empty()) {
  22902. std::string event = events_.front();
  22903. events_.erase(events_.begin());
  22904. sink.write(event.data(), event.size());
  22905. return true;
  22906. }
  22907. }
  22908. return !stop_server_.load();
  22909. });
  22910. });
  22911. // Endpoint that returns error
  22912. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22913. res.status = 500;
  22914. res.set_content("Internal Server Error", "text/plain");
  22915. });
  22916. // Endpoint for custom event types
  22917. server_->Get("/custom-events", [](const Request &, Response &res) {
  22918. res.set_chunked_content_provider(
  22919. "text/event-stream", [](size_t offset, DataSink &sink) {
  22920. if (offset == 0) {
  22921. std::string event = "event: update\ndata: updated\n\n"
  22922. "event: delete\ndata: deleted\n\n";
  22923. sink.write(event.data(), event.size());
  22924. }
  22925. return false; // End stream after sending
  22926. });
  22927. });
  22928. }
  22929. void start_server() {
  22930. port_ = server_->bind_to_any_port(HOST);
  22931. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22932. // Wait for server to start
  22933. while (!server_->is_running()) {
  22934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22935. }
  22936. }
  22937. int get_port() const { return port_; }
  22938. void send_event(const std::string &event) {
  22939. std::lock_guard<std::mutex> lock(event_mutex_);
  22940. events_.push_back(event);
  22941. event_cv_.notify_all();
  22942. }
  22943. std::unique_ptr<Server> server_;
  22944. std::thread server_thread_;
  22945. std::mutex event_mutex_;
  22946. std::condition_variable event_cv_;
  22947. std::vector<std::string> events_;
  22948. std::atomic<bool> stop_server_{false};
  22949. std::string last_received_event_id_;
  22950. int port_ = 0;
  22951. };
  22952. //==============================================================================
  22953. // SSE Parser Tests
  22954. //==============================================================================
  22955. struct SSEParseResult {
  22956. std::vector<sse::SSEMessage> events;
  22957. std::vector<std::string> ids;
  22958. std::vector<int> retries;
  22959. bool ok = true;
  22960. std::string trace; // Every handler call in order
  22961. };
  22962. static SSEParseResult
  22963. sse_parse(const std::vector<std::string> &chunks,
  22964. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  22965. SSEParseResult r;
  22966. detail::SSEParser parser(
  22967. [&](const sse::SSEMessage &msg) {
  22968. r.events.push_back(msg);
  22969. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  22970. },
  22971. [&](const std::string &id) {
  22972. r.ids.push_back(id);
  22973. r.trace += "id[" + id + "]";
  22974. },
  22975. [&](int retry_ms) {
  22976. r.retries.push_back(retry_ms);
  22977. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  22978. },
  22979. max_event_length);
  22980. for (const auto &chunk : chunks) {
  22981. if (!parser.parse(chunk.data(), chunk.size())) {
  22982. r.ok = false;
  22983. break;
  22984. }
  22985. }
  22986. return r;
  22987. }
  22988. static SSEParseResult sse_parse(const std::string &stream) {
  22989. return sse_parse(std::vector<std::string>{stream});
  22990. }
  22991. TEST(SSEParserTest, SingleLineData) {
  22992. auto r = sse_parse("data: hello\n\n");
  22993. ASSERT_EQ(r.events.size(), 1u);
  22994. EXPECT_EQ(r.events[0].data, "hello");
  22995. EXPECT_EQ(r.events[0].event, "message");
  22996. }
  22997. TEST(SSEParserTest, MultiLineData) {
  22998. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  22999. ASSERT_EQ(r.events.size(), 1u);
  23000. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23001. }
  23002. TEST(SSEParserTest, CustomEventType) {
  23003. auto r = sse_parse("event: update\ndata: payload\n\n");
  23004. ASSERT_EQ(r.events.size(), 1u);
  23005. EXPECT_EQ(r.events[0].event, "update");
  23006. EXPECT_EQ(r.events[0].data, "payload");
  23007. }
  23008. TEST(SSEParserTest, EventIdHandling) {
  23009. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23010. ASSERT_EQ(r.events.size(), 1u);
  23011. EXPECT_EQ(r.events[0].id, "12345");
  23012. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23013. }
  23014. TEST(SSEParserTest, EmptyEventId) {
  23015. auto r = sse_parse("id:\ndata: test\n\n");
  23016. ASSERT_EQ(r.events.size(), 1u);
  23017. EXPECT_EQ(r.events[0].id, "");
  23018. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23019. }
  23020. TEST(SSEParserTest, CommentsIgnored) {
  23021. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23022. ASSERT_EQ(r.events.size(), 1u);
  23023. EXPECT_EQ(r.events[0].data, "hello");
  23024. EXPECT_EQ(r.events[0].event, "message");
  23025. }
  23026. TEST(SSEParserTest, ColonInValue) {
  23027. auto r = sse_parse("data: hello:world:test\n\n");
  23028. ASSERT_EQ(r.events.size(), 1u);
  23029. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23030. }
  23031. TEST(SSEParserTest, FieldNameOnly) {
  23032. // A line without a colon is a field name with an empty value
  23033. auto r = sse_parse("data\n\n");
  23034. ASSERT_EQ(r.events.size(), 1u);
  23035. EXPECT_EQ(r.events[0].data, "");
  23036. }
  23037. TEST(SSEParserTest, TrailingCarriageReturn) {
  23038. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23039. ASSERT_EQ(r.events.size(), 1u);
  23040. EXPECT_EQ(r.events[0].event, "update");
  23041. EXPECT_EQ(r.events[0].data, "hello");
  23042. }
  23043. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23044. auto r = sse_parse("data\r\n\r\n");
  23045. ASSERT_EQ(r.events.size(), 1u);
  23046. EXPECT_EQ(r.events[0].data, "");
  23047. }
  23048. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23049. auto r = sse_parse("event: update\rdata: hello\r\r");
  23050. ASSERT_EQ(r.events.size(), 1u);
  23051. EXPECT_EQ(r.events[0].event, "update");
  23052. EXPECT_EQ(r.events[0].data, "hello");
  23053. }
  23054. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23055. // Chunk boundaries fall inside every \r\n and right before the first one
  23056. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23057. "\ndata: hello\r", "\n\r", "\n"});
  23058. ASSERT_EQ(r.events.size(), 1u);
  23059. EXPECT_EQ(r.events[0].event, "update");
  23060. EXPECT_EQ(r.events[0].data, "hello");
  23061. }
  23062. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23063. // Only a BOM at the start of the stream is ignored
  23064. auto r = sse_parse("\xEF\xBB\xBF"
  23065. "data: first\n\n"
  23066. "\xEF\xBB\xBF"
  23067. "data: second\n\n");
  23068. ASSERT_EQ(r.events.size(), 1u);
  23069. EXPECT_EQ(r.events[0].data, "first");
  23070. }
  23071. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23072. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23073. ASSERT_EQ(r.events.size(), 1u);
  23074. EXPECT_EQ(r.events[0].data, "hello");
  23075. EXPECT_EQ(r.events[0].event, "message");
  23076. }
  23077. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23078. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23079. ASSERT_EQ(r.events.size(), 2u);
  23080. EXPECT_EQ(r.events[0].data, "hello");
  23081. EXPECT_EQ(r.events[1].data, "hello");
  23082. }
  23083. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23084. // An event without data is not dispatched, and its type must not leak
  23085. // into the next event
  23086. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23087. ASSERT_EQ(r.events.size(), 1u);
  23088. EXPECT_EQ(r.events[0].event, "message");
  23089. EXPECT_EQ(r.events[0].data, "hello");
  23090. }
  23091. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23092. // Also when the empty field replaces an earlier type
  23093. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23094. ASSERT_EQ(r.events.size(), 2u);
  23095. EXPECT_EQ(r.events[0].event, "message");
  23096. EXPECT_EQ(r.events[1].event, "message");
  23097. }
  23098. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23099. auto r = sse_parse("id: 42\n\n");
  23100. EXPECT_TRUE(r.events.empty());
  23101. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23102. }
  23103. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23104. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23105. ASSERT_EQ(r.events.size(), 2u);
  23106. EXPECT_EQ(r.events[0].id, "1");
  23107. EXPECT_EQ(r.events[1].id, "");
  23108. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23109. }
  23110. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23111. // Ids that cannot be carried in a Last-Event-ID header
  23112. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23113. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23114. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23115. }
  23116. TEST(SSEParserTest, RetryDigitsOnly) {
  23117. auto r = sse_parse("retry: 1000\n");
  23118. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23119. // A value that is not all ASCII digits, or does not fit, is ignored
  23120. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23121. EXPECT_TRUE(r.retries.empty());
  23122. }
  23123. TEST(SSEParserTest, CompleteEventParsing) {
  23124. auto r = sse_parse("event: notification\nid: evt-42\n"
  23125. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23126. ASSERT_EQ(r.events.size(), 1u);
  23127. EXPECT_EQ(r.events[0].event, "notification");
  23128. EXPECT_EQ(r.events[0].id, "evt-42");
  23129. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23130. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23131. }
  23132. TEST(SSEParserTest, IncompleteEventNotReported) {
  23133. // An event still waiting for its blank line when the stream ends is
  23134. // discarded per the SSE spec
  23135. auto r = sse_parse("id: 1\ndata: x\n");
  23136. EXPECT_TRUE(r.events.empty());
  23137. EXPECT_TRUE(r.ids.empty());
  23138. }
  23139. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23140. const std::vector<std::string> streams = {
  23141. "\xEF\xBB\xBF"
  23142. "data: bom\r\n\r\n",
  23143. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23144. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23145. };
  23146. for (const auto &stream : streams) {
  23147. auto expected = sse_parse(stream).trace;
  23148. ASSERT_FALSE(expected.empty());
  23149. for (size_t i = 0; i <= stream.size(); i++) {
  23150. auto r = sse_parse(
  23151. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23152. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23153. }
  23154. std::vector<std::string> bytes;
  23155. for (auto c : stream) {
  23156. bytes.emplace_back(1, c);
  23157. }
  23158. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23159. }
  23160. }
  23161. TEST(SSEParserTest, MaxEventLength) {
  23162. // A line still waiting for its end
  23163. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23164. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23165. // Data accumulated over the lines of one event
  23166. EXPECT_TRUE(
  23167. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23168. EXPECT_FALSE(
  23169. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23170. // 0 means no limit
  23171. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23172. // Events completed in the same chunk are still reported
  23173. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23174. EXPECT_FALSE(r.ok);
  23175. ASSERT_EQ(r.events.size(), 1u);
  23176. EXPECT_EQ(r.events[0].data, "a");
  23177. }
  23178. TEST(SSEMessageTest, Clear) {
  23179. sse::SSEMessage msg;
  23180. msg.event = "custom";
  23181. msg.data = "some data";
  23182. msg.id = "123";
  23183. msg.clear();
  23184. EXPECT_EQ(msg.event, "message");
  23185. EXPECT_EQ(msg.data, "");
  23186. EXPECT_EQ(msg.id, "");
  23187. }
  23188. //==============================================================================
  23189. // SSE Integration Tests
  23190. //==============================================================================
  23191. // Test: Successful connection and on_open callback
  23192. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23193. // Add a simple endpoint that sends one event and closes
  23194. server_->Get("/simple-event", [](const Request &, Response &res) {
  23195. res.set_chunked_content_provider(
  23196. "text/event-stream", [](size_t offset, DataSink &sink) {
  23197. if (offset == 0) {
  23198. std::string event = "data: hello\n\n";
  23199. sink.write(event.data(), event.size());
  23200. }
  23201. return false; // Close stream after sending
  23202. });
  23203. });
  23204. Client client("localhost", get_port());
  23205. sse::SSEClient sse(client, "/simple-event");
  23206. std::atomic<bool> open_called{false};
  23207. std::atomic<bool> message_received{false};
  23208. sse.on_open([&open_called]() { open_called.store(true); });
  23209. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23210. if (msg.data == "hello") { message_received.store(true); }
  23211. });
  23212. sse.set_reconnect_interval(100);
  23213. sse.set_max_reconnect_attempts(1);
  23214. // Start async
  23215. sse.start_async();
  23216. // Wait for message to be processed
  23217. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23218. sse.stop();
  23219. EXPECT_TRUE(open_called.load());
  23220. EXPECT_TRUE(message_received.load());
  23221. }
  23222. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23223. // A data line that never ends.
  23224. server_->Get("/endless-line", [](const Request &, Response &res) {
  23225. res.set_chunked_content_provider(
  23226. "text/event-stream", [](size_t offset, DataSink &sink) {
  23227. if (offset == 0) { sink.write("data: ", 6); }
  23228. std::string chunk(64 * 1024, 'A');
  23229. return sink.write(chunk.data(), chunk.size());
  23230. });
  23231. });
  23232. Client client("localhost", get_port());
  23233. sse::SSEClient sse(client, "/endless-line");
  23234. std::atomic<bool> too_long{false};
  23235. sse.on_error([&](Error err) {
  23236. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23237. });
  23238. sse.set_max_reconnect_attempts(1);
  23239. sse.start_async();
  23240. for (int i = 0; i < 500 && !too_long; i++) {
  23241. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23242. }
  23243. sse.stop();
  23244. EXPECT_TRUE(too_long);
  23245. }
  23246. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23247. // Far more in all than the client's payload limit below.
  23248. server_->Get("/many-events", [](const Request &, Response &res) {
  23249. res.set_chunked_content_provider(
  23250. "text/event-stream", [](size_t offset, DataSink &sink) {
  23251. if (offset == 0) {
  23252. std::string events;
  23253. for (int i = 0; i < 1000; i++) {
  23254. events += "data: message\n\n";
  23255. }
  23256. sink.write(events.data(), events.size());
  23257. }
  23258. return false;
  23259. });
  23260. });
  23261. Client client("localhost", get_port());
  23262. client.set_payload_max_length(1024);
  23263. sse::SSEClient sse(client, "/many-events");
  23264. std::atomic<int> messages{0};
  23265. std::atomic<bool> too_large{false};
  23266. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23267. sse.on_error([&](Error err) {
  23268. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23269. });
  23270. sse.set_max_reconnect_attempts(1);
  23271. sse.start_async();
  23272. for (int i = 0; i < 500 && messages < 1000; i++) {
  23273. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23274. }
  23275. sse.stop();
  23276. EXPECT_GE(messages.load(), 1000);
  23277. EXPECT_FALSE(too_large);
  23278. }
  23279. // Test: on_message callback
  23280. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23281. // Endpoint that sends multiple events then closes
  23282. server_->Get("/multi-event", [](const Request &, Response &res) {
  23283. res.set_chunked_content_provider(
  23284. "text/event-stream", [](size_t offset, DataSink &sink) {
  23285. if (offset == 0) {
  23286. std::string events = "data: message1\n\ndata: message2\n\n";
  23287. sink.write(events.data(), events.size());
  23288. }
  23289. return false;
  23290. });
  23291. });
  23292. Client client("localhost", get_port());
  23293. sse::SSEClient sse(client, "/multi-event");
  23294. std::vector<std::string> received_messages;
  23295. std::mutex messages_mutex;
  23296. sse.on_message([&](const sse::SSEMessage &msg) {
  23297. std::lock_guard<std::mutex> lock(messages_mutex);
  23298. received_messages.push_back(msg.data);
  23299. });
  23300. sse.set_reconnect_interval(100);
  23301. sse.set_max_reconnect_attempts(1);
  23302. sse.start_async();
  23303. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23304. sse.stop();
  23305. std::lock_guard<std::mutex> lock(messages_mutex);
  23306. EXPECT_GE(received_messages.size(), 2u);
  23307. if (received_messages.size() >= 2) {
  23308. EXPECT_EQ(received_messages[0], "message1");
  23309. EXPECT_EQ(received_messages[1], "message2");
  23310. }
  23311. }
  23312. // Test: on_event for specific types
  23313. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23314. Client client("localhost", get_port());
  23315. sse::SSEClient sse(client, "/custom-events");
  23316. std::atomic<bool> update_received{false};
  23317. std::atomic<bool> delete_received{false};
  23318. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23319. if (msg.data == "updated") { update_received.store(true); }
  23320. });
  23321. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23322. if (msg.data == "deleted") { delete_received.store(true); }
  23323. });
  23324. sse.set_max_reconnect_attempts(1);
  23325. sse.start_async();
  23326. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23327. sse.stop();
  23328. EXPECT_TRUE(update_received.load());
  23329. EXPECT_TRUE(delete_received.load());
  23330. }
  23331. // Test: on_error callback on connection failure
  23332. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23333. // Connect to a non-existent port
  23334. Client client("localhost", 59999);
  23335. sse::SSEClient sse(client, "/events");
  23336. std::atomic<bool> error_called{false};
  23337. Error received_error = Error::Success;
  23338. sse.on_error([&](Error err) {
  23339. error_called.store(true);
  23340. received_error = err;
  23341. });
  23342. sse.set_reconnect_interval(50);
  23343. sse.set_max_reconnect_attempts(1);
  23344. sse.start_async();
  23345. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23346. sse.stop();
  23347. EXPECT_TRUE(error_called.load());
  23348. EXPECT_NE(received_error, Error::Success);
  23349. }
  23350. // Test: Last-Event-ID header sent on reconnect
  23351. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23352. // Endpoint that sends event with ID
  23353. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23354. res.set_chunked_content_provider(
  23355. "text/event-stream", [](size_t offset, DataSink &sink) {
  23356. if (offset == 0) {
  23357. std::string event = "id: evt-123\ndata: test\n\n";
  23358. sink.write(event.data(), event.size());
  23359. }
  23360. return false;
  23361. });
  23362. });
  23363. Client client("localhost", get_port());
  23364. sse::SSEClient sse(client, "/event-with-id");
  23365. std::atomic<bool> id_received{false};
  23366. sse.on_message([&](const sse::SSEMessage &msg) {
  23367. if (!msg.id.empty()) { id_received.store(true); }
  23368. });
  23369. sse.set_reconnect_interval(100);
  23370. sse.set_max_reconnect_attempts(1);
  23371. sse.start_async();
  23372. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23373. sse.stop();
  23374. EXPECT_TRUE(id_received.load());
  23375. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23376. }
  23377. // Test: last_event_id() read from another thread while start_async() runs
  23378. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23379. // Ids of every length up to 200, so the stored id keeps changing size
  23380. server_->Get("/many-ids", [](const Request &, Response &res) {
  23381. res.set_chunked_content_provider(
  23382. "text/event-stream", [](size_t offset, DataSink &sink) {
  23383. if (offset == 0) {
  23384. std::string events;
  23385. for (size_t i = 0; i < 2000; i++) {
  23386. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23387. events += "data: x\n\n";
  23388. }
  23389. events += "id: end\ndata: x\n\n";
  23390. sink.write(events.data(), events.size());
  23391. }
  23392. return false;
  23393. });
  23394. });
  23395. Client client("localhost", get_port());
  23396. sse::SSEClient sse(client, "/many-ids");
  23397. // Wait out the rest of the test rather than replay the stream
  23398. sse.set_reconnect_interval(10000);
  23399. sse.set_max_reconnect_attempts(1);
  23400. sse.start_async();
  23401. auto well_formed = true;
  23402. std::string id;
  23403. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23404. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23405. id = sse.last_event_id();
  23406. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23407. well_formed = false;
  23408. }
  23409. }
  23410. sse.stop();
  23411. EXPECT_TRUE(well_formed);
  23412. EXPECT_EQ(sse.last_event_id(), "end");
  23413. }
  23414. // Test: Manual stop
  23415. TEST_F(SSEIntegrationTest, ManualStop) {
  23416. // Endpoint that sends one event and stays open briefly. The server outlives
  23417. // this test body, so the provider uses the fixture's flag, not a local.
  23418. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23419. res.set_chunked_content_provider(
  23420. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23421. if (offset == 0) {
  23422. std::string event = "data: connected\n\n";
  23423. sink.write(event.data(), event.size());
  23424. }
  23425. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23426. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23427. }
  23428. return false;
  23429. });
  23430. });
  23431. Client client("localhost", get_port());
  23432. sse::SSEClient sse(client, "/stay-open");
  23433. std::atomic<bool> connected{false};
  23434. sse.on_open([&connected]() { connected.store(true); });
  23435. sse.set_reconnect_interval(100);
  23436. sse.set_max_reconnect_attempts(1);
  23437. sse.start_async();
  23438. // Wait for connection to establish
  23439. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23440. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23441. }
  23442. EXPECT_TRUE(connected.load());
  23443. EXPECT_TRUE(sse.is_connected());
  23444. // Signal handler to stop
  23445. stop_server_.store(true);
  23446. // Stop SSE client
  23447. sse.stop();
  23448. EXPECT_FALSE(sse.is_connected());
  23449. }
  23450. // Sends one event, then nothing until stop is set
  23451. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23452. return [&stop](const Request &, Response &res) {
  23453. res.set_chunked_content_provider(
  23454. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23455. if (offset == 0) {
  23456. std::string event = "data: hello\n\n";
  23457. sink.write(event.data(), event.size());
  23458. }
  23459. while (!stop.load()) {
  23460. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23461. }
  23462. return false;
  23463. });
  23464. };
  23465. }
  23466. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23467. static void check_stop_interrupts_blocked_read(Client &client) {
  23468. client.set_read_timeout(30, 0);
  23469. for (auto by_destructor : {false, true}) {
  23470. std::atomic<bool> received{false};
  23471. std::chrono::steady_clock::time_point start;
  23472. {
  23473. sse::SSEClient sse(client, "/idle-stream");
  23474. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23475. sse.start_async();
  23476. for (int i = 0; i < 500 && !received.load(); ++i) {
  23477. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23478. }
  23479. ASSERT_TRUE(received.load());
  23480. // Let the client block in the next read
  23481. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23482. start = std::chrono::steady_clock::now();
  23483. if (!by_destructor) { sse.stop(); }
  23484. }
  23485. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23486. std::chrono::seconds(2));
  23487. }
  23488. }
  23489. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23490. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23491. Client client("localhost", get_port());
  23492. check_stop_interrupts_blocked_read(client);
  23493. }
  23494. #ifdef CPPHTTPLIB_SSL_ENABLED
  23495. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23497. std::atomic<bool> done{false};
  23498. svr.Get("/idle-stream", idle_event_stream(done));
  23499. auto port = svr.bind_to_any_port(HOST);
  23500. std::thread t([&] { svr.listen_after_bind(); });
  23501. auto se = detail::scope_exit([&] {
  23502. done.store(true);
  23503. svr.stop();
  23504. t.join();
  23505. });
  23506. svr.wait_until_ready();
  23507. Client client("https://localhost:" + std::to_string(port));
  23508. client.enable_server_certificate_verification(false);
  23509. check_stop_interrupts_blocked_read(client);
  23510. }
  23511. #endif
  23512. // Test: SSEClient with custom headers
  23513. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23514. // Setup a server endpoint that checks for custom header
  23515. std::atomic<bool> header_received{false};
  23516. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23517. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23518. header_received.store(true);
  23519. }
  23520. res.set_chunked_content_provider("text/event-stream",
  23521. [](size_t, DataSink &) { return false; });
  23522. });
  23523. Client client("localhost", get_port());
  23524. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23525. sse::SSEClient sse(client, "/header-check", headers);
  23526. sse.set_max_reconnect_attempts(1);
  23527. sse.start_async();
  23528. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23529. sse.stop();
  23530. EXPECT_TRUE(header_received.load());
  23531. }
  23532. // Test: Reconnect interval configuration
  23533. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23534. Client client("localhost", get_port());
  23535. sse::SSEClient sse(client, "/events");
  23536. auto &result = sse.set_reconnect_interval(500);
  23537. // Builder pattern should return reference to self
  23538. EXPECT_EQ(&result, &sse);
  23539. }
  23540. // Test: Max reconnect attempts
  23541. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23542. // Connect to non-existent port to force reconnects
  23543. Client client("localhost", 59998);
  23544. sse::SSEClient sse(client, "/events");
  23545. std::atomic<int> error_count{0};
  23546. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23547. sse.set_reconnect_interval(50);
  23548. sse.set_max_reconnect_attempts(2);
  23549. auto start = std::chrono::steady_clock::now();
  23550. sse.start(); // Blocking call
  23551. auto end = std::chrono::steady_clock::now();
  23552. // Should have stopped after 2 failed attempts
  23553. EXPECT_GE(error_count.load(), 2);
  23554. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23555. auto duration =
  23556. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23557. #ifdef _WIN32
  23558. // Windows is much slower for socket connection failures
  23559. EXPECT_LT(duration.count(), 7000);
  23560. #else
  23561. EXPECT_LT(duration.count(), 1000);
  23562. #endif
  23563. }
  23564. // Test: Multi-line data in integration
  23565. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23566. // Endpoint with multi-line data
  23567. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23568. res.set_chunked_content_provider(
  23569. "text/event-stream", [](size_t offset, DataSink &sink) {
  23570. if (offset == 0) {
  23571. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23572. sink.write(event.data(), event.size());
  23573. }
  23574. return false;
  23575. });
  23576. });
  23577. Client client("localhost", get_port());
  23578. sse::SSEClient sse(client, "/multiline-data");
  23579. std::string received_data;
  23580. std::mutex data_mutex;
  23581. sse.on_message([&](const sse::SSEMessage &msg) {
  23582. std::lock_guard<std::mutex> lock(data_mutex);
  23583. received_data = msg.data;
  23584. });
  23585. sse.set_reconnect_interval(100);
  23586. sse.set_max_reconnect_attempts(1);
  23587. sse.start_async();
  23588. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23589. sse.stop();
  23590. std::lock_guard<std::mutex> lock(data_mutex);
  23591. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23592. }
  23593. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23594. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23595. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23596. DataSink &sink) {
  23597. if (offset == 0) {
  23598. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23599. sink.write(events.data(), events.size());
  23600. }
  23601. return false;
  23602. });
  23603. });
  23604. Client client("localhost", get_port());
  23605. sse::SSEClient sse(client, "/empty-data-lines");
  23606. std::mutex mutex;
  23607. std::condition_variable cv;
  23608. std::vector<std::string> received;
  23609. sse.on_message([&](const sse::SSEMessage &msg) {
  23610. std::lock_guard<std::mutex> lock(mutex);
  23611. received.push_back(msg.data);
  23612. cv.notify_all();
  23613. });
  23614. sse.set_max_reconnect_attempts(1);
  23615. sse.start_async();
  23616. {
  23617. std::unique_lock<std::mutex> lock(mutex);
  23618. cv.wait_for(lock, std::chrono::seconds(2),
  23619. [&] { return received.size() >= 3; });
  23620. }
  23621. sse.stop();
  23622. ASSERT_GE(received.size(), 3u);
  23623. EXPECT_EQ(received[0], "");
  23624. EXPECT_EQ(received[1], "\nhello");
  23625. EXPECT_EQ(received[2], "");
  23626. }
  23627. // Test: Auto-reconnect after server disconnection
  23628. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23629. std::atomic<int> connection_count{0};
  23630. std::atomic<int> message_count{0};
  23631. // Endpoint that sends one event and closes, forcing reconnect
  23632. server_->Get("/reconnect-test",
  23633. [&connection_count](const Request &, Response &res) {
  23634. connection_count.fetch_add(1);
  23635. res.set_chunked_content_provider(
  23636. "text/event-stream", [](size_t offset, DataSink &sink) {
  23637. if (offset == 0) {
  23638. std::string event = "data: hello\n\n";
  23639. sink.write(event.data(), event.size());
  23640. }
  23641. return false; // Close connection after sending
  23642. });
  23643. });
  23644. Client client("localhost", get_port());
  23645. sse::SSEClient sse(client, "/reconnect-test");
  23646. sse.on_message([&message_count](const sse::SSEMessage &) {
  23647. message_count.fetch_add(1);
  23648. });
  23649. sse.set_reconnect_interval(100);
  23650. sse.set_max_reconnect_attempts(3);
  23651. sse.start_async();
  23652. // Wait long enough for multiple reconnects
  23653. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23654. sse.stop();
  23655. // Should have connected multiple times (initial + reconnects)
  23656. EXPECT_GE(connection_count.load(), 2);
  23657. // Should have received messages from multiple connections
  23658. EXPECT_GE(message_count.load(), 2);
  23659. }
  23660. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23661. std::atomic<int> connection_count{0};
  23662. // Neither Content-Length nor chunked: the close ends the stream
  23663. server_->Get("/close-delimited",
  23664. [&connection_count](const Request &, Response &res) {
  23665. connection_count.fetch_add(1);
  23666. res.set_content_provider(
  23667. "text/event-stream", [](size_t offset, DataSink &sink) {
  23668. if (offset == 0) {
  23669. std::string event = "data: hello\n\n";
  23670. sink.write(event.data(), event.size());
  23671. } else {
  23672. sink.done();
  23673. }
  23674. return true;
  23675. });
  23676. });
  23677. Client client("localhost", get_port());
  23678. sse::SSEClient sse(client, "/close-delimited");
  23679. std::atomic<int> error_count{0};
  23680. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23681. sse.set_reconnect_interval(100);
  23682. sse.start_async();
  23683. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23684. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23685. }
  23686. sse.stop();
  23687. // Reconnects as after any end of the stream, but reports no error
  23688. EXPECT_GE(connection_count.load(), 2);
  23689. EXPECT_EQ(0, error_count.load());
  23690. }
  23691. // Test: A retry field of all ASCII digits sets the reconnection time
  23692. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23693. std::mutex mutex;
  23694. std::condition_variable cv;
  23695. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23696. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23697. {
  23698. std::lock_guard<std::mutex> lock(mutex);
  23699. connected_at.push_back(std::chrono::steady_clock::now());
  23700. cv.notify_all();
  23701. }
  23702. res.set_chunked_content_provider(
  23703. "text/event-stream", [](size_t offset, DataSink &sink) {
  23704. if (offset == 0) {
  23705. std::string event = "retry: 0\ndata: hello\n\n";
  23706. sink.write(event.data(), event.size());
  23707. }
  23708. return false;
  23709. });
  23710. });
  23711. Client client("localhost", get_port());
  23712. sse::SSEClient sse(client, "/zero-retry");
  23713. sse.set_reconnect_interval(10000);
  23714. sse.start_async();
  23715. {
  23716. std::unique_lock<std::mutex> lock(mutex);
  23717. cv.wait_for(lock, std::chrono::seconds(5),
  23718. [&] { return connected_at.size() >= 2; });
  23719. }
  23720. sse.stop();
  23721. // The server-supplied interval is applied, but never below 100ms, so
  23722. // "retry: 0" does not cause a busy reconnect loop
  23723. std::lock_guard<std::mutex> lock(mutex);
  23724. ASSERT_GE(connected_at.size(), 2u);
  23725. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23726. connected_at[1] - connected_at[0])
  23727. .count();
  23728. EXPECT_GE(interval_ms, 100);
  23729. }
  23730. // Test: Last-Event-ID sent on reconnect
  23731. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23732. std::atomic<int> connection_count{0};
  23733. std::vector<std::string> received_last_event_ids;
  23734. std::mutex id_mutex;
  23735. // Endpoint that checks Last-Event-ID header and sends event with ID
  23736. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23737. int conn = connection_count.fetch_add(1);
  23738. // Capture the Last-Event-ID header from each connection
  23739. {
  23740. std::lock_guard<std::mutex> lock(id_mutex);
  23741. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23742. }
  23743. res.set_chunked_content_provider(
  23744. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23745. if (offset == 0) {
  23746. std::string event =
  23747. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23748. sink.write(event.data(), event.size());
  23749. }
  23750. return false;
  23751. });
  23752. });
  23753. Client client("localhost", get_port());
  23754. sse::SSEClient sse(client, "/reconnect-with-id");
  23755. sse.set_reconnect_interval(100);
  23756. sse.set_max_reconnect_attempts(3);
  23757. sse.start_async();
  23758. // Wait for at least 2 connections
  23759. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23760. sse.stop();
  23761. // Verify behavior
  23762. std::lock_guard<std::mutex> lock(id_mutex);
  23763. EXPECT_GE(received_last_event_ids.size(), 2u);
  23764. // First connection should have no Last-Event-ID
  23765. if (!received_last_event_ids.empty()) {
  23766. EXPECT_EQ(received_last_event_ids[0], "");
  23767. }
  23768. // Second connection should have Last-Event-ID from first connection
  23769. if (received_last_event_ids.size() >= 2) {
  23770. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23771. }
  23772. }
  23773. // Test: set_headers updates headers used on reconnect
  23774. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23775. std::vector<std::string> received_tokens;
  23776. std::mutex token_mutex;
  23777. // Endpoint that captures Authorization header
  23778. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23779. {
  23780. std::lock_guard<std::mutex> lock(token_mutex);
  23781. received_tokens.push_back(req.get_header_value("Authorization"));
  23782. }
  23783. res.set_chunked_content_provider(
  23784. "text/event-stream", [](size_t offset, DataSink &sink) {
  23785. if (offset == 0) {
  23786. std::string event = "data: hello\n\n";
  23787. sink.write(event.data(), event.size());
  23788. }
  23789. return false; // Close connection to trigger reconnect
  23790. });
  23791. });
  23792. Client client("localhost", get_port());
  23793. Headers headers = {{"Authorization", "Bearer old-token"}};
  23794. sse::SSEClient sse(client, "/auth-check", headers);
  23795. // Update headers on each successful connection
  23796. sse.on_open(
  23797. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23798. sse.set_reconnect_interval(100);
  23799. sse.set_max_reconnect_attempts(3);
  23800. sse.start_async();
  23801. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23802. sse.stop();
  23803. std::lock_guard<std::mutex> lock(token_mutex);
  23804. ASSERT_GE(received_tokens.size(), 2u);
  23805. // First connection uses original header
  23806. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23807. // Second connection uses updated header from set_headers
  23808. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23809. }
  23810. // Test: 401 allows reconnection (so on_error can refresh headers)
  23811. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23812. std::atomic<int> connection_count{0};
  23813. // Endpoint: returns 401 on first attempt, 200 on second
  23814. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23815. int conn = connection_count.fetch_add(1);
  23816. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23817. res.status = StatusCode::Unauthorized_401;
  23818. res.set_content("Unauthorized", "text/plain");
  23819. return;
  23820. }
  23821. res.set_chunked_content_provider(
  23822. "text/event-stream", [](size_t offset, DataSink &sink) {
  23823. if (offset == 0) {
  23824. std::string event = "data: authenticated\n\n";
  23825. sink.write(event.data(), event.size());
  23826. }
  23827. return false;
  23828. });
  23829. });
  23830. Client client("localhost", get_port());
  23831. Headers headers = {{"Authorization", "Bearer expired"}};
  23832. sse::SSEClient sse(client, "/auth-retry", headers);
  23833. std::atomic<bool> message_received{false};
  23834. // Refresh token on error
  23835. sse.on_error(
  23836. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23837. sse.on_message([&](const sse::SSEMessage &msg) {
  23838. if (msg.data == "authenticated") { message_received.store(true); }
  23839. });
  23840. sse.set_reconnect_interval(100);
  23841. sse.set_max_reconnect_attempts(3);
  23842. sse.start_async();
  23843. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23844. sse.stop();
  23845. // Should have reconnected after 401 and succeeded with new token
  23846. EXPECT_GE(connection_count.load(), 2);
  23847. EXPECT_TRUE(message_received.load());
  23848. }
  23849. TEST(Issue2318Test, EmptyHostString) {
  23850. {
  23851. httplib::Client cli_empty("", PORT);
  23852. auto res = cli_empty.Get("/");
  23853. ASSERT_FALSE(res);
  23854. EXPECT_EQ(httplib::Error::Connection, res.error());
  23855. }
  23856. {
  23857. httplib::Client cli(" ", PORT);
  23858. auto res = cli.Get("/");
  23859. ASSERT_FALSE(res);
  23860. EXPECT_EQ(httplib::Error::Connection, res.error());
  23861. }
  23862. }
  23863. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23864. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23865. Server svr;
  23866. // Set a small payload limit (1KB)
  23867. svr.set_payload_max_length(1024);
  23868. svr.Post("/test", [&](const Request &req, Response &res) {
  23869. res.set_content("Body size: " + std::to_string(req.body.size()),
  23870. "text/plain");
  23871. });
  23872. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23873. auto se = detail::scope_exit([&] {
  23874. svr.stop();
  23875. listen_thread.join();
  23876. });
  23877. svr.wait_until_ready();
  23878. // Create data that compresses well but exceeds limit when decompressed
  23879. // 8KB of repeated null bytes compresses to a very small size
  23880. std::string original_data(8 * 1024, '\0');
  23881. // Compress the data using gzip
  23882. std::string compressed_data;
  23883. detail::gzip_compressor compressor;
  23884. compressor.compress(original_data.data(), original_data.size(), true,
  23885. [&](const char *data, size_t size) {
  23886. compressed_data.append(data, size);
  23887. return true;
  23888. });
  23889. // Verify compression worked (compressed should be much smaller)
  23890. ASSERT_LT(compressed_data.size(), original_data.size());
  23891. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23892. // Send compressed data with Content-Encoding: gzip
  23893. Client cli(HOST, PORT);
  23894. Headers headers = {{"Content-Encoding", "gzip"}};
  23895. auto res =
  23896. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23897. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23899. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23900. }
  23901. #endif
  23902. // ============================================================================
  23903. // OpenSSL-Specific Tests
  23904. // ============================================================================
  23905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23906. X509 *readCertificate(const std::string &strFileName) {
  23907. std::ifstream inStream(strFileName);
  23908. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23909. std::istreambuf_iterator<char>());
  23910. if (strCertPEM.empty()) return (nullptr);
  23911. BIO *pbCert = BIO_new(BIO_s_mem());
  23912. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23913. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23914. BIO_free(pbCert);
  23915. return (pCert);
  23916. }
  23917. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23918. std::ifstream inStream(strFileName);
  23919. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23920. std::istreambuf_iterator<char>());
  23921. if (strPrivateKeyPEM.empty()) return (nullptr);
  23922. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23923. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23924. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23925. BIO_free(pbPrivKey);
  23926. return (pPrivateKey);
  23927. }
  23928. TEST(BindServerTest, UpdateCerts) {
  23929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23930. int port = svr.bind_to_any_port("0.0.0.0");
  23931. ASSERT_TRUE(svr.is_valid());
  23932. ASSERT_TRUE(port > 0);
  23933. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23934. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23935. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23936. ASSERT_TRUE(cert != nullptr);
  23937. ASSERT_TRUE(ca_cert != nullptr);
  23938. ASSERT_TRUE(key != nullptr);
  23939. X509_STORE *cert_store = X509_STORE_new();
  23940. X509_STORE_add_cert(cert_store, ca_cert);
  23941. // svr.update_certs(cert, key, cert_store); // deprecated
  23942. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23943. CLIENT_CA_CERT_FILE);
  23944. ASSERT_TRUE(svr.is_valid());
  23945. svr.stop();
  23946. X509_STORE_free(cert_store);
  23947. X509_free(cert);
  23948. X509_free(ca_cert);
  23949. EVP_PKEY_free(key);
  23950. }
  23951. // Test that update_certs() updates client CA list correctly
  23952. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23953. // Start with file-based constructor
  23954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23955. ASSERT_TRUE(svr.is_valid());
  23956. // Initially no client CA list should be set
  23957. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23958. ASSERT_TRUE(ssl_ctx != nullptr);
  23959. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23960. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23961. // Now update with client CA (PEM string)
  23962. std::string cert_pem, key_pem, ca_pem;
  23963. read_file(SERVER_CERT_FILE, cert_pem);
  23964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23966. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23967. ASSERT_TRUE(svr.is_valid());
  23968. // Now client CA list should be set
  23969. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23970. ASSERT_TRUE(ca_list_after != nullptr);
  23971. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23972. }
  23973. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23974. // Test that the file-path SSLServer constructor properly sets the client CA
  23975. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23977. ASSERT_TRUE(svr.is_valid());
  23978. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23979. ASSERT_TRUE(ssl_ctx != nullptr);
  23980. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23981. ASSERT_TRUE(ca_list != nullptr);
  23982. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23983. }
  23984. #endif
  23985. // ============================================================================
  23986. // MbedTLS-Specific Tests
  23987. // ============================================================================
  23988. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23989. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23990. using namespace httplib::tls;
  23991. // Track if callback was invoked
  23992. bool callback_invoked = false;
  23993. // The callback receives void* ctx which is actually MbedTlsContext*
  23994. // We can access the mbedtls_ssl_config via the context
  23995. auto setup_callback = [&callback_invoked](void *ctx) {
  23996. callback_invoked = true;
  23997. // Cast to MbedTlsContext* to access the ssl config
  23998. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23999. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24000. // Use static variables to hold certificate data (simplified for test)
  24001. static mbedtls_x509_crt own_cert;
  24002. static mbedtls_pk_context own_key;
  24003. static mbedtls_x509_crt ca_chain;
  24004. static bool initialized = false;
  24005. if (!initialized) {
  24006. mbedtls_x509_crt_init(&own_cert);
  24007. mbedtls_pk_init(&own_key);
  24008. mbedtls_x509_crt_init(&ca_chain);
  24009. // Load server certificate
  24010. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24011. return false;
  24012. }
  24013. // Load server private key.
  24014. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24015. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24016. #if MBEDTLS_VERSION_MAJOR == 3
  24017. ,
  24018. mbedtls_ctr_drbg_random, nullptr
  24019. #endif
  24020. ) != 0) {
  24021. return false;
  24022. }
  24023. // Load CA chain for client verification
  24024. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24025. return false;
  24026. }
  24027. initialized = true;
  24028. }
  24029. // Configure the SSL config
  24030. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24031. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24032. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24033. // Set minimum TLS version using mbedTLS native API
  24034. #if MBEDTLS_VERSION_MAJOR >= 3
  24035. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24036. #else
  24037. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24038. MBEDTLS_SSL_MINOR_VERSION_3);
  24039. #endif
  24040. return true;
  24041. };
  24042. SSLServer svr(setup_callback);
  24043. ASSERT_TRUE(svr.is_valid());
  24044. ASSERT_TRUE(callback_invoked);
  24045. svr.Get("/test", [&](const Request &req, Response &res) {
  24046. res.set_content("test", "text/plain");
  24047. auto cert = req.peer_cert();
  24048. ASSERT_TRUE(static_cast<bool>(cert));
  24049. auto common_name = cert.subject_cn();
  24050. EXPECT_EQ("Common Name", common_name);
  24051. });
  24052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24053. auto se = detail::scope_exit([&] {
  24054. svr.stop();
  24055. t.join();
  24056. ASSERT_FALSE(svr.is_running());
  24057. });
  24058. svr.wait_until_ready();
  24059. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24060. cli.enable_server_certificate_verification(false);
  24061. cli.set_connection_timeout(30);
  24062. auto res = cli.Get("/test");
  24063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24064. ASSERT_EQ(StatusCode::OK_200, res->status);
  24065. }
  24066. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24067. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24068. // keep-alive SSL session, which reads through that config in
  24069. // mbedtls_ssl_close_notify.
  24070. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24072. ASSERT_TRUE(svr.is_valid());
  24073. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24074. res.set_content("test", "text/plain");
  24075. });
  24076. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24077. auto se = detail::scope_exit([&] {
  24078. svr.stop();
  24079. t.join();
  24080. ASSERT_FALSE(svr.is_running());
  24081. });
  24082. svr.wait_until_ready();
  24083. {
  24084. SSLClient cli(HOST, PORT);
  24085. cli.enable_server_certificate_verification(false);
  24086. cli.set_keep_alive(true);
  24087. auto res = cli.Get("/test");
  24088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24089. ASSERT_EQ(StatusCode::OK_200, res->status);
  24090. // cli is destructed here with the keep-alive SSL session still open.
  24091. }
  24092. }
  24093. #endif
  24094. // WebSocket Tests
  24095. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24096. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24097. // defining the meaning of these bits has been negotiated.
  24098. auto make_frame = [](uint8_t first_byte) {
  24099. std::string frame;
  24100. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24101. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24102. frame += "Hello";
  24103. return frame;
  24104. };
  24105. // RSV1 set (0x40)
  24106. {
  24107. detail::BufferStream strm;
  24108. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24109. ws::Opcode opcode;
  24110. std::string payload;
  24111. bool fin;
  24112. EXPECT_EQ(
  24113. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24114. ws::impl::FrameRead::Fail);
  24115. }
  24116. // RSV2 set (0x20)
  24117. {
  24118. detail::BufferStream strm;
  24119. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24120. ws::Opcode opcode;
  24121. std::string payload;
  24122. bool fin;
  24123. EXPECT_EQ(
  24124. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24125. ws::impl::FrameRead::Fail);
  24126. }
  24127. // RSV3 set (0x10)
  24128. {
  24129. detail::BufferStream strm;
  24130. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24131. ws::Opcode opcode;
  24132. std::string payload;
  24133. bool fin;
  24134. EXPECT_EQ(
  24135. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24136. ws::impl::FrameRead::Fail);
  24137. }
  24138. // No RSV bits set - should succeed
  24139. {
  24140. detail::BufferStream strm;
  24141. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24142. ws::Opcode opcode;
  24143. std::string payload;
  24144. bool fin;
  24145. EXPECT_EQ(
  24146. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24147. ws::impl::FrameRead::Ok);
  24148. EXPECT_EQ(ws::Opcode::Text, opcode);
  24149. EXPECT_EQ("Hello", payload);
  24150. EXPECT_TRUE(fin);
  24151. }
  24152. }
  24153. TEST(WebSocketTest, ControlFrameValidation) {
  24154. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24155. // payload length <= 125.
  24156. // Ping with FIN=0 - must be rejected
  24157. {
  24158. detail::BufferStream strm;
  24159. std::string frame;
  24160. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24161. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24162. strm.write(frame.data(), frame.size());
  24163. ws::Opcode opcode;
  24164. std::string payload;
  24165. bool fin;
  24166. EXPECT_EQ(
  24167. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24168. ws::impl::FrameRead::Fail);
  24169. }
  24170. // Close with FIN=0 - must be rejected
  24171. {
  24172. detail::BufferStream strm;
  24173. std::string frame;
  24174. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24175. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24176. strm.write(frame.data(), frame.size());
  24177. ws::Opcode opcode;
  24178. std::string payload;
  24179. bool fin;
  24180. EXPECT_EQ(
  24181. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24182. ws::impl::FrameRead::Fail);
  24183. }
  24184. // Ping with payload_len=126 (extended length) - must be rejected
  24185. {
  24186. detail::BufferStream strm;
  24187. std::string frame;
  24188. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24189. frame += static_cast<char>(126); // payload_len=126 (>125)
  24190. frame += static_cast<char>(0x00); // extended length high byte
  24191. frame += static_cast<char>(126); // extended length low byte
  24192. frame += std::string(126, 'x');
  24193. strm.write(frame.data(), frame.size());
  24194. ws::Opcode opcode;
  24195. std::string payload;
  24196. bool fin;
  24197. EXPECT_EQ(
  24198. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24199. ws::impl::FrameRead::Fail);
  24200. }
  24201. // Ping with FIN=1 and payload_len=125 - should succeed
  24202. {
  24203. detail::BufferStream strm;
  24204. std::string frame;
  24205. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24206. frame += static_cast<char>(125); // payload_len=125
  24207. frame += std::string(125, 'x');
  24208. strm.write(frame.data(), frame.size());
  24209. ws::Opcode opcode;
  24210. std::string payload;
  24211. bool fin;
  24212. EXPECT_EQ(
  24213. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24214. ws::impl::FrameRead::Ok);
  24215. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24216. EXPECT_EQ(125u, payload.size());
  24217. EXPECT_TRUE(fin);
  24218. }
  24219. }
  24220. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24221. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24222. // length MUST be 0.
  24223. // MSB set - must be rejected
  24224. {
  24225. detail::BufferStream strm;
  24226. std::string frame;
  24227. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24228. frame += static_cast<char>(127); // 64-bit extended length
  24229. frame += static_cast<char>(0x80); // MSB set (invalid)
  24230. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24231. strm.write(frame.data(), frame.size());
  24232. ws::Opcode opcode;
  24233. std::string payload;
  24234. bool fin;
  24235. EXPECT_EQ(
  24236. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24237. ws::impl::FrameRead::Fail);
  24238. }
  24239. // MSB clear - should pass length parsing (will be rejected by max_len,
  24240. // but that's a different check; use a small length to verify)
  24241. {
  24242. detail::BufferStream strm;
  24243. std::string frame;
  24244. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24245. frame += static_cast<char>(127); // 64-bit extended length
  24246. frame += std::string(7, '\0'); // high bytes = 0
  24247. frame += static_cast<char>(0x03); // length = 3
  24248. frame += "abc";
  24249. strm.write(frame.data(), frame.size());
  24250. ws::Opcode opcode;
  24251. std::string payload;
  24252. bool fin;
  24253. EXPECT_EQ(
  24254. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24255. ws::impl::FrameRead::Ok);
  24256. EXPECT_EQ(ws::Opcode::Text, opcode);
  24257. EXPECT_EQ("abc", payload);
  24258. }
  24259. }
  24260. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24261. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24262. // Valid UTF-8
  24263. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24264. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24265. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24266. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24267. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24268. // Invalid UTF-8
  24269. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24270. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24271. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24272. EXPECT_FALSE(
  24273. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24274. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24275. }
  24276. TEST(WebSocketTest, ConnectAndDisconnect) {
  24277. Server svr;
  24278. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24279. std::string msg;
  24280. while (ws.read(msg)) {}
  24281. });
  24282. auto port = svr.bind_to_any_port(HOST);
  24283. std::thread t([&]() { svr.listen_after_bind(); });
  24284. svr.wait_until_ready();
  24285. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24286. auto res = client.connect();
  24287. ASSERT_TRUE(res);
  24288. EXPECT_EQ(Error::Success, res.error());
  24289. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24290. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24291. EXPECT_TRUE(client.is_open());
  24292. client.close();
  24293. EXPECT_FALSE(client.is_open());
  24294. svr.stop();
  24295. t.join();
  24296. }
  24297. TEST(WebSocketTest, ValidURL) {
  24298. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24299. EXPECT_TRUE(ws1.is_valid());
  24300. ws::WebSocketClient ws2("ws://example.com/path");
  24301. EXPECT_TRUE(ws2.is_valid());
  24302. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24303. EXPECT_TRUE(ws3.is_valid());
  24304. #ifdef CPPHTTPLIB_SSL_ENABLED
  24305. ws::WebSocketClient wss1("wss://example.com/path");
  24306. EXPECT_TRUE(wss1.is_valid());
  24307. ws::WebSocketClient wss2("wss://example.com:443/path");
  24308. EXPECT_TRUE(wss2.is_valid());
  24309. #endif
  24310. }
  24311. TEST(WebSocketTest, InvalidURL) {
  24312. // No scheme
  24313. ws::WebSocketClient ws1("localhost:8080/path");
  24314. EXPECT_FALSE(ws1.is_valid());
  24315. // No path
  24316. ws::WebSocketClient ws2("ws://localhost:8080");
  24317. EXPECT_FALSE(ws2.is_valid());
  24318. // Empty string
  24319. ws::WebSocketClient ws3("");
  24320. EXPECT_FALSE(ws3.is_valid());
  24321. // Missing host
  24322. ws::WebSocketClient ws4("ws://:8080/path");
  24323. EXPECT_FALSE(ws4.is_valid());
  24324. // Port number overflow — should not crash
  24325. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24326. EXPECT_FALSE(ws5.is_valid());
  24327. // Port out of range
  24328. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24329. EXPECT_FALSE(ws6.is_valid());
  24330. }
  24331. TEST(WebSocketTest, UnsupportedScheme) {
  24332. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24333. ws::WebSocketClient ws1("http://localhost:8080/path");
  24334. EXPECT_FALSE(ws1.is_valid());
  24335. ws::WebSocketClient ws2("https://localhost:8080/path");
  24336. EXPECT_FALSE(ws2.is_valid());
  24337. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24338. EXPECT_FALSE(ws3.is_valid());
  24339. #else
  24340. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24341. std::invalid_argument);
  24342. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24343. std::invalid_argument);
  24344. #endif
  24345. }
  24346. TEST(WebSocketTest, ConnectWhenInvalid) {
  24347. ws::WebSocketClient ws("not a valid url");
  24348. EXPECT_FALSE(ws.is_valid());
  24349. auto res = ws.connect();
  24350. EXPECT_FALSE(res);
  24351. EXPECT_EQ(Error::Connection, res.error());
  24352. EXPECT_EQ(-1, res.status());
  24353. }
  24354. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24355. // Grab a port that is free, then close it again so nothing listens there
  24356. Server svr;
  24357. auto port = svr.bind_to_any_port(HOST);
  24358. svr.stop();
  24359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24360. auto res = client.connect();
  24361. ASSERT_FALSE(res);
  24362. EXPECT_EQ(Error::Connection, res.error());
  24363. EXPECT_EQ(-1, res.status());
  24364. }
  24365. TEST(WebSocketTest, DefaultPort) {
  24366. ws::WebSocketClient ws1("ws://example.com/path");
  24367. EXPECT_TRUE(ws1.is_valid());
  24368. // ws:// defaults to port 80 (verified by successful parse)
  24369. #ifdef CPPHTTPLIB_SSL_ENABLED
  24370. ws::WebSocketClient ws2("wss://example.com/path");
  24371. EXPECT_TRUE(ws2.is_valid());
  24372. // wss:// defaults to port 443 (verified by successful parse)
  24373. #endif
  24374. }
  24375. TEST(WebSocketTest, IPv6LiteralAddress) {
  24376. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24377. EXPECT_TRUE(ws1.is_valid());
  24378. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24379. EXPECT_TRUE(ws2.is_valid());
  24380. }
  24381. TEST(WebSocketTest, ComplexPath) {
  24382. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24383. EXPECT_TRUE(ws1.is_valid());
  24384. ws::WebSocketClient ws2("ws://localhost:8080/");
  24385. EXPECT_TRUE(ws2.is_valid());
  24386. }
  24387. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24388. Server svr;
  24389. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24390. std::string msg;
  24391. while (ws.read(msg)) {}
  24392. });
  24393. auto port = svr.bind_to_any_port(HOST);
  24394. std::thread t([&]() { svr.listen_after_bind(); });
  24395. svr.wait_until_ready();
  24396. auto another_host = "example.com";
  24397. auto wrong_ip = "192.0.2.1";
  24398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24399. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24400. ASSERT_TRUE(client.connect());
  24401. EXPECT_TRUE(client.is_open());
  24402. client.close();
  24403. svr.stop();
  24404. t.join();
  24405. }
  24406. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24407. Server svr;
  24408. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24409. std::string msg;
  24410. while (ws.read(msg)) {}
  24411. });
  24412. auto port = svr.bind_to_any_port(HOST);
  24413. std::thread t([&]() { svr.listen_after_bind(); });
  24414. svr.wait_until_ready();
  24415. auto wrong_ip = "192.0.2.1";
  24416. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24417. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24418. client.set_connection_timeout(1);
  24419. client.set_read_timeout(1);
  24420. client.set_write_timeout(1);
  24421. EXPECT_FALSE(client.connect());
  24422. EXPECT_FALSE(client.is_open());
  24423. svr.stop();
  24424. t.join();
  24425. }
  24426. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24427. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24428. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24429. // (RFC 6761) is only a map key and the Host header value.
  24430. auto host = "target.invalid";
  24431. Server svr;
  24432. std::string received_host;
  24433. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24434. received_host = req.get_header_value("Host");
  24435. std::string msg;
  24436. while (ws.read(msg)) {}
  24437. });
  24438. auto port = svr.bind_to_any_port(HOST);
  24439. std::thread t([&]() { svr.listen_after_bind(); });
  24440. // ASSERT_* below returns from the test body, which would leave t joinable
  24441. // and make ~thread call std::terminate.
  24442. auto se = detail::scope_exit([&] {
  24443. svr.stop();
  24444. if (t.joinable()) { t.join(); }
  24445. });
  24446. svr.wait_until_ready();
  24447. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24448. std::to_string(port) + "/ws");
  24449. client.set_direct_hostname_addr_map({{host, HOST}});
  24450. ASSERT_TRUE(client.connect());
  24451. EXPECT_TRUE(client.is_open());
  24452. client.close();
  24453. svr.stop();
  24454. t.join();
  24455. // The mapping only redirects the connection; the identity stays host_.
  24456. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24457. }
  24458. class WebSocketIntegrationTest : public ::testing::Test {
  24459. protected:
  24460. void SetUp() override {
  24461. server_ = httplib::detail::make_unique<Server>();
  24462. setup_server();
  24463. start_server();
  24464. }
  24465. void TearDown() override {
  24466. server_->stop();
  24467. if (server_thread_.joinable()) { server_thread_.join(); }
  24468. }
  24469. void setup_server() {
  24470. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24471. std::string msg;
  24472. ws::ReadResult ret;
  24473. while ((ret = ws.read(msg))) {
  24474. if (ret == ws::Binary) {
  24475. ws.send(msg.data(), msg.size());
  24476. } else {
  24477. ws.send(msg);
  24478. }
  24479. }
  24480. });
  24481. server_->WebSocket("/ws-echo-string",
  24482. [](const Request &, ws::WebSocket &ws) {
  24483. std::string msg;
  24484. while (ws.read(msg)) {
  24485. ws.send("echo: " + msg);
  24486. }
  24487. });
  24488. server_->WebSocket(
  24489. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24490. // Echo back request metadata
  24491. ws.send("path:" + req.path);
  24492. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24493. std::string msg;
  24494. while (ws.read(msg)) {}
  24495. });
  24496. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24497. std::string msg;
  24498. ws.read(msg); // wait for a message
  24499. ws.close();
  24500. });
  24501. server_->WebSocket("/ws-close-status",
  24502. [](const Request &, ws::WebSocket &ws) {
  24503. std::string msg;
  24504. ws.read(msg); // wait for a message
  24505. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24506. });
  24507. server_->WebSocket(
  24508. "/ws-subprotocol",
  24509. [](const Request &, ws::WebSocket &ws) {
  24510. std::string msg;
  24511. while (ws.read(msg)) {
  24512. ws.send(msg);
  24513. }
  24514. },
  24515. [](const std::vector<std::string> &protocols) -> std::string {
  24516. for (const auto &p : protocols) {
  24517. if (p == "graphql-ws") { return p; }
  24518. }
  24519. return "";
  24520. });
  24521. server_->WebSocket(
  24522. "/ws-subprotocol-unoffered",
  24523. [](const Request &, ws::WebSocket &ws) {
  24524. std::string msg;
  24525. while (ws.read(msg)) {
  24526. ws.send(msg);
  24527. }
  24528. },
  24529. [](const std::vector<std::string> &) -> std::string {
  24530. return "admin";
  24531. });
  24532. }
  24533. void start_server() {
  24534. port_ = server_->bind_to_any_port(HOST);
  24535. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24536. server_->wait_until_ready();
  24537. }
  24538. std::unique_ptr<Server> server_;
  24539. std::thread server_thread_;
  24540. int port_ = 0;
  24541. };
  24542. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24544. "/ws-echo");
  24545. ASSERT_TRUE(client.connect());
  24546. ASSERT_TRUE(client.is_open());
  24547. ASSERT_TRUE(client.send("Hello WebSocket"));
  24548. std::string msg;
  24549. EXPECT_EQ(ws::Text, client.read(msg));
  24550. EXPECT_EQ("Hello WebSocket", msg);
  24551. client.close();
  24552. }
  24553. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24555. "/ws-echo");
  24556. ASSERT_TRUE(client.connect());
  24557. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24558. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24559. std::string msg;
  24560. EXPECT_EQ(ws::Binary, client.read(msg));
  24561. EXPECT_EQ(binary_data, msg);
  24562. client.close();
  24563. }
  24564. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24566. "/ws-echo");
  24567. ASSERT_TRUE(client.connect());
  24568. for (int i = 0; i < 10; i++) {
  24569. auto text = "message " + std::to_string(i);
  24570. ASSERT_TRUE(client.send(text));
  24571. std::string msg;
  24572. ASSERT_TRUE(client.read(msg));
  24573. EXPECT_EQ(text, msg);
  24574. }
  24575. client.close();
  24576. }
  24577. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24579. "/ws-close");
  24580. ASSERT_TRUE(client.connect());
  24581. // Send a message to trigger the server to close
  24582. ASSERT_TRUE(client.send("trigger close"));
  24583. // The server will close, so read should return false
  24584. std::string msg;
  24585. EXPECT_FALSE(client.read(msg));
  24586. EXPECT_FALSE(client.is_open());
  24587. }
  24588. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24589. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24590. "/ws-echo");
  24591. ASSERT_TRUE(client.connect());
  24592. // 128KB message
  24593. std::string large_data(128 * 1024, 'X');
  24594. ASSERT_TRUE(client.send(large_data));
  24595. std::string msg;
  24596. ASSERT_TRUE(client.read(msg));
  24597. EXPECT_EQ(large_data, msg);
  24598. client.close();
  24599. }
  24600. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24602. "/ws-echo");
  24603. ASSERT_TRUE(client.connect());
  24604. const int num_threads = 4;
  24605. std::vector<std::thread> threads;
  24606. std::atomic<int> send_count{0};
  24607. for (int t = 0; t < num_threads; t++) {
  24608. threads.emplace_back([&client, &send_count, t]() {
  24609. for (int i = 0; i < 5; i++) {
  24610. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24611. if (client.send(text)) { send_count++; }
  24612. }
  24613. });
  24614. }
  24615. for (auto &th : threads) {
  24616. th.join();
  24617. }
  24618. int received = 0;
  24619. std::string msg;
  24620. while (received < send_count.load()) {
  24621. if (!client.read(msg)) { break; }
  24622. received++;
  24623. }
  24624. EXPECT_EQ(send_count.load(), received);
  24625. client.close();
  24626. }
  24627. TEST_F(WebSocketIntegrationTest, ReadString) {
  24628. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24629. "/ws-echo-string");
  24630. ASSERT_TRUE(client.connect());
  24631. ASSERT_TRUE(client.send("hello"));
  24632. std::string msg;
  24633. ASSERT_TRUE(client.read(msg));
  24634. EXPECT_EQ("echo: hello", msg);
  24635. ASSERT_TRUE(client.send("world"));
  24636. ASSERT_TRUE(client.read(msg));
  24637. EXPECT_EQ("echo: world", msg);
  24638. client.close();
  24639. }
  24640. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24641. Headers headers = {{"X-Test-Header", "test-value"}};
  24642. ws::WebSocketClient client(
  24643. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24644. ASSERT_TRUE(client.connect());
  24645. std::string msg;
  24646. ASSERT_TRUE(client.read(msg));
  24647. EXPECT_EQ("path:/ws-request-info", msg);
  24648. ASSERT_TRUE(client.read(msg));
  24649. EXPECT_EQ("header:test-value", msg);
  24650. client.close();
  24651. }
  24652. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24653. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24654. "/ws-echo");
  24655. client.set_read_timeout(1, 0); // 1 second
  24656. ASSERT_TRUE(client.connect());
  24657. // Don't send anything — server echo handler waits for a message, so read()
  24658. // should time out. The connection survives it: nothing was consumed.
  24659. std::string msg;
  24660. EXPECT_EQ(client.read(msg), ws::Timeout);
  24661. EXPECT_TRUE(client.is_open());
  24662. // And it is still usable afterwards.
  24663. EXPECT_TRUE(client.send("after timeout"));
  24664. EXPECT_EQ(client.read(msg), ws::Text);
  24665. EXPECT_EQ(msg, "after timeout");
  24666. }
  24667. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24668. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24669. "/ws-echo");
  24670. client.set_read_timeout(1, 0);
  24671. ASSERT_TRUE(client.connect());
  24672. ASSERT_TRUE(client.send("first"));
  24673. std::string msg;
  24674. ASSERT_EQ(client.read(msg), ws::Text);
  24675. ASSERT_EQ(msg, "first");
  24676. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24677. // not be used with a read timeout: it would reprocess the previous message.
  24678. EXPECT_EQ(client.read(msg), ws::Timeout);
  24679. EXPECT_EQ(msg, "first");
  24680. }
  24681. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24683. "/ws-echo");
  24684. ASSERT_TRUE(client.connect());
  24685. // Setting it once the connection is open reaches the live stream, not just
  24686. // the seed for the next connect().
  24687. client.set_read_timeout(1, 0);
  24688. std::string msg;
  24689. EXPECT_EQ(client.read(msg), ws::Timeout);
  24690. EXPECT_TRUE(client.is_open());
  24691. }
  24692. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24694. "/ws-echo");
  24695. client.set_read_timeout(5, 0);
  24696. ASSERT_TRUE(client.connect());
  24697. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24698. // The server should reject it and close the connection.
  24699. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24700. client.send(oversized);
  24701. // The server's read() should have failed due to payload limit,
  24702. // so our read() should return false (connection closed).
  24703. std::string msg;
  24704. EXPECT_FALSE(client.read(msg));
  24705. }
  24706. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24708. "/ws-echo");
  24709. client.set_read_timeout(10, 0);
  24710. ASSERT_TRUE(client.connect());
  24711. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24712. // This should succeed.
  24713. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24714. ASSERT_TRUE(client.send(at_limit));
  24715. std::string msg;
  24716. ASSERT_TRUE(client.read(msg));
  24717. EXPECT_EQ(at_limit.size(), msg.size());
  24718. client.close();
  24719. }
  24720. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24722. "/nonexistent");
  24723. auto res = client.connect();
  24724. EXPECT_FALSE(res);
  24725. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24726. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24727. EXPECT_FALSE(client.is_open());
  24728. }
  24729. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24730. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24731. "/ws-echo");
  24732. ASSERT_TRUE(client.connect());
  24733. ASSERT_TRUE(client.send(""));
  24734. std::string msg;
  24735. EXPECT_EQ(ws::Text, client.read(msg));
  24736. EXPECT_EQ("", msg);
  24737. client.close();
  24738. }
  24739. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24741. "/ws-echo");
  24742. // First connection
  24743. ASSERT_TRUE(client.connect());
  24744. ASSERT_TRUE(client.send("first"));
  24745. std::string msg;
  24746. ASSERT_TRUE(client.read(msg));
  24747. EXPECT_EQ("first", msg);
  24748. client.close();
  24749. EXPECT_FALSE(client.is_open());
  24750. // Reconnect using the same client object
  24751. ASSERT_TRUE(client.connect());
  24752. ASSERT_TRUE(client.is_open());
  24753. ASSERT_TRUE(client.send("second"));
  24754. ASSERT_TRUE(client.read(msg));
  24755. EXPECT_EQ("second", msg);
  24756. client.close();
  24757. }
  24758. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24760. "/ws-close-status");
  24761. ASSERT_TRUE(client.connect());
  24762. // Trigger the server to close with GoingAway status
  24763. ASSERT_TRUE(client.send("trigger"));
  24764. // read() should return false after receiving the close frame
  24765. std::string msg;
  24766. EXPECT_FALSE(client.read(msg));
  24767. EXPECT_FALSE(client.is_open());
  24768. }
  24769. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24771. "/ws-echo");
  24772. ASSERT_TRUE(client.connect());
  24773. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24774. EXPECT_FALSE(client.is_open());
  24775. }
  24776. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24777. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24778. ws::WebSocketClient client(
  24779. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24780. ASSERT_TRUE(client.connect());
  24781. // Server should have selected graphql-ws
  24782. EXPECT_EQ("graphql-ws", client.subprotocol());
  24783. client.close();
  24784. }
  24785. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24786. Headers headers;
  24787. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24788. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24789. ws::WebSocketClient client(
  24790. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24791. ASSERT_TRUE(client.connect());
  24792. // The offer on the second field line counts too, so graphql-ws is selected
  24793. EXPECT_EQ("graphql-ws", client.subprotocol());
  24794. client.close();
  24795. }
  24796. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24797. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24798. ws::WebSocketClient client(
  24799. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24800. ASSERT_TRUE(client.connect());
  24801. // Server should not have selected any subprotocol
  24802. EXPECT_TRUE(client.subprotocol().empty());
  24803. client.close();
  24804. }
  24805. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24806. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24807. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24808. "/ws-subprotocol-unoffered",
  24809. headers);
  24810. ASSERT_TRUE(client.connect());
  24811. EXPECT_TRUE(client.subprotocol().empty());
  24812. client.close();
  24813. }
  24814. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24815. // Connect without requesting any subprotocol
  24816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24817. "/ws-subprotocol");
  24818. ASSERT_TRUE(client.connect());
  24819. EXPECT_TRUE(client.subprotocol().empty());
  24820. client.close();
  24821. }
  24822. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24823. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24824. "/ws-echo");
  24825. client.set_tcp_nodelay(true);
  24826. client.set_connection_timeout(3, 0);
  24827. bool socket_options_called = false;
  24828. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24829. ASSERT_TRUE(client.connect());
  24830. ASSERT_TRUE(client.is_open());
  24831. EXPECT_TRUE(socket_options_called);
  24832. ASSERT_TRUE(client.send("hello"));
  24833. std::string msg;
  24834. auto result = client.read(msg);
  24835. EXPECT_EQ(result, ws::ReadResult::Text);
  24836. EXPECT_EQ(msg, "hello");
  24837. client.close();
  24838. }
  24839. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24841. "/ws-echo");
  24842. client.set_connection_timeout(std::chrono::seconds(3));
  24843. client.set_write_timeout(std::chrono::seconds(3));
  24844. // A sub-second remainder exercises the seconds/microseconds split.
  24845. client.set_read_timeout(std::chrono::milliseconds(1500));
  24846. ASSERT_TRUE(client.connect());
  24847. auto start = std::chrono::steady_clock::now();
  24848. std::string msg;
  24849. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24850. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24851. std::chrono::steady_clock::now() - start)
  24852. .count();
  24853. // Above 1s so that dropping the microseconds half of the split fails here.
  24854. // Ignoring the setter altogether would not reach this line at all: a client
  24855. // waits forever by default.
  24856. EXPECT_GE(elapsed, 1400);
  24857. EXPECT_LT(elapsed, 30000);
  24858. }
  24859. #ifndef _WIN32
  24860. // A send() that times out after part of the data went out returns the count
  24861. // written so far. Every byte of the frame must still be sent, or the peer reads
  24862. // the next frame's header and payload as the rest of this one.
  24863. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24864. signal(SIGPIPE, SIG_IGN);
  24865. const std::string large(4 * 1024 * 1024, 'A');
  24866. std::atomic<bool> large_sent{false};
  24867. std::atomic<bool> small_sent{false};
  24868. Server svr;
  24869. svr.set_write_timeout(0, 500000);
  24870. svr.set_socket_options([](socket_t sock) {
  24871. int size = 8192;
  24872. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24873. reinterpret_cast<const char *>(&size), sizeof(size));
  24874. });
  24875. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24876. large_sent = ws.send(large.data(), large.size());
  24877. small_sent = ws.send("after");
  24878. std::string msg;
  24879. while (ws.read(msg)) {}
  24880. });
  24881. auto port = svr.bind_to_any_port(HOST);
  24882. std::thread t([&]() { svr.listen_after_bind(); });
  24883. auto se = detail::scope_exit([&] {
  24884. svr.stop();
  24885. t.join();
  24886. });
  24887. svr.wait_until_ready();
  24888. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24889. std::to_string(port) + "/ws");
  24890. client.set_read_timeout(5);
  24891. client.set_socket_options([](socket_t sock) {
  24892. int size = 8192;
  24893. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24894. reinterpret_cast<const char *>(&size), sizeof(size));
  24895. });
  24896. ASSERT_TRUE(client.connect());
  24897. // Outlast the server's write timeout, then drain.
  24898. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24899. std::string msg;
  24900. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24901. EXPECT_TRUE(msg == large);
  24902. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24903. EXPECT_EQ("after", msg);
  24904. EXPECT_TRUE(large_sent);
  24905. EXPECT_TRUE(small_sent);
  24906. client.close();
  24907. }
  24908. #endif
  24909. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24910. Server svr;
  24911. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24912. if (!req.has_header("Authorization")) {
  24913. res.status = StatusCode::Unauthorized_401;
  24914. res.set_content("Unauthorized", "text/plain");
  24915. return Server::HandlerResponse::Handled;
  24916. }
  24917. return Server::HandlerResponse::Unhandled;
  24918. });
  24919. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24920. std::string msg;
  24921. while (ws.read(msg)) {
  24922. ws.send(msg);
  24923. }
  24924. });
  24925. auto port = svr.bind_to_any_port("localhost");
  24926. std::thread t([&]() { svr.listen_after_bind(); });
  24927. svr.wait_until_ready();
  24928. // Without Authorization header - should be rejected before upgrade
  24929. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24930. EXPECT_FALSE(client1.connect());
  24931. // The rejection is framed like any other HTTP response
  24932. {
  24933. Client cli("localhost", port);
  24934. Headers headers = {{"Upgrade", "websocket"},
  24935. {"Connection", "Upgrade"},
  24936. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24937. {"Sec-WebSocket-Version", "13"}};
  24938. auto res = cli.Get("/ws", headers);
  24939. ASSERT_TRUE(res);
  24940. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24941. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24942. EXPECT_EQ("Unauthorized", res->body);
  24943. }
  24944. // With Authorization header - should succeed
  24945. Headers headers = {{"Authorization", "Bearer token123"}};
  24946. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24947. headers);
  24948. ASSERT_TRUE(client2.connect());
  24949. ASSERT_TRUE(client2.send("hello"));
  24950. std::string msg;
  24951. ASSERT_TRUE(client2.read(msg));
  24952. EXPECT_EQ("hello", msg);
  24953. client2.close();
  24954. svr.stop();
  24955. t.join();
  24956. }
  24957. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24958. Server svr;
  24959. std::atomic<int> pre_routing_calls{0};
  24960. std::atomic<int> pre_request_calls{0};
  24961. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24962. pre_routing_calls++;
  24963. if (req.path == "/handled") {
  24964. res.set_content("handled", "text/plain");
  24965. return Server::HandlerResponse::Handled;
  24966. }
  24967. return Server::HandlerResponse::Unhandled;
  24968. });
  24969. svr.set_pre_request_handler([&](const Request &, Response &) {
  24970. pre_request_calls++;
  24971. return Server::HandlerResponse::Unhandled;
  24972. });
  24973. svr.Get("/http", [](const Request &, Response &res) {
  24974. res.set_content("http", "text/plain");
  24975. });
  24976. svr.WebSocket("/ws",
  24977. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24978. auto port = svr.bind_to_any_port("localhost");
  24979. std::thread t([&]() { svr.listen_after_bind(); });
  24980. auto se = detail::scope_exit([&] {
  24981. svr.stop();
  24982. t.join();
  24983. });
  24984. svr.wait_until_ready();
  24985. Headers upgrade = {{"Upgrade", "websocket"},
  24986. {"Connection", "Upgrade"},
  24987. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24988. {"Sec-WebSocket-Version", "13"}};
  24989. auto get = [&](const char *path) {
  24990. pre_routing_calls = 0;
  24991. return Client("localhost", port).Get(path, upgrade);
  24992. };
  24993. // No WebSocket route, but an HTTP one
  24994. auto res = get("/http");
  24995. ASSERT_TRUE(res);
  24996. EXPECT_EQ(StatusCode::OK_200, res->status);
  24997. EXPECT_EQ("http", res->body);
  24998. EXPECT_EQ(1, pre_routing_calls);
  24999. EXPECT_EQ(1, pre_request_calls);
  25000. // No route at all
  25001. res = get("/none");
  25002. ASSERT_TRUE(res);
  25003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25004. EXPECT_EQ(1, pre_routing_calls);
  25005. // Answered by the pre-routing handler
  25006. res = get("/handled");
  25007. ASSERT_TRUE(res);
  25008. EXPECT_EQ(StatusCode::OK_200, res->status);
  25009. EXPECT_EQ("handled", res->body);
  25010. EXPECT_EQ(1, pre_routing_calls);
  25011. // A WebSocket route
  25012. pre_routing_calls = 0;
  25013. pre_request_calls = 0;
  25014. {
  25015. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25016. "/ws");
  25017. ASSERT_TRUE(client.connect());
  25018. std::string msg;
  25019. ASSERT_TRUE(client.read(msg));
  25020. EXPECT_EQ("ws", msg);
  25021. client.close();
  25022. }
  25023. EXPECT_EQ(1, pre_routing_calls);
  25024. EXPECT_EQ(1, pre_request_calls);
  25025. }
  25026. // An upgrade request answered by a hook leaves its body unread, so that body
  25027. // must not be served as the next request on the connection.
  25028. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25029. Server svr;
  25030. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25031. if (req.path == "/pre-routing") {
  25032. res.set_content("pre-routing", "text/plain");
  25033. return Server::HandlerResponse::Handled;
  25034. }
  25035. return Server::HandlerResponse::Unhandled;
  25036. });
  25037. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25038. if (req.matched_route == "/pre-request") {
  25039. res.set_content("pre-request", "text/plain");
  25040. return Server::HandlerResponse::Handled;
  25041. }
  25042. return Server::HandlerResponse::Unhandled;
  25043. });
  25044. svr.Get("/smuggled", [](const Request &, Response &res) {
  25045. res.set_content("smuggled", "text/plain");
  25046. });
  25047. svr.WebSocket("/pre-request",
  25048. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25049. auto port = svr.bind_to_any_port(HOST);
  25050. std::thread t([&]() { svr.listen_after_bind(); });
  25051. auto se = detail::scope_exit([&] {
  25052. svr.stop();
  25053. t.join();
  25054. });
  25055. svr.wait_until_ready();
  25056. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25057. for (auto path : {"/pre-routing", "/pre-request"}) {
  25058. std::string req = std::string("GET ") + path +
  25059. " HTTP/1.1\r\n"
  25060. "Host: localhost\r\n"
  25061. "Upgrade: websocket\r\n"
  25062. "Connection: Upgrade\r\n"
  25063. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25064. "Sec-WebSocket-Version: 13\r\n"
  25065. "Content-Length: " +
  25066. std::to_string(body.size()) + "\r\n\r\n" + body;
  25067. std::string res;
  25068. ASSERT_TRUE(send_request(5, req, &res, port));
  25069. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25070. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25071. // Only one response, and the body was not served as a request
  25072. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25073. }
  25074. }
  25075. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25076. Server svr;
  25077. std::atomic<int> pre_request_calls{0};
  25078. std::atomic<bool> route_matched{false};
  25079. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25080. pre_request_calls++;
  25081. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25082. if (req.get_header_value("Authorization") != "Bearer token123") {
  25083. res.status = StatusCode::Unauthorized_401;
  25084. res.set_content("Unauthorized", "text/plain");
  25085. return Server::HandlerResponse::Handled;
  25086. }
  25087. return Server::HandlerResponse::Unhandled;
  25088. });
  25089. std::atomic<bool> handler_called{false};
  25090. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25091. handler_called = true;
  25092. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25093. });
  25094. auto port = svr.bind_to_any_port("localhost");
  25095. std::thread t([&]() { svr.listen_after_bind(); });
  25096. svr.wait_until_ready();
  25097. // Without Authorization header - should be rejected before upgrade
  25098. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25099. "/ws/1");
  25100. EXPECT_FALSE(client1.connect());
  25101. EXPECT_FALSE(handler_called);
  25102. EXPECT_EQ(1, pre_request_calls);
  25103. EXPECT_TRUE(route_matched);
  25104. // The rejection is an ordinary HTTP response, not a protocol switch
  25105. {
  25106. Client cli("localhost", port);
  25107. Headers headers = {{"Upgrade", "websocket"},
  25108. {"Connection", "Upgrade"},
  25109. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25110. {"Sec-WebSocket-Version", "13"}};
  25111. auto res = cli.Get("/ws/1", headers);
  25112. ASSERT_TRUE(res);
  25113. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25114. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25115. EXPECT_EQ("Unauthorized", res->body);
  25116. }
  25117. EXPECT_FALSE(handler_called);
  25118. // With Authorization header - should succeed
  25119. Headers headers = {{"Authorization", "Bearer token123"}};
  25120. ws::WebSocketClient client2(
  25121. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25122. ASSERT_TRUE(client2.connect());
  25123. std::string msg;
  25124. ASSERT_TRUE(client2.read(msg));
  25125. EXPECT_EQ("/ws/:id 2", msg);
  25126. EXPECT_TRUE(handler_called);
  25127. client2.close();
  25128. svr.stop();
  25129. t.join();
  25130. }
  25131. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25132. static Headers websocket_upgrade_headers() {
  25133. return {{"Upgrade", "websocket"},
  25134. {"Connection", "Upgrade"},
  25135. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25136. {"Sec-WebSocket-Version", "13"},
  25137. {"Sec-WebSocket-Protocol", "chat"}};
  25138. }
  25139. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25140. Server svr;
  25141. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25142. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25143. return Server::HandlerResponse::Unhandled;
  25144. });
  25145. svr.set_pre_request_handler([](const Request &req, Response &) {
  25146. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25147. return Server::HandlerResponse::Unhandled;
  25148. });
  25149. svr.set_exception_handler(
  25150. [](const Request &, Response &res, std::exception_ptr ep) {
  25151. try {
  25152. std::rethrow_exception(ep);
  25153. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25154. });
  25155. auto handler = [](const Request &, ws::WebSocket &) {};
  25156. svr.WebSocket("/pre-routing", handler);
  25157. svr.WebSocket("/pre-request", handler);
  25158. svr.WebSocket("/sub-protocol", handler,
  25159. [](const std::vector<std::string> &) -> std::string {
  25160. throw std::runtime_error("/sub-protocol");
  25161. });
  25162. auto port = svr.bind_to_any_port(HOST);
  25163. ASSERT_GT(port, 0);
  25164. thread t = thread([&] { svr.listen_after_bind(); });
  25165. auto se = detail::scope_exit([&] {
  25166. svr.stop();
  25167. t.join();
  25168. ASSERT_FALSE(svr.is_running());
  25169. });
  25170. svr.wait_until_ready();
  25171. Client cli(HOST, port);
  25172. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25173. auto res = cli.Get(path, websocket_upgrade_headers());
  25174. if (!res) {
  25175. ADD_FAILURE() << path << ": " << to_string(res.error());
  25176. continue;
  25177. }
  25178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25179. EXPECT_EQ(path, res->body);
  25180. }
  25181. }
  25182. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25183. Server svr;
  25184. svr.set_pre_routing_handler(
  25185. [](const Request &, Response &) -> Server::HandlerResponse {
  25186. throw std::runtime_error("pre-routing");
  25187. });
  25188. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25189. auto port = svr.bind_to_any_port(HOST);
  25190. ASSERT_GT(port, 0);
  25191. thread t = thread([&] { svr.listen_after_bind(); });
  25192. auto se = detail::scope_exit([&] {
  25193. svr.stop();
  25194. t.join();
  25195. ASSERT_FALSE(svr.is_running());
  25196. });
  25197. svr.wait_until_ready();
  25198. Client cli(HOST, port);
  25199. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25200. ASSERT_TRUE(res) << to_string(res.error());
  25201. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25202. }
  25203. #endif
  25204. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25205. Server svr;
  25206. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25207. // A read timeout is how a handler gets control back. Without it, a handler
  25208. // parked in read() can never write on the connection it is reading.
  25209. ws.set_read_timeout(std::chrono::milliseconds(100));
  25210. std::string msg;
  25211. while (ws.is_open()) {
  25212. auto r = ws.read(msg);
  25213. if (r == httplib::ws::Timeout) {
  25214. ws.send("tick");
  25215. continue;
  25216. }
  25217. if (r == httplib::ws::Fail) { break; }
  25218. ws.send(msg);
  25219. }
  25220. });
  25221. auto port = svr.bind_to_any_port("localhost");
  25222. std::thread t([&]() { svr.listen_after_bind(); });
  25223. svr.wait_until_ready();
  25224. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25225. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25226. ASSERT_TRUE(client.connect());
  25227. // The client sends nothing, so anything it receives came out of the
  25228. // handler's timeout path.
  25229. std::string msg;
  25230. ASSERT_EQ(client.read(msg), ws::Text);
  25231. EXPECT_EQ("tick", msg);
  25232. client.close();
  25233. svr.stop();
  25234. t.join();
  25235. }
  25236. // Stream::read may return fewer bytes than asked for. This is that contract at
  25237. // its worst -- one byte per call -- which is what a frame header straddling a
  25238. // read buffer's boundary looks like to the frame parser.
  25239. class WsByteAtATimeStream : public Stream {
  25240. public:
  25241. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25242. bool is_readable() const override { return true; }
  25243. bool wait_readable() const override { return true; }
  25244. bool wait_writable() const override { return true; }
  25245. ssize_t read(char *ptr, size_t size) override {
  25246. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25247. *ptr = data_[pos_++];
  25248. return 1;
  25249. }
  25250. ssize_t write(const char *, size_t size) override {
  25251. return static_cast<ssize_t>(size);
  25252. }
  25253. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25254. ip = "127.0.0.1";
  25255. port = 0;
  25256. }
  25257. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25258. ip = "127.0.0.1";
  25259. port = 0;
  25260. }
  25261. socket_t socket() const override { return INVALID_SOCKET; }
  25262. time_t duration() const override { return 0; }
  25263. private:
  25264. std::string data_;
  25265. size_t pos_ = 0;
  25266. };
  25267. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25268. // The payload uses the 16-bit extended length, so the header, the length
  25269. // and the mask key are all multi-byte fields here. Each used to be read
  25270. // with a single read() call, which fails as soon as one is split. The
  25271. // payload is also a little over one read chunk, so it is read in two.
  25272. std::string body;
  25273. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25274. body += static_cast<char>(i % 251);
  25275. }
  25276. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25277. std::string frame;
  25278. frame += static_cast<char>(0x81); // FIN + Text
  25279. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25280. frame += static_cast<char>(body.size() >> 8);
  25281. frame += static_cast<char>(body.size() & 0xff);
  25282. for (size_t i = 0; i < 4; i++) {
  25283. frame += static_cast<char>(mask[i]);
  25284. }
  25285. for (size_t i = 0; i < body.size(); i++) {
  25286. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25287. }
  25288. WsByteAtATimeStream strm(frame);
  25289. ws::Opcode opcode;
  25290. std::string payload;
  25291. bool fin = false;
  25292. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25293. /*expect_masked=*/true, body.size()),
  25294. ws::impl::FrameRead::Ok);
  25295. EXPECT_TRUE(fin);
  25296. EXPECT_EQ(opcode, ws::Opcode::Text);
  25297. EXPECT_EQ(payload, body);
  25298. }
  25299. // Keeps what is written, counting the writes, and reads it back.
  25300. class WsWriteCountingStream : public Stream {
  25301. public:
  25302. bool is_readable() const override { return true; }
  25303. bool wait_readable() const override { return true; }
  25304. bool wait_writable() const override { return true; }
  25305. ssize_t read(char *ptr, size_t size) override {
  25306. auto n = (std::min)(size, data_.size() - pos_);
  25307. if (n == 0) { return 0; }
  25308. memcpy(ptr, data_.data() + pos_, n);
  25309. pos_ += n;
  25310. return static_cast<ssize_t>(n);
  25311. }
  25312. ssize_t write(const char *ptr, size_t size) override {
  25313. writes++;
  25314. data_.append(ptr, size);
  25315. return static_cast<ssize_t>(size);
  25316. }
  25317. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25318. ip = "127.0.0.1";
  25319. port = 0;
  25320. }
  25321. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25322. ip = "127.0.0.1";
  25323. port = 0;
  25324. }
  25325. socket_t socket() const override { return INVALID_SOCKET; }
  25326. time_t duration() const override { return 0; }
  25327. int writes = 0;
  25328. private:
  25329. std::string data_;
  25330. size_t pos_ = 0;
  25331. };
  25332. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25333. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25334. // masked and not, reads back as written; a payload over one chunk follows
  25335. // its first in more writes.
  25336. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25337. for (auto mask : {false, true}) {
  25338. std::string body(len, '\0');
  25339. for (size_t i = 0; i < len; i++) {
  25340. body[i] = static_cast<char>(i % 251);
  25341. }
  25342. WsWriteCountingStream strm;
  25343. ASSERT_TRUE(detail::write_websocket_frame(
  25344. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25345. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25346. ws::Opcode opcode;
  25347. std::string payload;
  25348. bool fin = false;
  25349. ASSERT_EQ(
  25350. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25351. ws::impl::FrameRead::Ok)
  25352. << len << " " << mask;
  25353. EXPECT_TRUE(fin);
  25354. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25355. EXPECT_EQ(body, payload) << len << " " << mask;
  25356. }
  25357. }
  25358. }
  25359. // Hands out its pieces one read at a time, timing out between each two.
  25360. class WsTimeoutBetweenPiecesStream : public Stream {
  25361. public:
  25362. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25363. : pieces_(std::move(pieces)) {}
  25364. bool is_readable() const override { return true; }
  25365. bool wait_readable() const override { return true; }
  25366. bool wait_writable() const override { return true; }
  25367. ssize_t read(char *ptr, size_t size) override {
  25368. if (time_out_) {
  25369. time_out_ = false;
  25370. error_ = Error::Timeout;
  25371. return -1;
  25372. }
  25373. if (i_ >= pieces_.size()) {
  25374. error_ = Error::ConnectionClosed;
  25375. return 0;
  25376. }
  25377. auto &piece = pieces_[i_];
  25378. auto n = (std::min)(size, piece.size() - at_);
  25379. memcpy(ptr, piece.data() + at_, n);
  25380. at_ += n;
  25381. if (at_ == piece.size()) {
  25382. i_++;
  25383. at_ = 0;
  25384. time_out_ = true;
  25385. }
  25386. return static_cast<ssize_t>(n);
  25387. }
  25388. ssize_t write(const char *, size_t size) override {
  25389. return static_cast<ssize_t>(size);
  25390. }
  25391. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25392. ip = "127.0.0.1";
  25393. port = 0;
  25394. }
  25395. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25396. ip = "127.0.0.1";
  25397. port = 0;
  25398. }
  25399. socket_t socket() const override { return INVALID_SOCKET; }
  25400. time_t duration() const override { return 0; }
  25401. private:
  25402. std::vector<std::string> pieces_;
  25403. size_t i_ = 0;
  25404. size_t at_ = 0;
  25405. bool time_out_ = false;
  25406. };
  25407. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25408. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25409. std::string frame = "\x81\x85";
  25410. frame.append(4, '\0');
  25411. frame += "Hello";
  25412. // The header's first byte, then its second with half the mask key, then
  25413. // the rest
  25414. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25415. frame.substr(4)};
  25416. WsTimeoutBetweenPiecesStream strm(pieces);
  25417. ws::impl::FrameReader reader;
  25418. ws::Opcode opcode;
  25419. std::string payload;
  25420. bool fin = false;
  25421. for (int i = 0; i < 2; i++) {
  25422. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25423. reader.read(strm, opcode, payload, fin, true, 0));
  25424. EXPECT_TRUE(reader.begun());
  25425. }
  25426. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25427. reader.read(strm, opcode, payload, fin, true, 0));
  25428. EXPECT_FALSE(reader.begun());
  25429. EXPECT_TRUE(fin);
  25430. EXPECT_EQ(ws::Opcode::Text, opcode);
  25431. EXPECT_EQ("Hello", payload);
  25432. // Read in one go, the frame cannot be gone on with after a timeout
  25433. WsTimeoutBetweenPiecesStream again(pieces);
  25434. EXPECT_EQ(
  25435. ws::impl::FrameRead::Fail,
  25436. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25437. }
  25438. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25439. std::string body(2000, 'x');
  25440. std::string frame;
  25441. frame += static_cast<char>(0x82); // FIN + Binary
  25442. frame += static_cast<char>(126); // 16-bit length follows
  25443. frame += static_cast<char>(body.size() >> 8);
  25444. frame += static_cast<char>(body.size() & 0xff);
  25445. frame += body;
  25446. detail::BufferStream strm;
  25447. strm.write(frame.data(), frame.size());
  25448. ws::Opcode opcode;
  25449. std::string payload;
  25450. bool fin;
  25451. EXPECT_EQ(
  25452. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25453. ws::impl::FrameRead::Ok);
  25454. EXPECT_EQ(body, payload);
  25455. }
  25456. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25457. // The header announces the largest payload allowed, and only 3 bytes of it
  25458. // ever arrive.
  25459. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25460. std::string frame;
  25461. frame += static_cast<char>(0x82); // FIN + Binary
  25462. frame += static_cast<char>(127); // 64-bit length follows
  25463. for (int shift = 56; shift >= 0; shift -= 8) {
  25464. frame += static_cast<char>((len >> shift) & 0xff);
  25465. }
  25466. frame += "abc";
  25467. detail::BufferStream strm;
  25468. strm.write(frame.data(), frame.size());
  25469. ws::Opcode opcode;
  25470. std::string payload;
  25471. bool fin;
  25472. EXPECT_EQ(
  25473. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25474. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25475. ws::impl::FrameRead::Fail);
  25476. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25477. }
  25478. TEST(WebSocketTest, QueryStringInHandshake) {
  25479. Server svr;
  25480. std::mutex mtx;
  25481. std::string received_target;
  25482. std::string received_token;
  25483. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25484. {
  25485. std::lock_guard<std::mutex> lock(mtx);
  25486. received_target = req.target;
  25487. if (req.has_param("token")) {
  25488. received_token = req.get_param_value("token");
  25489. }
  25490. }
  25491. std::string msg;
  25492. while (ws.read(msg)) {
  25493. ws.send(msg);
  25494. }
  25495. });
  25496. auto port = svr.bind_to_any_port("localhost");
  25497. std::thread t([&]() { svr.listen_after_bind(); });
  25498. svr.wait_until_ready();
  25499. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25500. "/ws?token=ABC&session=123");
  25501. ASSERT_TRUE(client.connect());
  25502. // Round-trip ensures the handler has run and captured the request.
  25503. ASSERT_TRUE(client.send("hello"));
  25504. std::string msg;
  25505. ASSERT_TRUE(client.read(msg));
  25506. EXPECT_EQ("hello", msg);
  25507. client.close();
  25508. {
  25509. std::lock_guard<std::mutex> lock(mtx);
  25510. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25511. EXPECT_EQ("ABC", received_token);
  25512. }
  25513. svr.stop();
  25514. t.join();
  25515. }
  25516. // Run a handshake against a throwaway server and hand the request the server
  25517. // received back to the caller, so tests can assert on the headers the client
  25518. // actually put on the wire.
  25519. static void capture_websocket_handshake_request(
  25520. const Headers &client_headers,
  25521. std::function<void(const Request &, int port)> verify) {
  25522. Server svr;
  25523. std::mutex mtx;
  25524. Request received;
  25525. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25526. {
  25527. std::lock_guard<std::mutex> lock(mtx);
  25528. received = req;
  25529. }
  25530. std::string msg;
  25531. while (ws.read(msg)) {
  25532. ws.send(msg);
  25533. }
  25534. });
  25535. auto port = svr.bind_to_any_port("localhost");
  25536. std::thread t([&]() { svr.listen_after_bind(); });
  25537. auto se = detail::scope_exit([&] {
  25538. svr.stop();
  25539. t.join();
  25540. });
  25541. svr.wait_until_ready();
  25542. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25543. client_headers);
  25544. ASSERT_TRUE(client.connect());
  25545. ASSERT_TRUE(client.send("hello"));
  25546. std::string msg;
  25547. ASSERT_TRUE(client.read(msg));
  25548. client.close();
  25549. {
  25550. std::lock_guard<std::mutex> lock(mtx);
  25551. verify(received, port);
  25552. }
  25553. }
  25554. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25555. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25556. // Non-default port must be present in the Host header. Default ports
  25557. // (80/443) are omitted; that logic is covered by
  25558. // MakeHostAndPortStringTest.
  25559. EXPECT_EQ("localhost:" + std::to_string(port),
  25560. req.get_header_value("Host"));
  25561. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25562. req.get_header_value("User-Agent"));
  25563. EXPECT_FALSE(req.has_header("Accept"));
  25564. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25565. EXPECT_FALSE(req.has_header("Content-Length"));
  25566. });
  25567. }
  25568. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25569. capture_websocket_handshake_request(
  25570. {{"Host", "example.com"},
  25571. {"User-Agent", "custom-agent"},
  25572. {"X-Custom", "value"}},
  25573. [](const Request &req, int) {
  25574. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25575. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25576. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25577. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25578. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25579. });
  25580. }
  25581. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25582. capture_websocket_handshake_request(
  25583. {{"Upgrade", "bogus"},
  25584. {"Connection", "close"},
  25585. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25586. {"Sec-WebSocket-Version", "8"}},
  25587. [](const Request &req, int) {
  25588. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25589. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25590. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25591. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25592. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25593. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25594. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25595. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25596. req.get_header_value("Sec-WebSocket-Key"));
  25597. });
  25598. }
  25599. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25600. // A header the client refuses to send must abort the handshake before any
  25601. // part of it reaches the wire; a lone request line would otherwise sit in
  25602. // the peer's buffer as a truncated request.
  25603. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25604. ASSERT_NE(INVALID_SOCKET, srv);
  25605. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25606. sockaddr_in addr{};
  25607. addr.sin_family = AF_INET;
  25608. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25609. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25610. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25611. ASSERT_EQ(0, ::listen(srv, 1));
  25612. sockaddr_in bound{};
  25613. socklen_t bound_len = sizeof(bound);
  25614. ASSERT_EQ(
  25615. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25616. auto port = ntohs(bound.sin_port);
  25617. ssize_t received = -1;
  25618. std::thread t([&] {
  25619. // Bound every blocking call so a regression fails the test with a bad
  25620. // value instead of hanging the suite.
  25621. fd_set rfds;
  25622. FD_ZERO(&rfds);
  25623. FD_SET(srv, &rfds);
  25624. timeval tv{5, 0};
  25625. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25626. 0) {
  25627. return;
  25628. }
  25629. sockaddr_in cli_addr{};
  25630. socklen_t cli_len = sizeof(cli_addr);
  25631. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25632. if (cli == INVALID_SOCKET) { return; }
  25633. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25634. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25635. char buf[4096];
  25636. received = ::recv(cli, buf, sizeof(buf), 0);
  25637. });
  25638. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25639. // connect() has already shut the socket down by the time it returns false,
  25640. // so the peer sees EOF without waiting for the client to be destroyed.
  25641. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25642. {{"X-Bad", "a\r\nInjected: 1"}});
  25643. EXPECT_FALSE(client.connect());
  25644. t.join();
  25645. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25646. EXPECT_EQ(0, received);
  25647. }
  25648. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25649. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25650. // contains "upgrade" as a substring is a different token and must not
  25651. // start a WebSocket handshake.
  25652. auto make_request = [](const std::vector<std::string> &connection_values) {
  25653. Request req;
  25654. req.method = "GET";
  25655. req.headers.emplace("Upgrade", "websocket");
  25656. for (const auto &value : connection_values) {
  25657. req.headers.emplace("Connection", value);
  25658. }
  25659. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25660. req.headers.emplace("Sec-WebSocket-Version", "13");
  25661. return req;
  25662. };
  25663. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25664. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25665. EXPECT_TRUE(
  25666. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25667. EXPECT_TRUE(
  25668. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25669. EXPECT_TRUE(
  25670. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25671. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25672. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25673. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25674. EXPECT_FALSE(
  25675. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25676. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25677. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25678. }
  25679. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25680. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25681. // asks recipients to match each protocol-name case-insensitively, and RFC
  25682. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25683. // client naming websocket alongside another protocol, or on a second field
  25684. // line, is offering websocket; a value that merely contains "websocket" as a
  25685. // substring is a different protocol name and is not.
  25686. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25687. Request req;
  25688. req.method = "GET";
  25689. for (const auto &value : upgrade_values) {
  25690. req.headers.emplace("Upgrade", value);
  25691. }
  25692. req.headers.emplace("Connection", "Upgrade");
  25693. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25694. req.headers.emplace("Sec-WebSocket-Version", "13");
  25695. return req;
  25696. };
  25697. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25698. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25699. EXPECT_TRUE(
  25700. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25701. EXPECT_TRUE(
  25702. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25703. EXPECT_TRUE(
  25704. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25705. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25706. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25707. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25708. EXPECT_FALSE(
  25709. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25710. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25711. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25712. }
  25713. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25714. Server svr;
  25715. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25716. auto port = svr.bind_to_any_port("localhost");
  25717. std::thread t([&]() { svr.listen_after_bind(); });
  25718. auto se = detail::scope_exit([&] {
  25719. svr.stop();
  25720. t.join();
  25721. });
  25722. svr.wait_until_ready();
  25723. Headers headers = {{"Upgrade", "websocket"},
  25724. {"Connection", "notupgrade"},
  25725. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25726. {"Sec-WebSocket-Version", "13"}};
  25727. Client cli("localhost", port);
  25728. auto res = cli.Get("/ws", headers);
  25729. // The route exists only as a WebSocket route, so a request that fails the
  25730. // handshake check falls through to ordinary routing.
  25731. ASSERT_TRUE(res);
  25732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25733. }
  25734. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25735. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25736. // Connection value is the only thing left for the client to reject.
  25737. Server svr;
  25738. svr.Get("/ws", [](const Request &req, Response &res) {
  25739. res.status = StatusCode::SwitchingProtocol_101;
  25740. res.set_header("Upgrade", "websocket");
  25741. res.set_header("Connection", "notupgrade");
  25742. res.set_header("Sec-WebSocket-Accept",
  25743. detail::websocket_accept_key(
  25744. req.get_header_value("Sec-WebSocket-Key")));
  25745. });
  25746. auto port = svr.bind_to_any_port("localhost");
  25747. std::thread t([&]() { svr.listen_after_bind(); });
  25748. auto se = detail::scope_exit([&] {
  25749. svr.stop();
  25750. t.join();
  25751. });
  25752. svr.wait_until_ready();
  25753. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25754. auto res = client.connect();
  25755. EXPECT_FALSE(res);
  25756. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25757. EXPECT_FALSE(client.is_open());
  25758. }
  25759. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25760. Server svr;
  25761. svr.Get("/ws", [](const Request &req, Response &res) {
  25762. res.status = StatusCode::SwitchingProtocol_101;
  25763. res.set_header("Upgrade", "websocket");
  25764. res.set_header("Connection", "Upgrade");
  25765. res.set_header("Sec-WebSocket-Accept",
  25766. detail::websocket_accept_key(
  25767. req.get_header_value("Sec-WebSocket-Key")));
  25768. res.set_header("Sec-WebSocket-Protocol", "admin");
  25769. });
  25770. auto port = svr.bind_to_any_port("localhost");
  25771. std::thread t([&]() { svr.listen_after_bind(); });
  25772. auto se = detail::scope_exit([&] {
  25773. svr.stop();
  25774. t.join();
  25775. });
  25776. svr.wait_until_ready();
  25777. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25778. // Server selects a subprotocol the client never offered
  25779. {
  25780. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25781. ws::WebSocketClient client(url, headers);
  25782. auto res = client.connect();
  25783. EXPECT_FALSE(res);
  25784. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25785. EXPECT_FALSE(client.is_open());
  25786. EXPECT_TRUE(client.subprotocol().empty());
  25787. }
  25788. // Client offered none but the server named one anyway
  25789. {
  25790. ws::WebSocketClient client(url);
  25791. auto res = client.connect();
  25792. EXPECT_FALSE(res);
  25793. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25794. EXPECT_FALSE(client.is_open());
  25795. EXPECT_TRUE(client.subprotocol().empty());
  25796. }
  25797. }
  25798. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25799. // The socket path doubles as the URL host, so it must not contain '/'.
  25800. const char *shard = getenv("GTEST_SHARD_INDEX");
  25801. const std::string sock_path =
  25802. shard ? std::string("httplib-ws-") + shard + ".sock"
  25803. : std::string("httplib-ws.sock");
  25804. std::remove(sock_path.c_str());
  25805. Server svr;
  25806. std::mutex mtx;
  25807. std::string received_host;
  25808. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25809. {
  25810. std::lock_guard<std::mutex> lock(mtx);
  25811. received_host = req.get_header_value("Host");
  25812. }
  25813. std::string msg;
  25814. while (ws.read(msg)) {
  25815. ws.send(msg);
  25816. }
  25817. });
  25818. svr.set_address_family(AF_UNIX);
  25819. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25820. auto se = detail::scope_exit([&] {
  25821. svr.stop();
  25822. t.join();
  25823. std::remove(sock_path.c_str());
  25824. });
  25825. svr.wait_until_ready();
  25826. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25827. client.set_address_family(AF_UNIX);
  25828. ASSERT_TRUE(client.connect());
  25829. ASSERT_TRUE(client.send("hello"));
  25830. std::string msg;
  25831. ASSERT_TRUE(client.read(msg));
  25832. client.close();
  25833. {
  25834. std::lock_guard<std::mutex> lock(mtx);
  25835. // There is no host:port for a Unix socket, so the same "localhost"
  25836. // placeholder the HTTP client uses is expected.
  25837. EXPECT_EQ("localhost", received_host);
  25838. }
  25839. }
  25840. // Two threads must never parse WebSocket frames from the same stream.
  25841. // close() used to read the peer's Close reply with its own frame read, so it
  25842. // raced a reader thread that was in the middle of a payload: the payload loop
  25843. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25844. // so bytes taken by close() were replaced with bytes from further along the
  25845. // stream. The message kept its length and silently changed content.
  25846. //
  25847. // The raw peer below sends a frame header plus part of the payload, waits for
  25848. // the handler to call close(), and only then sends the rest. Whichever thread
  25849. // would win the race for those bytes, the message must arrive intact, because
  25850. // close() must not touch the stream while read() owns it.
  25851. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25852. #ifndef _WIN32
  25853. signal(SIGPIPE, SIG_IGN);
  25854. #endif
  25855. const size_t payload_len = 120; // fits the 7-bit length field
  25856. const size_t prefix_len = 8;
  25857. const int attempts = 8;
  25858. std::string expected(payload_len, '\0');
  25859. for (size_t i = 0; i < payload_len; i++) {
  25860. expected[i] = static_cast<char>('a' + i % 26);
  25861. }
  25862. std::atomic<bool> peer_stalled{false};
  25863. std::atomic<bool> handler_done{false};
  25864. std::mutex received_mutex;
  25865. std::vector<std::string> received;
  25866. // Bound every wait, so a regression fails the test instead of hanging the
  25867. // suite.
  25868. auto wait_for = [](const std::atomic<bool> &flag) {
  25869. for (int i = 0; i < 500 && !flag; i++) {
  25870. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25871. }
  25872. };
  25873. Server svr;
  25874. svr.set_websocket_ping_interval(0);
  25875. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25876. std::thread reader([&]() {
  25877. std::string msg;
  25878. while (ws.read(msg)) {
  25879. std::lock_guard<std::mutex> guard(received_mutex);
  25880. received.push_back(msg);
  25881. }
  25882. });
  25883. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25884. // inside a frame when close() runs.
  25885. wait_for(peer_stalled);
  25886. ws.close();
  25887. reader.join();
  25888. handler_done = true;
  25889. });
  25890. auto port = svr.bind_to_any_port("127.0.0.1");
  25891. std::thread t([&]() { svr.listen_after_bind(); });
  25892. auto se = detail::scope_exit([&] {
  25893. svr.stop();
  25894. t.join();
  25895. });
  25896. svr.wait_until_ready();
  25897. auto send_bytes = [](socket_t s, const std::string &data) {
  25898. #ifdef _WIN32
  25899. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25900. #else
  25901. auto n = ::send(s, data.data(), data.size(), 0);
  25902. #endif
  25903. return n == static_cast<decltype(n)>(data.size());
  25904. };
  25905. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25906. // Every length used here fits the 7-bit length field.
  25907. auto masked_header = [](uint8_t first_byte, size_t len) {
  25908. std::string h;
  25909. h += static_cast<char>(first_byte);
  25910. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25911. h.append(4, '\0'); // mask key
  25912. return h;
  25913. };
  25914. for (int attempt = 0; attempt < attempts; attempt++) {
  25915. peer_stalled = false;
  25916. handler_done = false;
  25917. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25918. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25919. auto se_sock = detail::scope_exit([&] {
  25920. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25921. });
  25922. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25923. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25924. sockaddr_in addr{};
  25925. addr.sin_family = AF_INET;
  25926. addr.sin_port = htons(static_cast<uint16_t>(port));
  25927. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25928. ASSERT_EQ(
  25929. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25930. << "attempt " << attempt;
  25931. ASSERT_TRUE(send_bytes(sock,
  25932. "GET /ws HTTP/1.1\r\n"
  25933. "Host: 127.0.0.1\r\n"
  25934. "Upgrade: websocket\r\n"
  25935. "Connection: Upgrade\r\n"
  25936. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25937. "Sec-WebSocket-Version: 13\r\n"
  25938. "\r\n"))
  25939. << "attempt " << attempt;
  25940. std::string response;
  25941. while (response.find("\r\n\r\n") == std::string::npos) {
  25942. char buf[512];
  25943. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25944. if (n <= 0) { break; }
  25945. response.append(buf, static_cast<size_t>(n));
  25946. }
  25947. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25948. << "attempt " << attempt;
  25949. // Send the header of a Binary message but only the first prefix_len bytes
  25950. // of its payload, leaving the reader thread stalled inside the payload.
  25951. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25952. expected.substr(0, prefix_len)))
  25953. << "attempt " << attempt;
  25954. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25955. peer_stalled = true;
  25956. // Let close() send its Close frame and park in its own read before the
  25957. // rest of the payload arrives, so both threads are waiting for it.
  25958. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25959. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25960. close_frame += static_cast<char>(0x03); // status 1000
  25961. close_frame += static_cast<char>(0xE8);
  25962. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25963. << "attempt " << attempt;
  25964. // Closing the peer releases the reader thread even on the buggy path,
  25965. // where it waits for bytes another thread already consumed.
  25966. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25967. detail::close_socket(sock);
  25968. sock = INVALID_SOCKET;
  25969. wait_for(handler_done);
  25970. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25971. }
  25972. std::lock_guard<std::mutex> guard(received_mutex);
  25973. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25974. << "a message in flight when close() ran was dropped";
  25975. for (size_t i = 0; i < received.size(); i++) {
  25976. EXPECT_EQ(expected, received[i]) << "message " << i;
  25977. }
  25978. }
  25979. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25980. // returning the socket, or INVALID_SOCKET.
  25981. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25982. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25983. if (sock == INVALID_SOCKET) { return sock; }
  25984. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25985. sockaddr_in addr{};
  25986. addr.sin_family = AF_INET;
  25987. addr.sin_port = htons(static_cast<uint16_t>(port));
  25988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25989. std::string req = "GET " + path +
  25990. " HTTP/1.1\r\n"
  25991. "Host: 127.0.0.1\r\n"
  25992. "Upgrade: websocket\r\n"
  25993. "Connection: Upgrade\r\n"
  25994. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25995. "Sec-WebSocket-Version: 13\r\n"
  25996. "\r\n";
  25997. std::string res;
  25998. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25999. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26000. static_cast<ssize_t>(req.size())) {
  26001. char c;
  26002. while (res.find("\r\n\r\n") == std::string::npos &&
  26003. ::recv(sock, &c, 1, 0) == 1) {
  26004. res += c;
  26005. }
  26006. }
  26007. if (res.find(" 101 ") == std::string::npos) {
  26008. detail::close_socket(sock);
  26009. return INVALID_SOCKET;
  26010. }
  26011. return sock;
  26012. }
  26013. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26014. // The payload must fit the 7-bit length field.
  26015. static std::string masked_frame(uint8_t first_byte,
  26016. const std::string &payload) {
  26017. std::string f;
  26018. f += static_cast<char>(first_byte);
  26019. f += static_cast<char>(0x80 | payload.size());
  26020. f.append(4, '\0');
  26021. return f + payload;
  26022. }
  26023. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26024. std::atomic<bool> done{false};
  26025. std::string received;
  26026. Server svr;
  26027. svr.set_websocket_ping_interval(0);
  26028. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26029. std::string msg;
  26030. if (ws.read(msg) == ws::Binary) { received = msg; }
  26031. done = true;
  26032. });
  26033. auto port = svr.bind_to_any_port("127.0.0.1");
  26034. std::thread t([&]() { svr.listen_after_bind(); });
  26035. auto se = detail::scope_exit([&] {
  26036. svr.stop();
  26037. t.join();
  26038. });
  26039. svr.wait_until_ready();
  26040. auto sock = connect_raw_websocket(port, "/ws");
  26041. ASSERT_NE(INVALID_SOCKET, sock);
  26042. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26043. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26044. masked_frame(0x89, "p") + // FIN + Ping
  26045. masked_frame(0x80, "lo"); // FIN + Continuation
  26046. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26047. for (int i = 0; i < 500 && !done; i++) {
  26048. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26049. }
  26050. ASSERT_TRUE(done);
  26051. EXPECT_EQ("Hello", received);
  26052. // The Ping between the fragments is answered with a Pong.
  26053. char pong[3];
  26054. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26055. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26056. }
  26057. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26058. #ifndef _WIN32
  26059. signal(SIGPIPE, SIG_IGN);
  26060. #endif
  26061. std::atomic<bool> read_ended{false};
  26062. std::atomic<bool> sending{true};
  26063. Server svr;
  26064. svr.set_websocket_ping_interval(0);
  26065. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26066. std::thread reader([&]() {
  26067. std::string msg;
  26068. while (ws.read(msg)) {}
  26069. read_ended = true;
  26070. });
  26071. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26072. ws.close();
  26073. reader.join();
  26074. });
  26075. auto port = svr.bind_to_any_port("127.0.0.1");
  26076. std::thread t([&]() { svr.listen_after_bind(); });
  26077. auto se = detail::scope_exit([&] {
  26078. svr.stop();
  26079. t.join();
  26080. });
  26081. svr.wait_until_ready();
  26082. auto sock = connect_raw_websocket(port, "/ws");
  26083. ASSERT_NE(INVALID_SOCKET, sock);
  26084. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26085. // A Text message whose empty continuation frames never end
  26086. std::thread sender([&]() {
  26087. auto data = masked_frame(0x01, "");
  26088. while (sending) {
  26089. data += masked_frame(0x00, "");
  26090. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26091. return;
  26092. }
  26093. data.clear();
  26094. }
  26095. });
  26096. for (int i = 0; i < 300 && !read_ended; i++) {
  26097. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26098. }
  26099. sending = false;
  26100. sender.join();
  26101. EXPECT_TRUE(read_ended);
  26102. }
  26103. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26104. Server svr;
  26105. svr.set_websocket_ping_interval(-1);
  26106. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26107. std::string msg;
  26108. while (ws.read(msg)) {}
  26109. });
  26110. auto port = svr.bind_to_any_port("127.0.0.1");
  26111. std::thread t([&]() { svr.listen_after_bind(); });
  26112. auto se = detail::scope_exit([&] {
  26113. svr.stop();
  26114. t.join();
  26115. });
  26116. svr.wait_until_ready();
  26117. auto sock = connect_raw_websocket(port, "/ws");
  26118. ASSERT_NE(INVALID_SOCKET, sock);
  26119. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26120. // Nothing comes while the client stays quiet.
  26121. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26122. char c;
  26123. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26124. }
  26125. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26126. // and that has to end a read() already waiting on the peer, on every platform.
  26127. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26128. // The peer sends no pings, and its handler never calls read(), which is
  26129. // where pongs are written.
  26130. std::mutex mutex;
  26131. std::condition_variable cv;
  26132. auto release = false;
  26133. svr.set_websocket_ping_interval(0);
  26134. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26135. std::unique_lock<std::mutex> lock(mutex);
  26136. cv.wait(lock, [&] { return release; });
  26137. });
  26138. auto port = svr.bind_to_any_port(HOST);
  26139. std::thread t([&]() { svr.listen_after_bind(); });
  26140. auto se = detail::scope_exit([&] {
  26141. {
  26142. std::lock_guard<std::mutex> lock(mutex);
  26143. release = true;
  26144. }
  26145. cv.notify_all();
  26146. svr.stop();
  26147. t.join();
  26148. });
  26149. svr.wait_until_ready();
  26150. ws::WebSocketClient client(std::string(scheme) +
  26151. "://localhost:" + std::to_string(port) + "/ws");
  26152. #ifdef CPPHTTPLIB_SSL_ENABLED
  26153. client.enable_server_certificate_verification(false);
  26154. #endif
  26155. // A ping a second, given up on after two go unanswered: about 3s
  26156. client.set_websocket_ping_interval(1);
  26157. client.set_websocket_max_missed_pongs(2);
  26158. // Well past that, so that a read the timeout ends instead stands out
  26159. client.set_read_timeout(10);
  26160. ASSERT_TRUE(client.connect());
  26161. auto start = std::chrono::steady_clock::now();
  26162. std::string msg;
  26163. EXPECT_EQ(ws::Fail, client.read(msg));
  26164. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26165. std::chrono::steady_clock::now() - start)
  26166. .count(),
  26167. 6000);
  26168. EXPECT_FALSE(client.is_open());
  26169. }
  26170. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26171. Server svr;
  26172. check_pong_timeout_ends_read(svr, "ws");
  26173. }
  26174. #ifdef CPPHTTPLIB_SSL_ENABLED
  26175. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26177. ASSERT_TRUE(svr.is_valid());
  26178. check_pong_timeout_ends_read(svr, "wss");
  26179. }
  26180. #endif
  26181. // listen() returns only after every handler has, so Server::stop() has to end
  26182. // a WebSocket handler's read() waiting on a client that stays connected and
  26183. // quiet, whether or not the handler bounded its reads, and the client's
  26184. // connection ends with it.
  26185. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26186. bool bounded) {
  26187. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26188. if (bounded) { ws.set_read_timeout(0, 50000); }
  26189. std::string msg;
  26190. while (ws.read(msg) != ws::Fail) {}
  26191. });
  26192. auto port = svr.bind_to_any_port(HOST);
  26193. std::thread t([&]() { svr.listen_after_bind(); });
  26194. auto se = detail::scope_exit([&] {
  26195. if (t.joinable()) {
  26196. svr.stop();
  26197. t.join();
  26198. }
  26199. });
  26200. svr.wait_until_ready();
  26201. ws::WebSocketClient client(std::string(scheme) +
  26202. "://localhost:" + std::to_string(port) + "/ws");
  26203. #ifdef CPPHTTPLIB_SSL_ENABLED
  26204. client.enable_server_certificate_verification(false);
  26205. #endif
  26206. client.set_read_timeout(2);
  26207. ASSERT_TRUE(client.connect());
  26208. auto stopped = std::async(std::launch::async, [&] {
  26209. svr.stop();
  26210. t.join();
  26211. });
  26212. std::string msg;
  26213. EXPECT_EQ(ws::Fail, client.read(msg));
  26214. EXPECT_FALSE(client.is_open());
  26215. auto in_time =
  26216. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26217. // A handler the stop did not reach ends when the client leaves
  26218. if (!in_time) { client.close(); }
  26219. stopped.wait();
  26220. EXPECT_TRUE(in_time);
  26221. }
  26222. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26223. Server svr;
  26224. check_stop_ends_websocket_read(svr, "ws", false);
  26225. }
  26226. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26227. Server svr;
  26228. check_stop_ends_websocket_read(svr, "ws", true);
  26229. }
  26230. #ifdef CPPHTTPLIB_SSL_ENABLED
  26231. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26233. ASSERT_TRUE(svr.is_valid());
  26234. check_stop_ends_websocket_read(svr, "wss", false);
  26235. }
  26236. #endif
  26237. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26238. // dropped connection, whether the handler waits for a message or for the rest
  26239. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26240. // time out inside the message as well, and the stop ends them too.
  26241. static void check_stop_closes_with_going_away(const std::string &sent,
  26242. bool bounded = false) {
  26243. Server svr;
  26244. svr.set_websocket_ping_interval(0);
  26245. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26246. if (bounded) { ws.set_read_timeout(0, 10000); }
  26247. std::string msg;
  26248. while (ws.read(msg) != ws::Fail) {}
  26249. });
  26250. auto port = svr.bind_to_any_port("127.0.0.1");
  26251. std::thread t([&]() { svr.listen_after_bind(); });
  26252. auto se = detail::scope_exit([&] {
  26253. svr.stop();
  26254. t.join();
  26255. });
  26256. svr.wait_until_ready();
  26257. // Closed before the join above, which a handler the stop did not reach
  26258. // would otherwise hold up.
  26259. auto sock = connect_raw_websocket(port, "/ws");
  26260. ASSERT_NE(INVALID_SOCKET, sock);
  26261. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26262. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26263. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26264. // Let the handler take what was sent and wait for more
  26265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26266. svr.stop();
  26267. // FIN + Close, its length, then the code: unmasked, from a server
  26268. std::string head;
  26269. char c;
  26270. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26271. head += c;
  26272. }
  26273. const std::string reason = "server stopping";
  26274. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26275. "\x03\xe9",
  26276. head);
  26277. }
  26278. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26279. check_stop_closes_with_going_away("");
  26280. }
  26281. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26282. // A Text frame without FIN: the first fragment of a message
  26283. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26284. }
  26285. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26286. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26287. /*bounded=*/true);
  26288. }
  26289. // A handler that bounds its reads gets control back within its timeout even
  26290. // while a message arrives in pieces, and the message whole once the last has
  26291. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26292. // sent a while after the one before, much longer than the handler's timeout.
  26293. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26294. const std::string &expected) {
  26295. std::atomic<bool> done{false};
  26296. std::string received;
  26297. std::chrono::steady_clock::duration longest{};
  26298. Server svr;
  26299. svr.set_websocket_ping_interval(0);
  26300. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26301. ws.set_read_timeout(0, 10000);
  26302. std::string msg;
  26303. ws::ReadResult r;
  26304. do {
  26305. auto began = std::chrono::steady_clock::now();
  26306. r = ws.read(msg);
  26307. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26308. } while (r == ws::Timeout);
  26309. if (r == ws::Text) { received = msg; }
  26310. done = true;
  26311. });
  26312. auto port = svr.bind_to_any_port("127.0.0.1");
  26313. std::thread t([&]() { svr.listen_after_bind(); });
  26314. auto se = detail::scope_exit([&] {
  26315. svr.stop();
  26316. t.join();
  26317. });
  26318. svr.wait_until_ready();
  26319. auto sock = connect_raw_websocket(port, "/ws");
  26320. ASSERT_NE(INVALID_SOCKET, sock);
  26321. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26322. for (const auto &piece : pieces) {
  26323. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26324. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26325. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26326. }
  26327. for (int i = 0; i < 500 && !done; i++) {
  26328. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26329. }
  26330. ASSERT_TRUE(done);
  26331. EXPECT_EQ(expected, received);
  26332. // Far under the 200 ms between the pieces, however loaded the machine
  26333. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26334. }
  26335. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26336. // The header's first byte, then its second with half the mask key, then
  26337. // the rest: what a frame written in several writes may look like when
  26338. // Nagle's algorithm holds the later ones back for an ACK.
  26339. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26340. check_bounded_read_resumes(
  26341. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26342. }
  26343. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26344. check_bounded_read_resumes(
  26345. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26346. }
  26347. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26348. Server svr;
  26349. svr.set_websocket_ping_interval(0);
  26350. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26351. std::string msg;
  26352. while (ws.read(msg)) {}
  26353. });
  26354. auto port = svr.bind_to_any_port("127.0.0.1");
  26355. std::thread t([&]() { svr.listen_after_bind(); });
  26356. auto se = detail::scope_exit([&] {
  26357. svr.stop();
  26358. t.join();
  26359. });
  26360. svr.wait_until_ready();
  26361. // Each Close payload and the reply it should get: an echo when valid, 1002
  26362. // otherwise.
  26363. std::vector<std::pair<std::string, std::string>> cases = {
  26364. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26365. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26366. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26367. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26368. };
  26369. // Also between the fragments of a message.
  26370. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26371. for (const auto &c : cases) {
  26372. auto sock = connect_raw_websocket(port, "/ws");
  26373. ASSERT_NE(INVALID_SOCKET, sock);
  26374. auto frames = prefix + masked_frame(0x88, c.first);
  26375. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26376. std::string reply;
  26377. char buf[256];
  26378. while (reply.size() < 2 + c.second.size()) {
  26379. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26380. if (n <= 0) { break; }
  26381. reply.append(buf, static_cast<size_t>(n));
  26382. }
  26383. detail::close_socket(sock);
  26384. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26385. c.second,
  26386. reply);
  26387. }
  26388. }
  26389. }
  26390. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26391. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26392. protected:
  26393. void SetUp() override {
  26394. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26395. SERVER_PRIVATE_KEY_FILE);
  26396. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26397. std::string msg;
  26398. ws::ReadResult ret;
  26399. while ((ret = ws.read(msg))) {
  26400. if (ret == ws::Binary) {
  26401. ws.send(msg.data(), msg.size());
  26402. } else {
  26403. ws.send(msg);
  26404. }
  26405. }
  26406. });
  26407. port_ = server_->bind_to_any_port(HOST);
  26408. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26409. server_->wait_until_ready();
  26410. }
  26411. void TearDown() override {
  26412. server_->stop();
  26413. if (server_thread_.joinable()) { server_thread_.join(); }
  26414. }
  26415. std::unique_ptr<SSLServer> server_;
  26416. std::thread server_thread_;
  26417. int port_ = 0;
  26418. };
  26419. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26420. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26421. {
  26422. ws::WebSocketClient client(url);
  26423. client.enable_server_certificate_verification(false);
  26424. auto calls = 0;
  26425. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26426. calls++;
  26427. return false;
  26428. });
  26429. EXPECT_FALSE(client.connect());
  26430. EXPECT_GT(calls, 0);
  26431. }
  26432. {
  26433. ws::WebSocketClient client(url);
  26434. client.enable_server_certificate_verification(false);
  26435. client.set_session_verifier([](tls::session_t) {
  26436. return SSLVerifierResponse::CertificateRejected;
  26437. });
  26438. EXPECT_FALSE(client.connect());
  26439. }
  26440. {
  26441. ws::WebSocketClient client(url);
  26442. client.enable_server_certificate_verification(false);
  26443. client.set_session_verifier([](tls::session_t) {
  26444. return SSLVerifierResponse::CertificateAccepted;
  26445. });
  26446. EXPECT_TRUE(client.connect());
  26447. }
  26448. }
  26449. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26450. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26451. "/ws-echo");
  26452. client.enable_server_certificate_verification(false);
  26453. ASSERT_TRUE(client.connect());
  26454. ASSERT_TRUE(client.is_open());
  26455. ASSERT_TRUE(client.send("Hello WSS"));
  26456. std::string msg;
  26457. EXPECT_EQ(ws::Text, client.read(msg));
  26458. EXPECT_EQ("Hello WSS", msg);
  26459. client.close();
  26460. }
  26461. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26462. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26463. "/ws-echo");
  26464. client.enable_server_certificate_verification(false);
  26465. EXPECT_TRUE(client.connect());
  26466. }
  26467. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26468. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26469. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26470. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26471. // client (without calling close() first) is the only path that runs
  26472. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26473. // bug exactly.
  26474. //
  26475. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26476. // when linked against an instrumented libssl; run under Valgrind to catch it
  26477. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26478. // suite (the freed session otherwise stalls on the close handshake) — this test
  26479. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26480. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26481. {
  26482. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26483. "/ws-echo");
  26484. client.enable_server_certificate_verification(false);
  26485. client.set_read_timeout(2, 0);
  26486. client.set_write_timeout(2, 0);
  26487. ASSERT_TRUE(client.connect());
  26488. ASSERT_TRUE(client.is_open());
  26489. ASSERT_TRUE(client.send("still open"));
  26490. // Intentionally do NOT call client.close(): leaving scope runs
  26491. // shutdown_and_close() with the WebSocket still open, which must send the
  26492. // close frame while the TLS session is still alive.
  26493. }
  26494. }
  26495. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26496. // shutdown_and_close() at the start of connect(), reproducing the same
  26497. // use-after-free within the test body rather than at scope exit. The second
  26498. // connect must succeed and echo, proving the close handshake ran over a live
  26499. // session. See the note above about memory-tool requirements.
  26500. TEST_F(WebSocketSSLIntegrationTest,
  26501. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26502. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26503. "/ws-echo");
  26504. client.enable_server_certificate_verification(false);
  26505. client.set_read_timeout(2, 0);
  26506. client.set_write_timeout(2, 0);
  26507. ASSERT_TRUE(client.connect());
  26508. ASSERT_TRUE(client.is_open());
  26509. ASSERT_TRUE(client.send("still open"));
  26510. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26511. // the still-open connection, which must not touch a freed TLS session.
  26512. ASSERT_TRUE(client.connect());
  26513. ASSERT_TRUE(client.is_open());
  26514. ASSERT_TRUE(client.send("after reconnect"));
  26515. std::string msg;
  26516. EXPECT_EQ(ws::Text, client.read(msg));
  26517. EXPECT_EQ("after reconnect", msg);
  26518. client.close();
  26519. }
  26520. #endif
  26521. #ifdef CPPHTTPLIB_SSL_ENABLED
  26522. class WebSocketSSLCATest : public ::testing::Test {
  26523. protected:
  26524. void SetUp() override {
  26525. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26526. SERVER_PRIVATE_KEY_FILE);
  26527. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26528. std::string msg;
  26529. while (ws.read(msg)) {
  26530. ws.send(msg);
  26531. }
  26532. });
  26533. port_ = server_->bind_to_any_port("127.0.0.1");
  26534. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26535. server_->wait_until_ready();
  26536. }
  26537. void TearDown() override {
  26538. server_->stop();
  26539. if (server_thread_.joinable()) { server_thread_.join(); }
  26540. }
  26541. std::string url() const {
  26542. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26543. }
  26544. std::unique_ptr<SSLServer> server_;
  26545. std::thread server_thread_;
  26546. int port_ = 0;
  26547. };
  26548. // A custom CA loaded as PEM verifies the server with full certificate
  26549. // verification enabled
  26550. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26551. ws::WebSocketClient client(url());
  26552. std::string cert;
  26553. read_file(SERVER_CERT2_FILE, cert);
  26554. client.load_ca_cert_store(cert.c_str(), cert.size());
  26555. ASSERT_TRUE(client.connect());
  26556. ASSERT_TRUE(client.send("hello"));
  26557. std::string msg;
  26558. EXPECT_EQ(ws::Text, client.read(msg));
  26559. EXPECT_EQ("hello", msg);
  26560. client.close();
  26561. }
  26562. // A custom CA that does not cover the server must fail verification (the
  26563. // custom CA is exclusive; system certs are not loaded alongside it)
  26564. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26565. ws::WebSocketClient client(url());
  26566. std::string cert;
  26567. read_file(CLIENT_CA_CERT_FILE, cert);
  26568. client.load_ca_cert_store(cert.c_str(), cert.size());
  26569. auto res = client.connect();
  26570. ASSERT_FALSE(res);
  26571. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26572. EXPECT_EQ(-1, res.status());
  26573. EXPECT_NE(0u, res.ssl_backend_error());
  26574. }
  26575. // The same CA as a file path rather than PEM in memory
  26576. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26577. ws::WebSocketClient client(url());
  26578. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26579. ASSERT_TRUE(client.connect());
  26580. ASSERT_TRUE(client.send("hello"));
  26581. std::string msg;
  26582. EXPECT_EQ(ws::Text, client.read(msg));
  26583. EXPECT_EQ("hello", msg);
  26584. client.close();
  26585. }
  26586. // ...and a CA file that does not cover the server still fails, so it is the
  26587. // path above that decides the outcome
  26588. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26589. ws::WebSocketClient client(url());
  26590. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26591. ASSERT_FALSE(client.connect());
  26592. }
  26593. // Regression test: reconnecting with a native custom CA store used to reuse
  26594. // a store handle the previous TLS context had already freed (use-after-free
  26595. // under the OpenSSL backend). The context now lives as long as the client.
  26596. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26597. ws::WebSocketClient client(url());
  26598. std::string cert;
  26599. read_file(SERVER_CERT2_FILE, cert);
  26600. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26601. ASSERT_TRUE(client.connect());
  26602. client.close();
  26603. ASSERT_TRUE(client.connect());
  26604. ASSERT_TRUE(client.send("again"));
  26605. std::string msg;
  26606. EXPECT_EQ(ws::Text, client.read(msg));
  26607. EXPECT_EQ("again", msg);
  26608. client.close();
  26609. }
  26610. // Regression test: a certificate with a trusted chain but no identity match
  26611. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26612. // verification entirely for IP hosts, so this connection succeeded there.
  26613. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26614. // chain verification while the identity check must still fail.
  26615. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26617. ASSERT_TRUE(svr.is_valid());
  26618. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26619. std::string msg;
  26620. while (ws.read(msg)) {
  26621. ws.send(msg);
  26622. }
  26623. });
  26624. auto port = svr.bind_to_any_port("127.0.0.1");
  26625. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26626. auto se = detail::scope_exit([&] {
  26627. svr.stop();
  26628. t.join();
  26629. });
  26630. svr.wait_until_ready();
  26631. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26632. "/echo");
  26633. std::string cert;
  26634. read_file(SERVER_CERT_FILE, cert);
  26635. client.load_ca_cert_store(cert.c_str(), cert.size());
  26636. ASSERT_FALSE(client.connect());
  26637. }
  26638. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26639. // SNI, so nothing binds the host name to the TLS session. These bind the
  26640. // server to "localhost" instead, the only shape that exercises the SNI and
  26641. // hostname-verification path with certificate verification left enabled.
  26642. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26643. protected:
  26644. void Start(const char *cert_file) {
  26645. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26646. SERVER_PRIVATE_KEY_FILE);
  26647. ASSERT_TRUE(server_->is_valid());
  26648. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26649. std::string msg;
  26650. while (ws.read(msg)) {
  26651. ws.send(msg);
  26652. }
  26653. });
  26654. port_ = server_->bind_to_any_port("localhost");
  26655. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26656. server_->wait_until_ready();
  26657. }
  26658. void TearDown() override {
  26659. if (server_) { server_->stop(); }
  26660. if (server_thread_.joinable()) { server_thread_.join(); }
  26661. }
  26662. std::string url() const {
  26663. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26664. }
  26665. std::unique_ptr<SSLServer> server_;
  26666. std::thread server_thread_;
  26667. int port_ = 0;
  26668. };
  26669. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26670. // out and the connection is usable
  26671. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26672. Start(SERVER_CERT2_FILE);
  26673. ws::WebSocketClient client(url());
  26674. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26675. ASSERT_TRUE(client.connect());
  26676. ASSERT_TRUE(client.send("hello"));
  26677. std::string msg;
  26678. EXPECT_EQ(ws::Text, client.read(msg));
  26679. EXPECT_EQ("hello", msg);
  26680. client.close();
  26681. }
  26682. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26683. // while the identity check must still reject "localhost"
  26684. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26685. Start(SERVER_CERT_FILE);
  26686. ws::WebSocketClient client(url());
  26687. client.set_ca_cert_path(SERVER_CERT_FILE);
  26688. auto res = client.connect();
  26689. ASSERT_FALSE(res);
  26690. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26691. EXPECT_EQ(-1, res.status());
  26692. }
  26693. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26694. // disabled: the chain is still checked, only the identity check is skipped
  26695. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26696. Start(SERVER_CERT_FILE);
  26697. ws::WebSocketClient client(url());
  26698. client.set_ca_cert_path(SERVER_CERT_FILE);
  26699. client.enable_server_hostname_verification(false);
  26700. ASSERT_TRUE(client.connect());
  26701. ASSERT_TRUE(client.send("hello"));
  26702. std::string msg;
  26703. EXPECT_EQ(ws::Text, client.read(msg));
  26704. EXPECT_EQ("hello", msg);
  26705. client.close();
  26706. }
  26707. // A CA that did not sign the server certificate fails the chain, even though
  26708. // the name would match
  26709. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26710. Start(SERVER_CERT2_FILE);
  26711. ws::WebSocketClient client(url());
  26712. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26713. ASSERT_FALSE(client.connect());
  26714. }
  26715. // With verification disabled, neither the chain nor the name is checked
  26716. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26717. Start(SERVER_CERT_FILE);
  26718. ws::WebSocketClient client(url());
  26719. client.enable_server_certificate_verification(false);
  26720. ASSERT_TRUE(client.connect());
  26721. ASSERT_TRUE(client.send("hello"));
  26722. std::string msg;
  26723. EXPECT_EQ(ws::Text, client.read(msg));
  26724. EXPECT_EQ("hello", msg);
  26725. client.close();
  26726. }
  26727. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26728. protected:
  26729. void SetUp() override {
  26730. server_ = httplib::detail::make_unique<SSLServer>(
  26731. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26732. ASSERT_TRUE(server_->is_valid());
  26733. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26734. std::string msg;
  26735. while (ws.read(msg)) {
  26736. ws.send(msg);
  26737. }
  26738. });
  26739. port_ = server_->bind_to_any_port("localhost");
  26740. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26741. server_->wait_until_ready();
  26742. }
  26743. void TearDown() override {
  26744. server_->stop();
  26745. if (server_thread_.joinable()) { server_thread_.join(); }
  26746. }
  26747. std::string url() const {
  26748. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26749. }
  26750. void ConnectWithClientCert(const std::string &client_cert_file,
  26751. const std::string &client_private_key_file,
  26752. const char *private_key_password) {
  26753. std::string cert_pem, key_pem;
  26754. read_file(client_cert_file, cert_pem);
  26755. read_file(client_private_key_file, key_pem);
  26756. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26757. key_pem.c_str(), key_pem.size(),
  26758. private_key_password};
  26759. ConnectWithPem(pem);
  26760. }
  26761. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26762. ws::WebSocketClient client(url(), pem);
  26763. ASSERT_TRUE(client.is_valid());
  26764. client.enable_server_certificate_verification(false);
  26765. ASSERT_TRUE(client.connect());
  26766. ASSERT_TRUE(client.send("hello"));
  26767. std::string msg;
  26768. EXPECT_EQ(ws::Text, client.read(msg));
  26769. EXPECT_EQ("hello", msg);
  26770. client.close();
  26771. }
  26772. std::unique_ptr<SSLServer> server_;
  26773. std::thread server_thread_;
  26774. int port_ = 0;
  26775. };
  26776. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26777. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26778. }
  26779. // Control for the tests above: the fixture's server really does require a
  26780. // client certificate, so it is the PEM the constructor installed that decides
  26781. // the outcome.
  26782. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26783. ws::WebSocketClient client(url());
  26784. ASSERT_TRUE(client.is_valid());
  26785. client.enable_server_certificate_verification(false);
  26786. EXPECT_FALSE(client.connect());
  26787. }
  26788. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26789. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26790. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26791. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26792. }
  26793. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26794. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26795. std::string cert_pem, key_pem;
  26796. read_file(CLIENT_CERT_FILE, cert_pem);
  26797. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26798. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26799. std::vector<char> key(key_pem.begin(), key_pem.end());
  26800. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26801. key.size(), nullptr};
  26802. ConnectWithPem(pem);
  26803. }
  26804. #endif
  26805. #if !defined(_WIN32)
  26806. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26807. auto secret_dir = std::string("./symlink_test_secret");
  26808. auto served_dir = std::string("./symlink_test_served");
  26809. auto secret_file = secret_dir + "/secret.txt";
  26810. auto symlink_path = served_dir + "/escape";
  26811. // Setup: create directories and files
  26812. mkdir(secret_dir.c_str(), 0755);
  26813. mkdir(served_dir.c_str(), 0755);
  26814. {
  26815. std::ofstream ofs(secret_file);
  26816. ofs << "SECRET_DATA";
  26817. }
  26818. // Create symlink using absolute path so it resolves correctly
  26819. #ifdef PATH_MAX
  26820. char abs_secret[PATH_MAX];
  26821. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26822. #else
  26823. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26824. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26825. ASSERT_NE(nullptr, abs_secret);
  26826. #endif
  26827. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26828. auto se = detail::scope_exit([&] {
  26829. unlink(symlink_path.c_str());
  26830. unlink(secret_file.c_str());
  26831. rmdir(served_dir.c_str());
  26832. rmdir(secret_dir.c_str());
  26833. });
  26834. Server svr;
  26835. svr.set_mount_point("/", served_dir);
  26836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26837. auto se2 = detail::scope_exit([&] {
  26838. svr.stop();
  26839. listen_thread.join();
  26840. });
  26841. svr.wait_until_ready();
  26842. Client cli("localhost", PORT);
  26843. // Symlink pointing outside base dir should be blocked
  26844. auto res = cli.Get("/escape/secret.txt");
  26845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26846. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26847. }
  26848. #else
  26849. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26850. auto secret_dir = std::string("junction_test_secret");
  26851. auto served_dir = std::string("junction_test_served");
  26852. auto secret_file = secret_dir + "\\secret.txt";
  26853. auto junction_path = served_dir + "\\escape";
  26854. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26855. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26856. {
  26857. std::ofstream ofs(secret_file);
  26858. ofs << "SECRET_DATA";
  26859. }
  26860. // A junction needs no privilege to create, unlike a symlink
  26861. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26862. ASSERT_EQ(0, std::system(cmd.c_str()));
  26863. auto se = detail::scope_exit([&] {
  26864. ::RemoveDirectoryA(junction_path.c_str());
  26865. std::remove(secret_file.c_str());
  26866. ::RemoveDirectoryA(served_dir.c_str());
  26867. ::RemoveDirectoryA(secret_dir.c_str());
  26868. });
  26869. Server svr;
  26870. svr.set_mount_point("/", served_dir);
  26871. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26872. auto se2 = detail::scope_exit([&] {
  26873. svr.stop();
  26874. listen_thread.join();
  26875. });
  26876. svr.wait_until_ready();
  26877. Client cli("localhost", PORT);
  26878. // Junction pointing outside base dir should be blocked
  26879. auto res = cli.Get("/escape/secret.txt");
  26880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26881. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26882. }
  26883. #endif
  26884. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26885. // "GET /smuggled" request), reads the first response, and only then sends the
  26886. // embedded request as the body. Returns how many times /smuggled ran.
  26887. //
  26888. // The body is sent AFTER receiving the first response (as in the original
  26889. // PoC) so that the stream_line_reader cannot buffer it together with the
  26890. // headers of the first request.
  26891. static int count_smuggled_requests(const std::string &outer_head,
  26892. std::string &first_response) {
  26893. Server svr;
  26894. svr.set_mount_point("/", "./www");
  26895. std::atomic<int> smuggled_count(0);
  26896. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26897. smuggled_count++;
  26898. res.set_content("oops", "text/plain");
  26899. });
  26900. svr.Post("/post", [&](const Request &req, Response &res) {
  26901. res.set_content(req.body, "text/plain");
  26902. });
  26903. auto port = svr.bind_to_any_port("localhost");
  26904. thread t = thread([&] { svr.listen_after_bind(); });
  26905. auto se = detail::scope_exit([&] {
  26906. svr.stop();
  26907. t.join();
  26908. });
  26909. svr.wait_until_ready();
  26910. auto error = Error::Success;
  26911. auto sock = detail::create_client_socket(
  26912. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26913. /*connection_timeout_sec=*/2, 0,
  26914. /*read_timeout_sec=*/2, 0,
  26915. /*write_timeout_sec=*/2, 0, std::string(), error);
  26916. EXPECT_NE(INVALID_SOCKET, sock);
  26917. if (sock == INVALID_SOCKET) { return -1; }
  26918. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26919. // The "smuggled" request will be sent as the body of the outer request
  26920. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26921. "Host: localhost\r\n"
  26922. "Connection: close\r\n"
  26923. "\r\n";
  26924. auto head = outer_head;
  26925. auto len = std::to_string(smuggled.size());
  26926. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26927. pos = head.find("{len}", pos + len.size())) {
  26928. head.replace(pos, 5, len);
  26929. }
  26930. // Step 1: Send only the outer request headers (no body yet)
  26931. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26932. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26933. // Step 2: Read the first response
  26934. char buf[4096];
  26935. for (;;) {
  26936. auto n = recv(sock, buf, sizeof(buf), 0);
  26937. if (n <= 0) break;
  26938. first_response.append(buf, static_cast<size_t>(n));
  26939. // Stop once we have a complete response (headers + body)
  26940. auto hdr_end = first_response.find("\r\n\r\n");
  26941. if (hdr_end != std::string::npos) {
  26942. // Check for Content-Length to know when the body is complete
  26943. auto cl_pos = first_response.find("Content-Length:");
  26944. if (cl_pos != std::string::npos) {
  26945. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26946. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26947. auto cl = std::stoul(
  26948. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26949. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26950. } else {
  26951. break; // No Content-Length, assume headers-only response
  26952. }
  26953. }
  26954. }
  26955. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26956. // vulnerable server the keep-alive loop reads this as a second request. The
  26957. // server may already have closed the connection, so the result is ignored.
  26958. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26959. // Half-close so that a server which drained the body sees EOF and closes,
  26960. // instead of the read below waiting for the read timeout.
  26961. #ifdef _WIN32
  26962. ::shutdown(sock, SD_SEND);
  26963. #else
  26964. ::shutdown(sock, SHUT_WR);
  26965. #endif
  26966. // Step 4: Read until the server closes the connection
  26967. for (;;) {
  26968. auto n = recv(sock, buf, sizeof(buf), 0);
  26969. if (n <= 0) break;
  26970. }
  26971. return smuggled_count.load();
  26972. }
  26973. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26974. // A GET request with Content-Length to a static file handler must have its
  26975. // body drained before the keep-alive connection is reused. Otherwise the
  26976. // unread body bytes are interpreted as the next HTTP request.
  26977. std::string first_response;
  26978. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26979. "Host: localhost\r\n"
  26980. "Content-Length: {len}\r\n"
  26981. "\r\n",
  26982. first_response));
  26983. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26984. }
  26985. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26986. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26987. // be answered with 400 and the connection closed. Treating it as "no body"
  26988. // leaves the body to be parsed as the next request.
  26989. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26990. const char *targets[] = {
  26991. "GET /file", // handler that never reads the body
  26992. "GET /not-found", // no handler matches (404)
  26993. "POST /post", // handler that reads the body
  26994. };
  26995. for (auto target : targets) {
  26996. for (auto value : values) {
  26997. std::string first_response;
  26998. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26999. " HTTP/1.1\r\n"
  27000. "Host: localhost\r\n"
  27001. "Content-Length: " +
  27002. value + "\r\n\r\n",
  27003. first_response))
  27004. << target << " with Content-Length: " << value;
  27005. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27006. << target << " with Content-Length: " << value;
  27007. }
  27008. }
  27009. }
  27010. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27011. // A 400 for an unparseable request line leaves the rest of the message
  27012. // unread, so the connection must be closed rather than reused.
  27013. std::string first_response;
  27014. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27015. "Host: localhost\r\n"
  27016. "Content-Length: {len}\r\n"
  27017. "\r\n",
  27018. first_response));
  27019. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27020. }
  27021. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27022. // Same as above for a header block that fails to parse.
  27023. std::string first_response;
  27024. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27025. "Host: localhost\r\n"
  27026. "Bad Header\r\n"
  27027. "Content-Length: {len}\r\n"
  27028. "\r\n",
  27029. first_response));
  27030. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27031. }
  27032. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27033. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27034. // server must not read another request on that connection, even when the
  27035. // request had no body to drain.
  27036. std::string first_response;
  27037. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27038. "Host: localhost\r\n"
  27039. "\r\n",
  27040. first_response));
  27041. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27042. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27043. }
  27044. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27045. // A content reader that stops early leaves the stream inside the body.
  27046. // Draining the whole Content-Length from there, or reading the body again,
  27047. // reads into the next request, and whatever follows is parsed as a request
  27048. // of its own.
  27049. Server svr;
  27050. std::atomic<int> smuggled_count(0);
  27051. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27052. svr.Post("/upload", [](const Request &req, Response &res,
  27053. const ContentReader &content_reader) {
  27054. // Stop at the last chunk, so the whole body has been read however it
  27055. // arrives.
  27056. auto length = req.get_header_value_u64("Content-Length");
  27057. size_t total = 0;
  27058. auto consumed = content_reader([&](const char *, size_t n) {
  27059. total += n;
  27060. return total < length;
  27061. });
  27062. EXPECT_FALSE(consumed);
  27063. if (req.has_param("retry")) {
  27064. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27065. }
  27066. // Replace the 400 the aborted read set, which would close the connection.
  27067. res.set_redirect("/done");
  27068. });
  27069. auto port = svr.bind_to_any_port(HOST);
  27070. thread t = thread([&] { svr.listen_after_bind(); });
  27071. auto se = detail::scope_exit([&] {
  27072. svr.stop();
  27073. t.join();
  27074. });
  27075. svr.wait_until_ready();
  27076. // A front end sees the second request as a POST whose body is the GET. The
  27077. // first body is as long as the POST's headers, so draining it again reads
  27078. // exactly those and leaves the GET to be parsed next.
  27079. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27080. "Host: localhost\r\n"
  27081. "\r\n";
  27082. std::string second_head = "POST /post HTTP/1.1\r\n"
  27083. "Host: localhost\r\n"
  27084. "Content-Length: " +
  27085. std::to_string(inner.size()) +
  27086. "\r\n"
  27087. "\r\n";
  27088. for (auto target : {"/upload", "/upload?retry"}) {
  27089. smuggled_count = 0;
  27090. std::string request = "POST " + std::string(target) +
  27091. " HTTP/1.1\r\n"
  27092. "Host: localhost\r\n"
  27093. "Content-Length: " +
  27094. std::to_string(second_head.size()) +
  27095. "\r\n"
  27096. "\r\n" +
  27097. std::string(second_head.size(), 'A') + second_head +
  27098. inner;
  27099. std::string response;
  27100. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27101. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27102. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27103. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27104. EXPECT_EQ(0, smuggled_count.load()) << target;
  27105. }
  27106. }
  27107. // An error response closes the connection anyway, so the body is left unread
  27108. // with a redirect, such as one to a login page.
  27109. static void serve_redirects(Server &svr,
  27110. const std::function<void(int)> &client) {
  27111. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27112. res.set_redirect("/login");
  27113. return Server::HandlerResponse::Handled;
  27114. });
  27115. auto port = svr.bind_to_any_port(HOST);
  27116. ASSERT_GT(port, 0);
  27117. thread t = thread([&] { svr.listen_after_bind(); });
  27118. auto se = detail::scope_exit([&] {
  27119. svr.stop();
  27120. t.join();
  27121. ASSERT_FALSE(svr.is_running());
  27122. });
  27123. svr.wait_until_ready();
  27124. client(port);
  27125. }
  27126. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27127. Server svr;
  27128. serve_redirects(svr, [](int port) {
  27129. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27130. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27131. std::to_string(body.size()) + "\r\n\r\n" + body +
  27132. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27133. std::string resp;
  27134. ASSERT_TRUE(send_request(1, req, &resp, port));
  27135. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27136. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27137. });
  27138. }
  27139. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27140. Server svr;
  27141. svr.set_read_timeout(0, 200000);
  27142. serve_redirects(svr, [](int port) {
  27143. // A byte every 100 ms keeps each read within the read timeout, but not the
  27144. // body as a whole, so the server closes and the bytes sent after that fail.
  27145. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27146. "Content-Length: 10\r\n\r\n"};
  27147. parts.resize(11, "x");
  27148. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27149. });
  27150. }
  27151. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27152. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27153. // must be rejected with 400 Bad Request.
  27154. Server svr;
  27155. svr.Post("/test", [&](const Request &, Response &res) {
  27156. res.set_content("ok", "text/plain");
  27157. });
  27158. thread t = thread([&] { svr.listen(HOST, PORT); });
  27159. auto se = detail::scope_exit([&] {
  27160. svr.stop();
  27161. t.join();
  27162. ASSERT_FALSE(svr.is_running());
  27163. });
  27164. svr.wait_until_ready();
  27165. // Exact "chunked"
  27166. {
  27167. auto req = "POST /test HTTP/1.1\r\n"
  27168. "Host: localhost\r\n"
  27169. "Content-Length: 5\r\n"
  27170. "Transfer-Encoding: chunked\r\n"
  27171. "Connection: close\r\n"
  27172. "\r\n"
  27173. "hello";
  27174. std::string response;
  27175. ASSERT_TRUE(send_request(1, req, &response));
  27176. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27177. response.substr(0, response.find("\r\n")));
  27178. }
  27179. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27180. {
  27181. auto req = "POST /test HTTP/1.1\r\n"
  27182. "Host: localhost\r\n"
  27183. "Content-Length: 5\r\n"
  27184. "Transfer-Encoding: gzip, chunked\r\n"
  27185. "Connection: close\r\n"
  27186. "\r\n"
  27187. "hello";
  27188. std::string response;
  27189. ASSERT_TRUE(send_request(1, req, &response));
  27190. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27191. response.substr(0, response.find("\r\n")));
  27192. }
  27193. }
  27194. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27195. Server svr;
  27196. svr.Post("/test", [&](const Request &, Response &res) {
  27197. res.set_content("ok", "text/plain");
  27198. });
  27199. thread t = thread([&] { svr.listen(HOST, PORT); });
  27200. auto se = detail::scope_exit([&] {
  27201. svr.stop();
  27202. t.join();
  27203. ASSERT_FALSE(svr.is_running());
  27204. });
  27205. svr.wait_until_ready();
  27206. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27207. // length cannot be determined, so the server must answer 400 and close
  27208. // rather than treat the request as bodyless and leave the body in the
  27209. // socket for the next request to pick up.
  27210. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27211. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27212. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27213. std::string response;
  27214. ASSERT_TRUE(send_request(1, req, &response));
  27215. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27216. response.substr(0, response.find("\r\n")))
  27217. << transfer_encoding;
  27218. }
  27219. // RFC 9110 5.3: the codings may also be split across several
  27220. // Transfer-Encoding lines, which combine in the order they were received.
  27221. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27222. // just like the single-line "chunked, gzip" above.
  27223. {
  27224. auto req = "POST /test HTTP/1.1\r\n"
  27225. "Host: localhost\r\n"
  27226. "Transfer-Encoding: chunked\r\n"
  27227. "Transfer-Encoding: gzip\r\n"
  27228. "\r\n"
  27229. "0\r\n\r\n";
  27230. std::string response;
  27231. ASSERT_TRUE(send_request(1, req, &response));
  27232. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27233. response.substr(0, response.find("\r\n")));
  27234. }
  27235. }
  27236. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27237. Server svr;
  27238. svr.Post("/test", [&](const Request &, Response &res) {
  27239. res.set_content("ok", "text/plain");
  27240. });
  27241. auto port = svr.bind_to_any_port(HOST);
  27242. ASSERT_GT(port, 0);
  27243. thread t = thread([&] { svr.listen_after_bind(); });
  27244. auto se = detail::scope_exit([&] {
  27245. svr.stop();
  27246. t.join();
  27247. ASSERT_FALSE(svr.is_running());
  27248. });
  27249. svr.wait_until_ready();
  27250. for (auto transfer_encoding :
  27251. {"Transfer-Encoding: gzip, chunked\r\n",
  27252. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27253. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27254. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27255. transfer_encoding + "\r\n0\r\n\r\n";
  27256. std::string response;
  27257. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27258. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27259. response.substr(0, response.find("\r\n")))
  27260. << transfer_encoding;
  27261. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27262. << transfer_encoding;
  27263. }
  27264. }
  27265. // Regression for issue #2450: a DELETE without Content-Length on a
  27266. // keep-alive connection must not let the post-response drain consume the
  27267. // next request's bytes.
  27268. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27269. Server svr;
  27270. std::atomic<int> delete_count(0);
  27271. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27272. delete_count++;
  27273. res.status = StatusCode::NoContent_204;
  27274. });
  27275. auto port = svr.bind_to_any_port(HOST);
  27276. thread t = thread([&] { svr.listen_after_bind(); });
  27277. auto se = detail::scope_exit([&] {
  27278. svr.stop();
  27279. t.join();
  27280. });
  27281. svr.wait_until_ready();
  27282. auto error = Error::Success;
  27283. auto sock = detail::create_client_socket(
  27284. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27285. /*connection_timeout_sec=*/2, 0,
  27286. /*read_timeout_sec=*/2, 0,
  27287. /*write_timeout_sec=*/2, 0, std::string(), error);
  27288. ASSERT_NE(INVALID_SOCKET, sock);
  27289. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27290. auto send_request_and_read_response = [&](const std::string &req,
  27291. std::string &out) -> bool {
  27292. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27293. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27294. char buf[4096];
  27295. for (;;) {
  27296. auto n = recv(sock, buf, sizeof(buf), 0);
  27297. if (n <= 0) { return !out.empty(); }
  27298. out.append(buf, static_cast<size_t>(n));
  27299. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27300. }
  27301. };
  27302. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27303. "Host: localhost\r\n"
  27304. "\r\n";
  27305. std::string resp1;
  27306. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27307. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27308. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27309. "Host: localhost\r\n"
  27310. "Connection: close\r\n"
  27311. "\r\n";
  27312. std::string resp2;
  27313. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27314. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27315. EXPECT_EQ(2, delete_count.load());
  27316. }
  27317. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27318. Server svr;
  27319. svr.Post("/ingest", [&](const Request &, Response &res,
  27320. const ContentReader &content_reader) {
  27321. auto consumed = content_reader([](const char *, size_t) { return false; });
  27322. EXPECT_FALSE(consumed);
  27323. res.status = StatusCode::Conflict_409;
  27324. res.set_header("Connection", "close");
  27325. });
  27326. auto port = svr.bind_to_any_port(HOST);
  27327. thread t = thread([&] { svr.listen_after_bind(); });
  27328. auto se = detail::scope_exit([&] {
  27329. svr.stop();
  27330. t.join();
  27331. });
  27332. svr.wait_until_ready();
  27333. auto error = Error::Success;
  27334. auto sock = detail::create_client_socket(
  27335. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27336. /*connection_timeout_sec=*/2, 0,
  27337. /*read_timeout_sec=*/1, 0,
  27338. /*write_timeout_sec=*/2, 0, std::string(), error);
  27339. ASSERT_NE(INVALID_SOCKET, sock);
  27340. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27341. std::string request = "POST /ingest HTTP/1.1\r\n"
  27342. "Host: localhost\r\n"
  27343. "Transfer-Encoding: chunked\r\n"
  27344. "\r\n"
  27345. "4\r\n"
  27346. "data\r\n";
  27347. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27348. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27349. std::string response;
  27350. ssize_t received = 0;
  27351. do {
  27352. char buf[4096];
  27353. received = recv(sock, buf, sizeof(buf), 0);
  27354. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27355. } while (received > 0);
  27356. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27357. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27358. EXPECT_EQ(0, received);
  27359. }
  27360. namespace no_proxy_test {
  27361. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27362. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27363. // calling listen().
  27364. class ScopedServer {
  27365. public:
  27366. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27367. ~ScopedServer() {
  27368. svr_.stop();
  27369. if (th_.joinable()) { th_.join(); }
  27370. }
  27371. Server &svr() { return svr_; }
  27372. int port() const { return port_; }
  27373. void listen() {
  27374. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27375. svr_.wait_until_ready();
  27376. }
  27377. private:
  27378. Server svr_;
  27379. std::thread th_;
  27380. int port_ = 0;
  27381. };
  27382. class ProxyAndTargetServers {
  27383. public:
  27384. ProxyAndTargetServers() {
  27385. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27386. proxy_hits_++;
  27387. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27388. res.set_content("via-proxy", "text/plain");
  27389. });
  27390. target_.Get(".*", [this](const Request &req, Response &res) {
  27391. target_hits_++;
  27392. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27393. res.set_content("direct", "text/plain");
  27394. });
  27395. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27396. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27397. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27398. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27399. proxy_mock_.wait_until_ready();
  27400. target_.wait_until_ready();
  27401. }
  27402. ~ProxyAndTargetServers() {
  27403. proxy_mock_.stop();
  27404. target_.stop();
  27405. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27406. if (target_thread_.joinable()) { target_thread_.join(); }
  27407. }
  27408. Server &proxy_mock() { return proxy_mock_; }
  27409. Server &target() { return target_; }
  27410. int proxy_port() const { return proxy_port_; }
  27411. int target_port() const { return target_port_; }
  27412. int proxy_hits() const { return proxy_hits_.load(); }
  27413. int target_hits() const { return target_hits_.load(); }
  27414. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27415. void reset_counters() {
  27416. proxy_hits_ = 0;
  27417. target_hits_ = 0;
  27418. last_had_proxy_authz_ = false;
  27419. }
  27420. private:
  27421. Server proxy_mock_;
  27422. Server target_;
  27423. std::thread proxy_thread_;
  27424. std::thread target_thread_;
  27425. int proxy_port_ = 0;
  27426. int target_port_ = 0;
  27427. std::atomic<int> proxy_hits_{0};
  27428. std::atomic<int> target_hits_{0};
  27429. std::atomic<bool> last_had_proxy_authz_{false};
  27430. };
  27431. inline std::unique_ptr<Client> make_client(const std::string &host,
  27432. ProxyAndTargetServers &s) {
  27433. auto cli = detail::make_unique<Client>(host, s.target_port());
  27434. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27435. cli->set_proxy("127.0.0.1", s.proxy_port());
  27436. return cli;
  27437. }
  27438. } // namespace no_proxy_test
  27439. using no_proxy_test::make_client;
  27440. using no_proxy_test::ProxyAndTargetServers;
  27441. // A stream request carries the credentials a buffered request does
  27442. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27443. no_proxy_test::ScopedServer origin;
  27444. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27445. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27446. });
  27447. origin.listen();
  27448. Client cli("127.0.0.1", origin.port());
  27449. cli.set_basic_auth("user", "pass");
  27450. auto handle = cli.open_stream("GET", "/x");
  27451. ASSERT_TRUE(handle.is_valid());
  27452. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27453. Client bearer("127.0.0.1", origin.port());
  27454. bearer.set_bearer_token_auth("tok");
  27455. auto handle2 = bearer.open_stream("GET", "/x");
  27456. ASSERT_TRUE(handle2.is_valid());
  27457. EXPECT_EQ("Bearer tok", read_all(handle2));
  27458. }
  27459. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27460. // takes its own credentials, as for a buffered request
  27461. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27462. std::string target, authz, proxy_authz;
  27463. no_proxy_test::ScopedServer proxy;
  27464. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27465. target = req.target;
  27466. authz = req.get_header_value("Authorization");
  27467. proxy_authz = req.get_header_value("Proxy-Authorization");
  27468. res.set_content("ok", "text/plain");
  27469. });
  27470. proxy.listen();
  27471. Client cli("origin.example", 8080);
  27472. cli.set_proxy("127.0.0.1", proxy.port());
  27473. cli.set_proxy_basic_auth("puser", "ppass");
  27474. cli.set_basic_auth("user", "pass");
  27475. auto handle = cli.open_stream("GET", "/x");
  27476. ASSERT_TRUE(handle.is_valid());
  27477. EXPECT_EQ("ok", read_all(handle));
  27478. EXPECT_EQ("http://origin.example:8080/x", target);
  27479. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27480. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27481. }
  27482. // In absolute-form the path follows the authority, so a path that does not
  27483. // begin with '/' would make the proxy connect to another host
  27484. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27485. std::vector<std::string> targets;
  27486. no_proxy_test::ScopedServer proxy;
  27487. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27488. targets.push_back(req.target);
  27489. res.set_content("ok", "text/plain");
  27490. });
  27491. proxy.listen();
  27492. Client cli("origin.example", 8080);
  27493. cli.set_proxy("127.0.0.1", proxy.port());
  27494. cli.set_basic_auth("user", "pass");
  27495. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27496. auto res = cli.Get(path);
  27497. EXPECT_FALSE(res) << path;
  27498. auto handle = cli.open_stream("GET", path);
  27499. EXPECT_FALSE(handle.is_valid()) << path;
  27500. }
  27501. EXPECT_TRUE(targets.empty());
  27502. auto res = cli.Get("/x");
  27503. ASSERT_TRUE(res);
  27504. ASSERT_EQ(1u, targets.size());
  27505. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27506. }
  27507. TEST(NoProxyTest, ExactHostnameBypasses) {
  27508. ProxyAndTargetServers s;
  27509. auto cli = make_client("example.com", s);
  27510. cli->set_no_proxy({"example.com"});
  27511. auto res = cli->Get("/");
  27512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27513. EXPECT_EQ(0, s.proxy_hits());
  27514. EXPECT_EQ(1, s.target_hits());
  27515. }
  27516. TEST(NoProxyTest, SubdomainBypasses) {
  27517. ProxyAndTargetServers s;
  27518. auto cli = make_client("foo.example.com", s);
  27519. cli->set_no_proxy({"example.com"});
  27520. auto res = cli->Get("/");
  27521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27522. EXPECT_EQ(0, s.proxy_hits());
  27523. EXPECT_EQ(1, s.target_hits());
  27524. }
  27525. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27526. // Regression guard: "evilexample.com" must not be considered a subdomain
  27527. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27528. // check would let traffic bypass the proxy and leak credentials direct
  27529. // to the attacker host.
  27530. ProxyAndTargetServers s;
  27531. auto cli = make_client("evilexample.com", s);
  27532. cli->set_no_proxy({"example.com"});
  27533. auto res = cli->Get("/");
  27534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27535. EXPECT_GE(s.proxy_hits(), 1);
  27536. EXPECT_EQ(0, s.target_hits());
  27537. }
  27538. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27539. ProxyAndTargetServers s;
  27540. auto cli = make_client("example.com.evil.com", s);
  27541. cli->set_no_proxy({"example.com"});
  27542. auto res = cli->Get("/");
  27543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27544. EXPECT_GE(s.proxy_hits(), 1);
  27545. EXPECT_EQ(0, s.target_hits());
  27546. }
  27547. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27548. ProxyAndTargetServers s;
  27549. auto cli = make_client("example.com", s);
  27550. cli->set_no_proxy({".example.com"});
  27551. auto res = cli->Get("/");
  27552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27553. EXPECT_EQ(0, s.proxy_hits());
  27554. EXPECT_EQ(1, s.target_hits());
  27555. }
  27556. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27557. ProxyAndTargetServers s;
  27558. auto cli = make_client("Example.COM", s);
  27559. cli->set_no_proxy({"EXAMPLE.com"});
  27560. auto res = cli->Get("/");
  27561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27562. EXPECT_EQ(0, s.proxy_hits());
  27563. EXPECT_EQ(1, s.target_hits());
  27564. }
  27565. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27566. ProxyAndTargetServers s;
  27567. auto cli = make_client("example.com.", s);
  27568. cli->set_no_proxy({"example.com"});
  27569. auto res = cli->Get("/");
  27570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27571. EXPECT_EQ(0, s.proxy_hits());
  27572. EXPECT_EQ(1, s.target_hits());
  27573. }
  27574. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27575. // Trailing dots must be normalized on BOTH sides — host and entry.
  27576. // An implementation that only strips the host-side trailing dot would
  27577. // fail to match host "example.com" against entry "example.com." because
  27578. // a literal substring search would compare 11 chars against 12.
  27579. ProxyAndTargetServers s;
  27580. auto cli = make_client("example.com", s);
  27581. cli->set_no_proxy({"example.com."});
  27582. auto res = cli->Get("/");
  27583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27584. EXPECT_EQ(0, s.proxy_hits());
  27585. EXPECT_EQ(1, s.target_hits());
  27586. }
  27587. TEST(NoProxyTest, WildcardBypassesEverything) {
  27588. ProxyAndTargetServers s;
  27589. auto cli = make_client("anything.invalid.test", s);
  27590. cli->set_no_proxy({"*"});
  27591. auto res = cli->Get("/");
  27592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27593. EXPECT_EQ(0, s.proxy_hits());
  27594. EXPECT_EQ(1, s.target_hits());
  27595. }
  27596. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27597. ProxyAndTargetServers s;
  27598. Client cli("127.0.0.1", s.target_port());
  27599. cli.set_proxy("127.0.0.1", s.proxy_port());
  27600. cli.set_no_proxy({"127.0.0.1"});
  27601. auto res = cli.Get("/");
  27602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27603. EXPECT_EQ(0, s.proxy_hits());
  27604. EXPECT_EQ(1, s.target_hits());
  27605. }
  27606. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27607. ProxyAndTargetServers s;
  27608. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27609. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27610. cli.set_proxy("127.0.0.1", s.proxy_port());
  27611. cli.set_no_proxy({"::1"});
  27612. auto res = cli.Get("/");
  27613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27614. EXPECT_EQ(0, s.proxy_hits());
  27615. EXPECT_EQ(1, s.target_hits());
  27616. }
  27617. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27618. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27619. // must still be recognized as IPv6 for CIDR matching. Implementations
  27620. // that detect IPv6 only when the host begins with '[' would parse the
  27621. // host as a hostname and miss the match.
  27622. ProxyAndTargetServers s;
  27623. Client cli("fe80::1", s.target_port());
  27624. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27625. cli.set_proxy("127.0.0.1", s.proxy_port());
  27626. cli.set_no_proxy({"fe80::/10"});
  27627. auto res = cli.Get("/");
  27628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27629. EXPECT_EQ(0, s.proxy_hits());
  27630. EXPECT_EQ(1, s.target_hits());
  27631. }
  27632. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27633. ProxyAndTargetServers s;
  27634. Client cli("::1", s.target_port());
  27635. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27636. cli.set_proxy("127.0.0.1", s.proxy_port());
  27637. cli.set_no_proxy({"[::1]"});
  27638. auto res = cli.Get("/");
  27639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27640. EXPECT_EQ(0, s.proxy_hits());
  27641. EXPECT_EQ(1, s.target_hits());
  27642. }
  27643. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27644. ProxyAndTargetServers s;
  27645. Client cli("fe80::1", s.target_port());
  27646. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27647. cli.set_proxy("127.0.0.1", s.proxy_port());
  27648. cli.set_no_proxy({"[fe80::]/10"});
  27649. auto res = cli.Get("/");
  27650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27651. EXPECT_EQ(0, s.proxy_hits());
  27652. EXPECT_EQ(1, s.target_hits());
  27653. }
  27654. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27655. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27656. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27657. // tricks via address-family conversion.
  27658. ProxyAndTargetServers s;
  27659. Client cli("::ffff:127.0.0.1", s.target_port());
  27660. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27661. cli.set_proxy("127.0.0.1", s.proxy_port());
  27662. cli.set_no_proxy({"127.0.0.1"});
  27663. auto res = cli.Get("/");
  27664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27665. EXPECT_GE(s.proxy_hits(), 1);
  27666. EXPECT_EQ(0, s.target_hits());
  27667. }
  27668. TEST(NoProxyTest, IPv4CidrMatch) {
  27669. ProxyAndTargetServers s;
  27670. Client cli("127.0.0.1", s.target_port());
  27671. cli.set_proxy("127.0.0.1", s.proxy_port());
  27672. cli.set_no_proxy({"127.0.0.0/8"});
  27673. auto res = cli.Get("/");
  27674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27675. EXPECT_EQ(0, s.proxy_hits());
  27676. EXPECT_EQ(1, s.target_hits());
  27677. }
  27678. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27679. ProxyAndTargetServers s;
  27680. Client cli("127.0.0.1", s.target_port());
  27681. cli.set_proxy("127.0.0.1", s.proxy_port());
  27682. cli.set_no_proxy({"10.0.0.0/8"});
  27683. auto res = cli.Get("/");
  27684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27685. EXPECT_GE(s.proxy_hits(), 1);
  27686. EXPECT_EQ(0, s.target_hits());
  27687. }
  27688. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27689. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27690. // IPv4 target matches.
  27691. ProxyAndTargetServers s;
  27692. Client cli("127.0.0.1", s.target_port());
  27693. cli.set_proxy("127.0.0.1", s.proxy_port());
  27694. cli.set_no_proxy({"0.0.0.0/0"});
  27695. auto res = cli.Get("/");
  27696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27697. EXPECT_EQ(0, s.proxy_hits());
  27698. EXPECT_EQ(1, s.target_hits());
  27699. }
  27700. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27701. ProxyAndTargetServers s;
  27702. Client cli("127.0.0.1", s.target_port());
  27703. cli.set_proxy("127.0.0.1", s.proxy_port());
  27704. cli.set_no_proxy({"127.0.0.1"});
  27705. auto res = cli.Get("/");
  27706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27707. EXPECT_EQ(0, s.proxy_hits());
  27708. EXPECT_EQ(1, s.target_hits());
  27709. }
  27710. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27711. ProxyAndTargetServers s;
  27712. Client cli("127.0.0.1", s.target_port());
  27713. cli.set_proxy("127.0.0.1", s.proxy_port());
  27714. cli.set_no_proxy({"127.0.0.0/33"});
  27715. auto res = cli.Get("/");
  27716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27717. EXPECT_GE(s.proxy_hits(), 1);
  27718. EXPECT_EQ(0, s.target_hits());
  27719. }
  27720. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27721. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27722. ProxyAndTargetServers s;
  27723. Client cli("127.0.0.1", s.target_port());
  27724. cli.set_proxy("127.0.0.1", s.proxy_port());
  27725. cli.set_no_proxy({"127.0.0.1/"});
  27726. auto res = cli.Get("/");
  27727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27728. EXPECT_GE(s.proxy_hits(), 1);
  27729. EXPECT_EQ(0, s.target_hits());
  27730. }
  27731. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27732. ProxyAndTargetServers s;
  27733. auto cli = make_client("internal.corp", s);
  27734. cli->set_proxy_basic_auth("u", "p");
  27735. cli->set_no_proxy({"internal.corp"});
  27736. auto res = cli->Get("/");
  27737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27738. EXPECT_EQ(1, s.target_hits());
  27739. EXPECT_EQ(0, s.proxy_hits());
  27740. EXPECT_FALSE(s.last_had_proxy_authz())
  27741. << "Proxy-Authorization must not be sent direct to the target";
  27742. }
  27743. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27744. ProxyAndTargetServers s;
  27745. auto cli = make_client("public.example", s);
  27746. cli->set_proxy_basic_auth("u", "p");
  27747. cli->set_no_proxy({"internal.corp"}); // does not match
  27748. auto res = cli->Get("/");
  27749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27750. EXPECT_GE(s.proxy_hits(), 1);
  27751. EXPECT_TRUE(s.last_had_proxy_authz());
  27752. }
  27753. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27754. std::atomic<int> hits{0};
  27755. std::atomic<int> hits_with_authz{0};
  27756. no_proxy_test::ScopedServer proxy_mock;
  27757. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27758. hits++;
  27759. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27760. if (req.target.find("/redir") != std::string::npos) {
  27761. res.set_redirect("http://other.example/landed");
  27762. } else {
  27763. res.set_content("via-proxy", "text/plain");
  27764. }
  27765. });
  27766. proxy_mock.listen();
  27767. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27768. hits = 0;
  27769. hits_with_authz = 0;
  27770. Client cli("public.example", 80);
  27771. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27772. cli.set_proxy_basic_auth(c.first, c.second);
  27773. cli.set_follow_location(true);
  27774. // The redirect to another host goes through the proxy as well
  27775. auto res = cli.Get("/redir");
  27776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27777. EXPECT_EQ(2, hits.load());
  27778. EXPECT_EQ(2, hits_with_authz.load());
  27779. }
  27780. }
  27781. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27782. ProxyAndTargetServers s;
  27783. auto cli = make_client("anything.test", s);
  27784. auto res = cli->Get("/");
  27785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27786. EXPECT_GE(s.proxy_hits(), 1);
  27787. EXPECT_EQ(0, s.target_hits());
  27788. }
  27789. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27790. ProxyAndTargetServers s;
  27791. auto cli = make_client("example.com", s);
  27792. cli->set_no_proxy({"example.com:8080"});
  27793. auto res = cli->Get("/");
  27794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27795. EXPECT_GE(s.proxy_hits(), 1);
  27796. EXPECT_EQ(0, s.target_hits());
  27797. }
  27798. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27799. ProxyAndTargetServers s;
  27800. auto cli = make_client("anything.test", s);
  27801. cli->set_no_proxy({"", " ", "\t"});
  27802. auto res = cli->Get("/");
  27803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27804. EXPECT_GE(s.proxy_hits(), 1);
  27805. EXPECT_EQ(0, s.target_hits());
  27806. }
  27807. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27808. // An entry with leading/trailing whitespace must still match — env-style
  27809. // values are commonly pasted with stray spaces and an implementation
  27810. // that feeds the raw token directly to inet_pton would fail to match
  27811. // valid CIDRs because of the spaces.
  27812. ProxyAndTargetServers s;
  27813. Client cli("127.0.0.1", s.target_port());
  27814. cli.set_proxy("127.0.0.1", s.proxy_port());
  27815. cli.set_no_proxy({" 127.0.0.0/8 "});
  27816. auto res = cli.Get("/");
  27817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27818. EXPECT_EQ(0, s.proxy_hits());
  27819. EXPECT_EQ(1, s.target_hits());
  27820. }
  27821. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27822. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27823. // go direct and must NOT carry Proxy-Authorization.
  27824. std::atomic<int> proxy_hits{0};
  27825. std::atomic<int> target_hits{0};
  27826. std::atomic<bool> target_saw_authz{false};
  27827. no_proxy_test::ScopedServer proxy_mock, target;
  27828. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27829. proxy_hits++;
  27830. res.status = 302;
  27831. res.set_header("Location", "http://127.0.0.1:" +
  27832. std::to_string(target.port()) + "/landed");
  27833. });
  27834. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27835. target_hits++;
  27836. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27837. res.set_content("direct", "text/plain");
  27838. });
  27839. proxy_mock.listen();
  27840. target.listen();
  27841. Client cli("public.example", target.port());
  27842. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27843. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27844. cli.set_proxy_basic_auth("u", "p");
  27845. cli.set_no_proxy({"127.0.0.1"});
  27846. cli.set_follow_location(true);
  27847. auto res = cli.Get("/redir");
  27848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27849. EXPECT_GE(proxy_hits.load(), 1);
  27850. EXPECT_GE(target_hits.load(), 1);
  27851. EXPECT_FALSE(target_saw_authz.load());
  27852. }
  27853. #ifdef CPPHTTPLIB_SSL_ENABLED
  27854. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27855. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27856. // proxy creds would be sent to the (possibly hostile) origin.
  27857. std::atomic<int> target_hits{0};
  27858. std::atomic<bool> target_saw_proxy_authz{false};
  27859. no_proxy_test::ScopedServer target;
  27860. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27861. target_hits++;
  27862. if (req.has_header("Proxy-Authorization")) {
  27863. target_saw_proxy_authz = true;
  27864. }
  27865. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27866. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27867. "nonce=\"abc\", algorithm=MD5");
  27868. });
  27869. target.listen();
  27870. // The proxy address is set to the target's port: the bypass MUST kick in;
  27871. // if it doesn't, the test still routes "via proxy" to the same server and
  27872. // the Proxy-Authorization assertion below catches the leak.
  27873. Client cli("evil.example", target.port());
  27874. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27875. cli.set_proxy("127.0.0.1", target.port());
  27876. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27877. cli.set_no_proxy({"evil.example"});
  27878. auto res = cli.Get("/x");
  27879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27880. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27881. EXPECT_EQ(1, target_hits.load());
  27882. EXPECT_FALSE(target_saw_proxy_authz.load());
  27883. }
  27884. #endif
  27885. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27886. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27887. std::atomic<int> proxy_hits{0};
  27888. std::atomic<int> bypass_hits{0};
  27889. std::atomic<bool> proxy_saw_c_url{false};
  27890. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27891. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27892. proxy_hits++;
  27893. if (req.path.find("/start") != std::string::npos) {
  27894. res.status = 302;
  27895. res.set_header("Location", "http://127.0.0.1:" +
  27896. std::to_string(bypass_server.port()) +
  27897. "/middle");
  27898. return;
  27899. }
  27900. if (req.path.find("/end") != std::string::npos) {
  27901. proxy_saw_c_url = true;
  27902. res.set_content("c-via-proxy", "text/plain");
  27903. return;
  27904. }
  27905. res.set_content("unexpected", "text/plain");
  27906. });
  27907. // public.example's "advertised" port is arbitrary (the request never lands
  27908. // there — it goes through the proxy), but use a dynamic value to stay
  27909. // friendly with sharded parallel runs.
  27910. int public_port = bypass_server.port();
  27911. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27912. bypass_hits++;
  27913. res.status = 302;
  27914. res.set_header("Location", "http://public.example:" +
  27915. std::to_string(public_port) + "/end");
  27916. });
  27917. proxy_mock.listen();
  27918. bypass_server.listen();
  27919. Client cli("public.example", public_port);
  27920. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27921. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27922. cli.set_no_proxy({"127.0.0.1"});
  27923. cli.set_follow_location(true);
  27924. auto res = cli.Get("/start");
  27925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27926. EXPECT_EQ(StatusCode::OK_200, res->status);
  27927. EXPECT_EQ("c-via-proxy", res->body);
  27928. EXPECT_GE(proxy_hits.load(), 2);
  27929. EXPECT_GE(bypass_hits.load(), 1);
  27930. EXPECT_TRUE(proxy_saw_c_url.load());
  27931. }
  27932. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27933. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27934. // request reconnects to the correct endpoint.
  27935. std::atomic<int> proxy_hits{0};
  27936. std::atomic<int> target_hits{0};
  27937. no_proxy_test::ScopedServer proxy_mock, target;
  27938. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27939. proxy_hits++;
  27940. res.set_content("via-proxy", "text/plain");
  27941. });
  27942. target.svr().Get(".*", [&](const Request &, Response &res) {
  27943. target_hits++;
  27944. res.set_content("direct", "text/plain");
  27945. });
  27946. proxy_mock.listen();
  27947. target.listen();
  27948. Client cli("public.example", target.port());
  27949. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27950. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27951. cli.set_keep_alive(true);
  27952. auto res1 = cli.Get("/a");
  27953. ASSERT_TRUE(res1);
  27954. EXPECT_EQ("via-proxy", res1->body);
  27955. EXPECT_EQ(1, proxy_hits.load());
  27956. EXPECT_EQ(0, target_hits.load());
  27957. cli.set_no_proxy({"public.example"});
  27958. auto res2 = cli.Get("/b");
  27959. ASSERT_TRUE(res2);
  27960. EXPECT_EQ("direct", res2->body);
  27961. EXPECT_EQ(1, proxy_hits.load());
  27962. EXPECT_EQ(1, target_hits.load());
  27963. }
  27964. // Forward declarations (see the base64_encode note).
  27965. namespace httplib {
  27966. namespace detail {
  27967. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27968. int shutdown_socket(socket_t sock) noexcept;
  27969. } // namespace detail
  27970. } // namespace httplib
  27971. namespace proxy_tunnel_test {
  27972. const char *const kTunnelEstablished =
  27973. "HTTP/1.1 200 Connection established\r\n\r\n";
  27974. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27975. using ConnectReply = std::function<std::string(const std::string &head)>;
  27976. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27977. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27978. class ScopedConnectProxy {
  27979. public:
  27980. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27981. : forward_port_(forward_port), reply_(std::move(reply)) {
  27982. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27983. if (listen_sock_ == INVALID_SOCKET) { return; }
  27984. auto a = loopback(0);
  27985. auto addr = reinterpret_cast<sockaddr *>(&a);
  27986. socklen_t alen = sizeof(a);
  27987. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27988. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27989. ::listen(listen_sock_, 4) != 0) {
  27990. return;
  27991. }
  27992. port_ = ntohs(a.sin_port);
  27993. th_ = std::thread([this] { run(); });
  27994. }
  27995. ~ScopedConnectProxy() {
  27996. if (th_.joinable()) {
  27997. stop_ = true;
  27998. auto wake = connect_to(port_);
  27999. th_.join();
  28000. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28001. }
  28002. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28003. }
  28004. int port() const { return port_; }
  28005. int connect_hits() const { return connect_hits_.load(); }
  28006. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28007. std::string connect_request() const {
  28008. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28009. return connect_request_;
  28010. }
  28011. private:
  28012. static sockaddr_in loopback(int port) {
  28013. sockaddr_in a{};
  28014. a.sin_family = AF_INET;
  28015. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28016. a.sin_port = htons(static_cast<unsigned short>(port));
  28017. return a;
  28018. }
  28019. static socket_t connect_to(int port) {
  28020. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28021. if (sock == INVALID_SOCKET) { return sock; }
  28022. auto a = loopback(port);
  28023. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28024. detail::close_socket(sock);
  28025. return INVALID_SOCKET;
  28026. }
  28027. return sock;
  28028. }
  28029. static bool send_all(socket_t sock, const char *data, size_t size) {
  28030. while (size > 0) {
  28031. auto n = detail::send_socket(sock, data, size, 0);
  28032. if (n <= 0) { return false; }
  28033. data += n;
  28034. size -= static_cast<size_t>(n);
  28035. }
  28036. return true;
  28037. }
  28038. void run() {
  28039. for (;;) {
  28040. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28041. if (stop_) {
  28042. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28043. return;
  28044. }
  28045. if (client == INVALID_SOCKET) { continue; }
  28046. serve(client);
  28047. detail::close_socket(client);
  28048. }
  28049. }
  28050. void serve(socket_t client) {
  28051. std::string head;
  28052. char buf[2048];
  28053. while (head.find("\r\n\r\n") == std::string::npos) {
  28054. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28055. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28056. if (n <= 0) { return; }
  28057. head.append(buf, static_cast<size_t>(n));
  28058. }
  28059. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28060. connect_hits_++;
  28061. {
  28062. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28063. connect_request_ = head;
  28064. }
  28065. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28066. if (!send_all(client, res.data(), res.size()) ||
  28067. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28068. return;
  28069. }
  28070. auto origin = connect_to(forward_port_);
  28071. if (origin == INVALID_SOCKET) { return; }
  28072. // When either side stops, shut both down so the other pump returns too.
  28073. auto pump = [&](socket_t from, socket_t to) {
  28074. char b[8192];
  28075. for (;;) {
  28076. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28077. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28078. }
  28079. detail::shutdown_socket(client);
  28080. detail::shutdown_socket(origin);
  28081. };
  28082. std::thread up([&] { pump(client, origin); });
  28083. pump(origin, client);
  28084. up.join();
  28085. detail::close_socket(origin);
  28086. }
  28087. int forward_port_;
  28088. ConnectReply reply_;
  28089. socket_t listen_sock_ = INVALID_SOCKET;
  28090. int port_ = 0;
  28091. std::thread th_;
  28092. std::atomic<bool> stop_{false};
  28093. std::atomic<int> connect_hits_{0};
  28094. mutable std::mutex connect_request_mutex_;
  28095. std::string connect_request_;
  28096. };
  28097. } // namespace proxy_tunnel_test
  28098. #ifdef CPPHTTPLIB_SSL_ENABLED
  28099. namespace proxy_tunnel_test {
  28100. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28101. class ScopedSSLServer {
  28102. public:
  28103. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28104. port_ = svr_.bind_to_any_port("127.0.0.1");
  28105. }
  28106. ~ScopedSSLServer() {
  28107. svr_.stop();
  28108. if (th_.joinable()) { th_.join(); }
  28109. }
  28110. SSLServer &svr() { return svr_; }
  28111. int port() const { return port_; }
  28112. void listen() {
  28113. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28114. svr_.wait_until_ready();
  28115. }
  28116. private:
  28117. SSLServer svr_;
  28118. std::thread th_;
  28119. int port_ = 0;
  28120. };
  28121. // Sends one request through the CONNECT proxy to the TLS origin with a
  28122. // credential configured for each hop, and checks that each credential reaches
  28123. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28124. // origin's (every header in origin_headers) on the tunnelled request.
  28125. void CredentialsStayWithTheirHop(
  28126. const std::function<void(SSLClient &)> &set_credentials,
  28127. const std::string &scheme,
  28128. const std::vector<std::string> &origin_headers = {"Authorization"},
  28129. bool stream = false) {
  28130. std::atomic<int> origin_hits{0};
  28131. std::atomic<bool> origin_saw_proxy_authz{false};
  28132. std::atomic<bool> origin_saw_headers{false};
  28133. ScopedSSLServer origin;
  28134. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28135. origin_hits++;
  28136. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28137. origin_saw_headers =
  28138. std::all_of(origin_headers.begin(), origin_headers.end(),
  28139. [&](const std::string &h) { return req.has_header(h); });
  28140. res.set_content("ok", "text/plain");
  28141. });
  28142. origin.listen();
  28143. ScopedConnectProxy proxy(origin.port());
  28144. ASSERT_NE(0, proxy.port());
  28145. // Pinned to 127.0.0.1 for the same reason as the test below.
  28146. SSLClient cli("127.0.0.1", origin.port());
  28147. cli.enable_server_certificate_verification(false);
  28148. cli.set_proxy("127.0.0.1", proxy.port());
  28149. set_credentials(cli);
  28150. if (stream) {
  28151. auto handle = cli.open_stream("GET", "/x");
  28152. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28153. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28154. } else {
  28155. auto res = cli.Get("/x");
  28156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28157. EXPECT_EQ(StatusCode::OK_200, res->status);
  28158. }
  28159. EXPECT_EQ(1, origin_hits.load());
  28160. EXPECT_EQ(1, proxy.connect_hits());
  28161. EXPECT_TRUE(origin_saw_headers.load());
  28162. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28163. << "Proxy-Authorization must not be sent inside the tunnel";
  28164. auto connect_req = proxy.connect_request();
  28165. EXPECT_NE(std::string::npos,
  28166. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28167. for (const auto &h : origin_headers) {
  28168. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28169. << h << " must not be sent to the proxy on CONNECT";
  28170. }
  28171. }
  28172. } // namespace proxy_tunnel_test
  28173. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28174. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28175. [](SSLClient &cli) {
  28176. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28177. cli.set_basic_auth("origin-user", "origin-pass");
  28178. },
  28179. "Basic");
  28180. }
  28181. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28182. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28183. [](SSLClient &cli) {
  28184. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28185. cli.set_basic_auth("origin-user", "origin-pass");
  28186. },
  28187. "Basic", {"Authorization"}, true);
  28188. }
  28189. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28190. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28191. [](SSLClient &cli) {
  28192. cli.set_proxy_bearer_token_auth("proxy-token");
  28193. cli.set_bearer_token_auth("origin-token");
  28194. },
  28195. "Bearer");
  28196. }
  28197. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28198. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28199. [](SSLClient &cli) {
  28200. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28201. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28202. {"Cookie", "sid=origin-session"},
  28203. {"X-Api-Key", "origin-key"}});
  28204. },
  28205. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28206. }
  28207. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28208. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28209. // retry; otherwise proxy creds would be sent to the origin.
  28210. std::atomic<int> origin_hits{0};
  28211. std::atomic<bool> origin_saw_proxy_authz{false};
  28212. proxy_tunnel_test::ScopedSSLServer origin;
  28213. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28214. origin_hits++;
  28215. if (req.has_header("Proxy-Authorization")) {
  28216. origin_saw_proxy_authz = true;
  28217. }
  28218. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28219. res.set_header("Proxy-Authenticate",
  28220. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28221. "algorithm=MD5");
  28222. });
  28223. origin.listen();
  28224. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28225. ASSERT_NE(0, proxy.port());
  28226. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28227. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28228. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28229. // and answer with its own status, making this test flaky.
  28230. SSLClient cli("127.0.0.1", origin.port());
  28231. cli.enable_server_certificate_verification(false);
  28232. cli.set_proxy("127.0.0.1", proxy.port());
  28233. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28234. auto res = cli.Get("/x");
  28235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28236. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28237. EXPECT_EQ(1, origin_hits.load());
  28238. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28239. EXPECT_EQ(1, proxy.connect_hits());
  28240. }
  28241. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28242. std::string origin_sni;
  28243. std::string origin_host;
  28244. proxy_tunnel_test::ScopedSSLServer origin;
  28245. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28246. origin_sni = req.sni();
  28247. origin_host = req.get_header_value("Host");
  28248. res.set_content("ok", "text/plain");
  28249. });
  28250. origin.listen();
  28251. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28252. ASSERT_NE(0, proxy.port());
  28253. SSLClient cli("origin.example", origin.port());
  28254. cli.enable_server_certificate_verification(false);
  28255. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28256. cli.set_proxy("127.0.0.1", proxy.port());
  28257. auto res = cli.Get("/x");
  28258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28259. EXPECT_EQ(StatusCode::OK_200, res->status);
  28260. auto port = std::to_string(origin.port());
  28261. auto target = "127.0.0.1:" + port;
  28262. auto connect_req = proxy.connect_request();
  28263. EXPECT_EQ(1, proxy.connect_hits());
  28264. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28265. EXPECT_NE(std::string::npos,
  28266. connect_req.find("\r\nHost: " + target + "\r\n"));
  28267. EXPECT_EQ("origin.example", origin_sni);
  28268. EXPECT_EQ("origin.example:" + port, origin_host);
  28269. }
  28270. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28271. proxy_tunnel_test::ScopedSSLServer origin;
  28272. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28273. res.set_content("ok", "text/plain");
  28274. });
  28275. origin.listen();
  28276. proxy_tunnel_test::ScopedConnectProxy proxy(
  28277. origin.port(), [](const std::string &head) -> std::string {
  28278. if (head.find(
  28279. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28280. std::string::npos) {
  28281. return proxy_tunnel_test::kTunnelEstablished;
  28282. }
  28283. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28284. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28285. "nonce=\"abc\", algorithm=MD5\r\n"
  28286. "Content-Length: 0\r\n\r\n";
  28287. });
  28288. ASSERT_NE(0, proxy.port());
  28289. SSLClient cli("origin.example", origin.port());
  28290. cli.enable_server_certificate_verification(false);
  28291. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28292. cli.set_proxy("127.0.0.1", proxy.port());
  28293. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28294. auto res = cli.Get("/x");
  28295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28296. EXPECT_EQ(StatusCode::OK_200, res->status);
  28297. // The retried CONNECT is the one the proxy saw last.
  28298. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28299. auto connect_req = proxy.connect_request();
  28300. EXPECT_EQ(2, proxy.connect_hits());
  28301. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28302. EXPECT_NE(std::string::npos,
  28303. connect_req.find("\r\nHost: " + target + "\r\n"));
  28304. }
  28305. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28306. proxy_tunnel_test::ScopedSSLServer origin;
  28307. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28308. res.set_content("ok", "text/plain");
  28309. });
  28310. origin.listen();
  28311. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28312. ASSERT_NE(0, proxy.port());
  28313. SSLClient cli("origin.example", origin.port());
  28314. cli.enable_server_certificate_verification(false);
  28315. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28316. cli.set_proxy("127.0.0.1", proxy.port());
  28317. auto res = cli.Get("/x");
  28318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28319. EXPECT_EQ(StatusCode::OK_200, res->status);
  28320. auto target = "origin.example:" + std::to_string(origin.port());
  28321. auto connect_req = proxy.connect_request();
  28322. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28323. EXPECT_NE(std::string::npos,
  28324. connect_req.find("\r\nHost: " + target + "\r\n"));
  28325. }
  28326. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28327. proxy_tunnel_test::ScopedSSLServer origin;
  28328. auto port = std::to_string(origin.port());
  28329. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28330. res.set_redirect("https://next.example:" + port + "/y");
  28331. });
  28332. origin.svr().Get("/y", [](const Request &, Response &res) {
  28333. res.set_content("ok", "text/plain");
  28334. });
  28335. origin.listen();
  28336. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28337. ASSERT_NE(0, proxy.port());
  28338. SSLClient cli("origin.example", origin.port());
  28339. cli.enable_server_certificate_verification(false);
  28340. cli.set_tunnel_hostname_addr_map(
  28341. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28342. cli.set_proxy("127.0.0.1", proxy.port());
  28343. cli.set_follow_location(true);
  28344. auto res = cli.Get("/x");
  28345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28346. EXPECT_EQ("ok", res->body);
  28347. // The last CONNECT is the redirect client's.
  28348. ASSERT_EQ(2, proxy.connect_hits());
  28349. auto target = "127.0.0.1:" + port;
  28350. auto connect_req = proxy.connect_request();
  28351. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28352. EXPECT_NE(std::string::npos,
  28353. connect_req.find("\r\nHost: " + target + "\r\n"));
  28354. }
  28355. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28356. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28357. std::atomic<int> origin_hits{0};
  28358. proxy_tunnel_test::ScopedSSLServer origin;
  28359. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28360. origin_hits++;
  28361. res.set_content("ok", "text/plain");
  28362. });
  28363. origin.listen();
  28364. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28365. ASSERT_NE(0, proxy.port());
  28366. SSLClient cli("127.0.0.1", origin.port());
  28367. cli.enable_server_certificate_verification(false);
  28368. cli.set_proxy("127.0.0.1", proxy.port());
  28369. cli.set_keep_alive(true);
  28370. cli.set_session_verifier(
  28371. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28372. auto res = cli.Get("/x");
  28373. EXPECT_FALSE(res);
  28374. ASSERT_FALSE(cli.is_socket_open());
  28375. res = cli.Get("/x");
  28376. EXPECT_FALSE(res);
  28377. EXPECT_EQ(2, proxy.connect_hits());
  28378. auto handle = cli.open_stream("GET", "/x");
  28379. EXPECT_FALSE(handle.is_valid());
  28380. EXPECT_EQ(3, proxy.connect_hits());
  28381. EXPECT_EQ(0, origin_hits.load());
  28382. }
  28383. #endif
  28384. namespace proxy_tunnel_test {
  28385. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28386. // anything else gets a 407 with `challenge`.
  28387. ConnectReply require_proxy_auth(const std::string &expected,
  28388. const std::string &challenge) {
  28389. return [=](const std::string &head) -> std::string {
  28390. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28391. std::string::npos) {
  28392. return kTunnelEstablished;
  28393. }
  28394. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28395. "Proxy-Authenticate: " +
  28396. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28397. };
  28398. }
  28399. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28400. // request, then echoes.
  28401. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28402. ws.send(
  28403. "authorization:" + req.get_header_value("Authorization") +
  28404. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28405. std::string msg;
  28406. while (ws.read(msg)) {
  28407. ws.send(msg);
  28408. }
  28409. }
  28410. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28411. class ScopedWebSocketOrigin {
  28412. public:
  28413. ScopedWebSocketOrigin() {
  28414. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28415. server_.listen();
  28416. }
  28417. int port() const { return server_.port(); }
  28418. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28419. std::string url() const {
  28420. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28421. }
  28422. private:
  28423. no_proxy_test::ScopedServer server_;
  28424. };
  28425. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28426. // passed as a constructor header, and checks that each reaches only its hop.
  28427. void WebSocketCredentialsStayWithTheirHop(
  28428. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28429. const std::string &proxy_authz, const std::string &origin_authz) {
  28430. ScopedWebSocketOrigin origin;
  28431. ScopedConnectProxy proxy(
  28432. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28433. ASSERT_NE(0, proxy.port());
  28434. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28435. client.set_proxy("127.0.0.1", proxy.port());
  28436. set_proxy_credentials(client);
  28437. auto res = client.connect();
  28438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28439. std::string msg;
  28440. ASSERT_TRUE(client.read(msg));
  28441. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28442. client.close();
  28443. EXPECT_EQ(1, proxy.connect_hits());
  28444. EXPECT_EQ(std::string::npos,
  28445. proxy.connect_request().find("\r\nAuthorization: "))
  28446. << "origin credentials must not be sent to the proxy";
  28447. }
  28448. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28449. void WebSocketSetterCredentialsStayWithTheirHop(
  28450. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28451. const std::string &proxy_authz, const std::string &origin_authz) {
  28452. ScopedWebSocketOrigin origin;
  28453. ScopedConnectProxy proxy(
  28454. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28455. ASSERT_NE(0, proxy.port());
  28456. ws::WebSocketClient client(origin.url());
  28457. client.set_proxy("127.0.0.1", proxy.port());
  28458. set_credentials(client);
  28459. auto res = client.connect();
  28460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28461. std::string msg;
  28462. ASSERT_TRUE(client.read(msg));
  28463. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28464. client.close();
  28465. EXPECT_EQ(1, proxy.connect_hits());
  28466. EXPECT_EQ(std::string::npos,
  28467. proxy.connect_request().find("\r\nAuthorization: "))
  28468. << "origin credentials must not be sent to the proxy";
  28469. }
  28470. } // namespace proxy_tunnel_test
  28471. namespace {
  28472. // Connects `client` and returns the Authorization header its upgrade
  28473. // request carried, or "<failed>" when the connection could not be opened.
  28474. std::string websocket_authorization(ws::WebSocketClient &client) {
  28475. if (!client.connect()) { return "<failed>"; }
  28476. std::string msg;
  28477. if (!client.read(msg)) { return "<failed>"; }
  28478. client.close();
  28479. auto prefix = std::string("authorization:");
  28480. auto end = msg.find("|proxy-authorization:");
  28481. return msg.substr(prefix.size(), end - prefix.size());
  28482. }
  28483. } // namespace
  28484. TEST(WebSocketClientAuthTest, BasicAuth) {
  28485. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28486. ws::WebSocketClient client(origin.url());
  28487. client.set_basic_auth("user", "pass");
  28488. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28489. websocket_authorization(client));
  28490. }
  28491. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28492. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28493. ws::WebSocketClient client(origin.url());
  28494. client.set_basic_auth("user", "");
  28495. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28496. websocket_authorization(client));
  28497. }
  28498. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28499. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28500. ws::WebSocketClient client(origin.url());
  28501. client.set_bearer_token_auth("token123");
  28502. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28503. }
  28504. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28505. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28506. ws::WebSocketClient client(origin.url());
  28507. client.set_bearer_token_auth("token123");
  28508. client.set_basic_auth("user", "pass");
  28509. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28510. websocket_authorization(client));
  28511. }
  28512. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28513. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28514. ws::WebSocketClient client(origin.url(),
  28515. {{"Authorization", "Bearer from-header"}});
  28516. client.set_bearer_token_auth("from-setter");
  28517. client.set_basic_auth("user", "pass");
  28518. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28519. }
  28520. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28521. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28522. ws::WebSocketClient client(origin.url());
  28523. EXPECT_EQ("", websocket_authorization(client));
  28524. client.set_bearer_token_auth("first");
  28525. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28526. client.set_bearer_token_auth("second");
  28527. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28528. client.set_bearer_token_auth("");
  28529. EXPECT_EQ("", websocket_authorization(client));
  28530. }
  28531. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28532. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28533. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28534. ASSERT_NE(0, proxy.port());
  28535. ws::WebSocketClient client(origin.url());
  28536. client.set_proxy("127.0.0.1", proxy.port());
  28537. auto res = client.connect();
  28538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28539. std::string msg;
  28540. ASSERT_TRUE(client.read(msg));
  28541. ASSERT_TRUE(client.send("hello"));
  28542. ASSERT_TRUE(client.read(msg));
  28543. EXPECT_EQ("hello", msg);
  28544. client.close();
  28545. EXPECT_EQ(1, proxy.connect_hits());
  28546. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28547. auto connect_req = proxy.connect_request();
  28548. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28549. EXPECT_NE(std::string::npos,
  28550. connect_req.find("\r\nHost: " + target + "\r\n"));
  28551. }
  28552. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28553. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28554. [](ws::WebSocketClient &cli) {
  28555. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28556. },
  28557. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28558. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28559. }
  28560. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28561. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28562. [](ws::WebSocketClient &cli) {
  28563. cli.set_proxy_bearer_token_auth("proxy-token");
  28564. },
  28565. "Bearer proxy-token", "Bearer origin-token");
  28566. }
  28567. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28568. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28569. [](ws::WebSocketClient &cli) {
  28570. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28571. cli.set_basic_auth("origin-user", "origin-pass");
  28572. },
  28573. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28574. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28575. }
  28576. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28577. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28578. [](ws::WebSocketClient &cli) {
  28579. cli.set_proxy_bearer_token_auth("proxy-token");
  28580. cli.set_bearer_token_auth("origin-token");
  28581. },
  28582. "Bearer proxy-token", "Bearer origin-token");
  28583. }
  28584. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28585. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28586. proxy_tunnel_test::ScopedConnectProxy proxy(
  28587. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28588. "Basic " + detail::base64_encode("proxy-user:"),
  28589. "Basic realm=\"proxy\""));
  28590. ASSERT_NE(0, proxy.port());
  28591. ws::WebSocketClient client(origin.url());
  28592. client.set_proxy("127.0.0.1", proxy.port());
  28593. client.set_proxy_basic_auth("proxy-user", "");
  28594. auto res = client.connect();
  28595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28596. client.close();
  28597. EXPECT_EQ(1, proxy.connect_hits());
  28598. }
  28599. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28600. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28601. proxy_tunnel_test::ScopedConnectProxy proxy(
  28602. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28603. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28604. ASSERT_NE(0, proxy.port());
  28605. ws::WebSocketClient client(origin.url());
  28606. client.set_proxy("127.0.0.1", proxy.port());
  28607. auto res = client.connect();
  28608. EXPECT_FALSE(res);
  28609. EXPECT_EQ(Error::ProxyConnection, res.error());
  28610. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28611. EXPECT_EQ("Basic realm=\"proxy\"",
  28612. res.get_header_value("Proxy-Authenticate"));
  28613. EXPECT_FALSE(client.is_open());
  28614. }
  28615. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28616. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28617. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28618. ASSERT_NE(0, proxy.port());
  28619. ws::WebSocketClient client(origin.url());
  28620. client.set_proxy("127.0.0.1", proxy.port());
  28621. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28622. client.set_no_proxy({"127.0.0.1"});
  28623. auto res = client.connect();
  28624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28625. std::string msg;
  28626. ASSERT_TRUE(client.read(msg));
  28627. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28628. << "proxy credentials must not reach a bypassed origin";
  28629. client.close();
  28630. EXPECT_EQ(0, proxy.connect_hits());
  28631. }
  28632. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28633. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28634. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28635. ASSERT_NE(0, proxy.port());
  28636. ws::WebSocketClient client(origin.url());
  28637. client.set_proxy("127.0.0.1", proxy.port());
  28638. ASSERT_TRUE(client.connect());
  28639. ASSERT_TRUE(client.connect());
  28640. client.close();
  28641. EXPECT_EQ(2, proxy.connect_hits());
  28642. }
  28643. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28644. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28645. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28646. ASSERT_NE(0, proxy.port());
  28647. auto port = std::to_string(origin.port());
  28648. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28649. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28650. client.set_proxy("127.0.0.1", proxy.port());
  28651. auto res = client.connect();
  28652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28653. std::string msg;
  28654. ASSERT_TRUE(client.read(msg));
  28655. client.close();
  28656. EXPECT_EQ(1, proxy.connect_hits());
  28657. auto target = "127.0.0.1:" + port;
  28658. auto connect_req = proxy.connect_request();
  28659. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28660. EXPECT_NE(std::string::npos,
  28661. connect_req.find("\r\nHost: " + target + "\r\n"));
  28662. }
  28663. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28664. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28665. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28666. ASSERT_NE(0, proxy.port());
  28667. auto port = std::to_string(origin.port());
  28668. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28669. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28670. client.set_proxy("127.0.0.1", proxy.port());
  28671. auto res = client.connect();
  28672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28673. client.close();
  28674. auto target = "origin.example:" + port;
  28675. auto connect_req = proxy.connect_request();
  28676. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28677. EXPECT_NE(std::string::npos,
  28678. connect_req.find("\r\nHost: " + target + "\r\n"));
  28679. }
  28680. #ifdef CPPHTTPLIB_SSL_ENABLED
  28681. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28682. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28683. proxy_tunnel_test::ScopedConnectProxy proxy(
  28684. origin.port(), [](const std::string &head) -> std::string {
  28685. if (head.find(
  28686. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28687. std::string::npos) {
  28688. return proxy_tunnel_test::kTunnelEstablished;
  28689. }
  28690. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28691. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28692. "nonce=\"abc\", algorithm=MD5\r\n"
  28693. "Content-Length: 0\r\n\r\n";
  28694. });
  28695. ASSERT_NE(0, proxy.port());
  28696. ws::WebSocketClient client(origin.url());
  28697. client.set_proxy("127.0.0.1", proxy.port());
  28698. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28699. auto res = client.connect();
  28700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28701. std::string msg;
  28702. ASSERT_TRUE(client.read(msg));
  28703. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28704. client.close();
  28705. EXPECT_EQ(2, proxy.connect_hits());
  28706. }
  28707. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28708. proxy_tunnel_test::ScopedSSLServer origin;
  28709. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28710. origin.listen();
  28711. proxy_tunnel_test::ScopedConnectProxy proxy(
  28712. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28713. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28714. ASSERT_NE(0, proxy.port());
  28715. ws::WebSocketClient client(
  28716. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28717. client.enable_server_certificate_verification(false);
  28718. client.set_proxy("127.0.0.1", proxy.port());
  28719. client.set_proxy_bearer_token_auth("proxy-token");
  28720. auto res = client.connect();
  28721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28722. std::string msg;
  28723. ASSERT_TRUE(client.read(msg));
  28724. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28725. << "Proxy-Authorization must not be sent inside the tunnel";
  28726. client.close();
  28727. EXPECT_EQ(1, proxy.connect_hits());
  28728. }
  28729. #endif
  28730. // ---------------------------------------------------------------------------
  28731. // Poller
  28732. // ---------------------------------------------------------------------------
  28733. namespace poller_test {
  28734. struct PollerBackend {
  28735. const char *name;
  28736. std::unique_ptr<detail::Poller> (*create)();
  28737. };
  28738. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28739. *os << backend.name;
  28740. }
  28741. // Every backend runs the same contract tests. A new one is added here only.
  28742. std::vector<PollerBackend> poller_backends() {
  28743. return {
  28744. {"poll", &detail::PollPoller::create},
  28745. #ifdef __linux__
  28746. {"epoll", &detail::EpollPoller::create},
  28747. #endif
  28748. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28749. {"kqueue", &detail::KqueuePoller::create},
  28750. #endif
  28751. };
  28752. }
  28753. // A descriptor whose readability the test controls.
  28754. struct TestSocketPair {
  28755. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28756. TestSocketPair() { detail::create_socket_pair(fd); }
  28757. ~TestSocketPair() {
  28758. for (auto s : fd) {
  28759. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28760. }
  28761. }
  28762. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28763. socket_t reader() const { return fd[0]; }
  28764. void make_readable() {
  28765. const char c = 1;
  28766. detail::send_socket(fd[1], &c, 1, 0);
  28767. }
  28768. void close_writer() {
  28769. detail::close_socket(fd[1]);
  28770. fd[1] = INVALID_SOCKET;
  28771. }
  28772. };
  28773. using Tokens = std::vector<detail::Poller::Token>;
  28774. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28775. protected:
  28776. void SetUp() override {
  28777. poller_ = GetParam().create();
  28778. ASSERT_TRUE(poller_ != nullptr);
  28779. }
  28780. Tokens wait_for(int timeout_ms) {
  28781. Tokens ready;
  28782. poller_->wait(timeout_ms, ready);
  28783. std::sort(ready.begin(), ready.end());
  28784. return ready;
  28785. }
  28786. std::unique_ptr<detail::Poller> poller_;
  28787. };
  28788. } // namespace poller_test
  28789. using poller_test::PollerTest;
  28790. using poller_test::TestSocketPair;
  28791. using poller_test::Tokens;
  28792. INSTANTIATE_TEST_SUITE_P(
  28793. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28794. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28795. return std::string(p.param.name);
  28796. });
  28797. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28798. TestSocketPair sp;
  28799. ASSERT_TRUE(sp.ok());
  28800. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28801. EXPECT_EQ(Tokens{}, wait_for(0));
  28802. sp.make_readable();
  28803. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28804. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28805. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28806. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28807. }
  28808. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28809. TestSocketPair sp;
  28810. ASSERT_TRUE(sp.ok());
  28811. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28812. poller_->disarm(sp.reader());
  28813. poller_->disarm(sp.reader()); // disarming twice is harmless
  28814. sp.make_readable();
  28815. EXPECT_EQ(Tokens{}, wait_for(0));
  28816. }
  28817. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28818. TestSocketPair sp;
  28819. ASSERT_TRUE(sp.ok());
  28820. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28821. auto start = std::chrono::steady_clock::now();
  28822. EXPECT_EQ(Tokens{}, wait_for(30));
  28823. auto elapsed = std::chrono::steady_clock::now() - start;
  28824. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28825. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28826. }
  28827. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28828. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28829. for (detail::Poller::Token i = 0; i < 8; i++) {
  28830. sps.emplace_back(new TestSocketPair());
  28831. ASSERT_TRUE(sps.back()->ok());
  28832. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28833. }
  28834. sps[0]->make_readable();
  28835. sps[3]->make_readable();
  28836. sps[7]->make_readable();
  28837. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28838. // The others are still armed, the delivered ones are not.
  28839. sps[1]->make_readable();
  28840. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28841. EXPECT_EQ(Tokens{}, wait_for(0));
  28842. }
  28843. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28844. TestSocketPair s0, s1, s2;
  28845. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28846. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28847. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28848. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28849. // A delivery may move another entry inside the poller.
  28850. s0.make_readable();
  28851. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28852. // The entries left must still be found by descriptor.
  28853. poller_->disarm(s2.reader());
  28854. s1.make_readable();
  28855. s2.make_readable();
  28856. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28857. }
  28858. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  28859. TestSocketPair sp;
  28860. ASSERT_TRUE(sp.ok());
  28861. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  28862. sp.close_writer();
  28863. EXPECT_EQ(Tokens{5}, wait_for(1000));
  28864. char c;
  28865. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  28866. }
  28867. TEST_P(PollerTest, WakeEndsABlockedWait) {
  28868. std::thread waker([&] {
  28869. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  28870. poller_->wake();
  28871. });
  28872. Tokens ready;
  28873. auto start = std::chrono::steady_clock::now();
  28874. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  28875. waker.join();
  28876. EXPECT_TRUE(ready.empty());
  28877. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  28878. }
  28879. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  28880. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  28881. Tokens ready;
  28882. EXPECT_TRUE(poller_->wait(1000, ready));
  28883. }
  28884. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  28885. for (int i = 0; i < 1000; i++) {
  28886. poller_->wake();
  28887. }
  28888. Tokens ready;
  28889. EXPECT_TRUE(poller_->wait(0, ready));
  28890. EXPECT_FALSE(poller_->wait(0, ready));
  28891. poller_->wake();
  28892. EXPECT_TRUE(poller_->wait(0, ready));
  28893. }
  28894. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  28895. // Two threads publish changes and wake() after each, as a reactor's workers
  28896. // do. Every change must be seen without a wait() timing out. A lost wake()
  28897. // needs an unlucky interleaving, hence the rounds.
  28898. for (int round = 0; round < 5; round++) {
  28899. SCOPED_TRACE(round);
  28900. const int per_thread = 20000;
  28901. std::atomic<int> posted{0};
  28902. auto post = [&] {
  28903. for (int i = 0; i < per_thread; i++) {
  28904. posted++;
  28905. poller_->wake();
  28906. }
  28907. };
  28908. std::thread t1(post), t2(post);
  28909. auto lost = false;
  28910. Tokens ready;
  28911. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  28912. if (!poller_->wait(1000, ready)) {
  28913. lost = true;
  28914. break;
  28915. }
  28916. }
  28917. t1.join();
  28918. t2.join();
  28919. ASSERT_FALSE(lost);
  28920. }
  28921. }
  28922. TEST(PollerFactoryTest, MakePollerWorks) {
  28923. auto poller = detail::make_poller();
  28924. ASSERT_TRUE(poller != nullptr);
  28925. poller->wake();
  28926. std::vector<detail::Poller::Token> ready;
  28927. EXPECT_TRUE(poller->wait(1000, ready));
  28928. }
  28929. // ---------------------------------------------------------------------------
  28930. // Keep-alive parking
  28931. // ---------------------------------------------------------------------------
  28932. namespace parking_test {
  28933. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  28934. // runs once the port is bound and listening, before the server accepts.
  28935. struct RunningServer {
  28936. explicit RunningServer(
  28937. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  28938. : svr_(svr) {
  28939. port = svr_.bind_to_any_port("127.0.0.1");
  28940. if (before_listen) { before_listen(port); }
  28941. thread = std::thread([this] { svr_.listen_after_bind(); });
  28942. svr_.wait_until_ready();
  28943. }
  28944. ~RunningServer() {
  28945. svr_.stop();
  28946. if (thread.joinable()) { thread.join(); }
  28947. }
  28948. Server &svr_;
  28949. int port = 0;
  28950. std::thread thread;
  28951. };
  28952. struct Sockets {
  28953. std::vector<socket_t> socks;
  28954. ~Sockets() {
  28955. for (auto s : socks) {
  28956. detail::close_socket(s);
  28957. }
  28958. }
  28959. socket_t connect(int port) {
  28960. auto error = Error::Success;
  28961. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  28962. false, false, nullptr, 2, 0, 2, 0, 2,
  28963. 0, std::string(), error);
  28964. if (s != INVALID_SOCKET) { socks.push_back(s); }
  28965. return s;
  28966. }
  28967. };
  28968. std::chrono::steady_clock::time_point in_ms(int ms) {
  28969. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  28970. }
  28971. bool readable_by(socket_t sock,
  28972. std::chrono::steady_clock::time_point deadline) {
  28973. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  28974. deadline - std::chrono::steady_clock::now())
  28975. .count();
  28976. return left > 0 && detail::select_read(sock, 0, left) > 0;
  28977. }
  28978. bool send_get(socket_t sock, const std::string &path = "/") {
  28979. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  28980. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  28981. static_cast<ssize_t>(req.size());
  28982. }
  28983. // Reads one response whose body is "ok".
  28984. bool receives_ok(socket_t sock, int timeout_ms) {
  28985. auto deadline = in_ms(timeout_ms);
  28986. std::string buf;
  28987. while (readable_by(sock, deadline)) {
  28988. char tmp[1024];
  28989. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  28990. if (n <= 0) { return false; }
  28991. buf.append(tmp, static_cast<size_t>(n));
  28992. auto end = buf.find("\r\n\r\n");
  28993. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  28994. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  28995. buf.compare(end + 4, 2, "ok") == 0;
  28996. }
  28997. }
  28998. return false;
  28999. }
  29000. bool get_ok(socket_t sock, int timeout_ms) {
  29001. return send_get(sock) && receives_ok(sock, timeout_ms);
  29002. }
  29003. // Whether the server closes `sock` by `deadline`.
  29004. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29005. char c;
  29006. return readable_by(sock, deadline) &&
  29007. detail::read_socket(sock, &c, 1, 0) <= 0;
  29008. }
  29009. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29010. auto deadline = in_ms(timeout_ms);
  29011. while (!cond()) {
  29012. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29013. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29014. }
  29015. return true;
  29016. }
  29017. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29018. svr.new_task_queue = std::move(new_task_queue);
  29019. svr.set_keep_alive_parking(true);
  29020. svr.Get("/", [](const Request &, Response &res) {
  29021. res.set_content("ok", "text/plain");
  29022. });
  29023. }
  29024. std::function<TaskQueue *(void)> threads(size_t n) {
  29025. return [n] { return new ThreadPool(n); };
  29026. }
  29027. // Counts what the event loop managed to queue, so that a test can wait for it.
  29028. class CountingTaskQueue final : public TaskQueue {
  29029. public:
  29030. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29031. std::atomic<int> &full)
  29032. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29033. bool enqueue(std::function<void()> fn) override {
  29034. auto queued = pool_.enqueue([this, fn]() {
  29035. fn();
  29036. // Holds the worker back from taking the next job.
  29037. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29038. });
  29039. (queued ? ok_ : full_)++;
  29040. return queued;
  29041. }
  29042. void shutdown() override { pool_.shutdown(); }
  29043. std::atomic<int> pause_after_ms{0};
  29044. private:
  29045. ThreadPool pool_;
  29046. std::atomic<int> &ok_;
  29047. std::atomic<int> &full_;
  29048. };
  29049. // Holds handlers until it opens, or for 3 seconds at most.
  29050. class Gate {
  29051. public:
  29052. void wait() {
  29053. std::unique_lock<std::mutex> lock(m_);
  29054. entered_++;
  29055. cv_.notify_all();
  29056. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29057. }
  29058. void open() {
  29059. std::lock_guard<std::mutex> guard(m_);
  29060. open_ = true;
  29061. cv_.notify_all();
  29062. }
  29063. int entered() {
  29064. std::lock_guard<std::mutex> guard(m_);
  29065. return entered_;
  29066. }
  29067. private:
  29068. std::mutex m_;
  29069. std::condition_variable cv_;
  29070. bool open_ = false;
  29071. int entered_ = 0;
  29072. };
  29073. } // namespace parking_test
  29074. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29075. using namespace parking_test;
  29076. Server svr;
  29077. serve_ok(svr, threads(1));
  29078. RunningServer running(svr);
  29079. Sockets socks;
  29080. // One kept-alive connection that has been served, and many that have not
  29081. // sent anything yet. None of them may keep the only worker.
  29082. auto served = socks.connect(running.port);
  29083. ASSERT_TRUE(get_ok(served, 2000));
  29084. for (int i = 0; i < 49; i++) {
  29085. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29086. }
  29087. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29088. EXPECT_TRUE(get_ok(served, 1000));
  29089. }
  29090. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29091. using namespace parking_test;
  29092. Server svr;
  29093. serve_ok(svr, threads(1));
  29094. svr.set_keep_alive_timeout(1);
  29095. RunningServer running(svr);
  29096. Sockets socks;
  29097. for (int i = 0; i < 3; i++) {
  29098. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29099. }
  29100. // One worker waiting on each in turn would take about 3 seconds.
  29101. auto deadline = in_ms(2000);
  29102. for (auto s : socks.socks) {
  29103. EXPECT_TRUE(sees_eof(s, deadline));
  29104. }
  29105. }
  29106. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29107. using namespace parking_test;
  29108. std::atomic<int> queued{0}, full{0};
  29109. Server svr;
  29110. // One worker and room for one queued task.
  29111. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29112. Gate gate;
  29113. svr.Get("/block", [&](const Request &, Response &res) {
  29114. gate.wait();
  29115. res.set_content("ok", "text/plain");
  29116. });
  29117. RunningServer running(svr);
  29118. // Before the server stops, so that a failed run does not wait for the
  29119. // handler's timeout.
  29120. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29121. Sockets socks;
  29122. auto a = socks.connect(running.port);
  29123. ASSERT_TRUE(get_ok(a, 2000));
  29124. // B keeps the only worker busy.
  29125. auto b = socks.connect(running.port);
  29126. ASSERT_TRUE(send_get(b, "/block"));
  29127. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29128. // A new connection C fills the queue.
  29129. auto c = socks.connect(running.port);
  29130. ASSERT_TRUE(send_get(c));
  29131. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29132. // A's next request finds the queue full, but A has been served before, so it
  29133. // waits instead of being cut off.
  29134. ASSERT_TRUE(send_get(a));
  29135. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29136. gate.open();
  29137. EXPECT_TRUE(receives_ok(b, 2000));
  29138. EXPECT_TRUE(receives_ok(c, 2000));
  29139. EXPECT_TRUE(receives_ok(a, 2000));
  29140. }
  29141. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29142. using namespace parking_test;
  29143. std::atomic<int> queued{0}, full{0};
  29144. CountingTaskQueue *queue = nullptr;
  29145. Server svr;
  29146. // Two workers and room for one queued task.
  29147. serve_ok(svr,
  29148. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29149. Gate first, second;
  29150. svr.Get("/first", [&](const Request &, Response &res) {
  29151. first.wait();
  29152. res.set_content("ok", "text/plain");
  29153. });
  29154. svr.Get("/second", [&](const Request &, Response &res) {
  29155. second.wait();
  29156. res.set_content("ok", "text/plain");
  29157. });
  29158. RunningServer running(svr);
  29159. auto open_gates = detail::scope_exit([&] {
  29160. first.open();
  29161. second.open();
  29162. });
  29163. Sockets socks;
  29164. auto a = socks.connect(running.port);
  29165. ASSERT_TRUE(get_ok(a, 2000));
  29166. // B and D take both workers, and C fills the queue. One at a time: the
  29167. // queue has room for one job only until a worker takes it.
  29168. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29169. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29170. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29171. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29172. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29173. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29174. // A's next request waits in the backlog.
  29175. ASSERT_TRUE(send_get(a));
  29176. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29177. // B's worker finishes, then takes C off the queue only later, which makes
  29178. // room for A.
  29179. queue->pause_after_ms = 200;
  29180. first.open();
  29181. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29182. queue->pause_after_ms = 0;
  29183. second.open();
  29184. EXPECT_TRUE(receives_ok(a, 2000));
  29185. }
  29186. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29187. using namespace parking_test;
  29188. Server svr;
  29189. serve_ok(svr, threads(1));
  29190. svr.set_keep_alive_timeout(0);
  29191. // The request is on the socket before the server accepts the connection,
  29192. // so it does not race the 10 ms floor. Without the floor the connection is
  29193. // closed unread.
  29194. Sockets socks;
  29195. auto sock = INVALID_SOCKET;
  29196. RunningServer running(svr, [&](int port) {
  29197. sock = socks.connect(port);
  29198. send_get(sock);
  29199. });
  29200. EXPECT_TRUE(receives_ok(sock, 1000));
  29201. }
  29202. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29203. using namespace parking_test;
  29204. for (int round = 0; round < 5; round++) {
  29205. SCOPED_TRACE(round);
  29206. Server svr;
  29207. serve_ok(svr, threads(2));
  29208. RunningServer running(svr);
  29209. Sockets socks;
  29210. for (int i = 0; i < 20; i++) {
  29211. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29212. }
  29213. auto start = std::chrono::steady_clock::now();
  29214. svr.stop();
  29215. running.thread.join();
  29216. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29217. std::chrono::milliseconds(500));
  29218. auto deadline = in_ms(1000);
  29219. for (auto s : socks.socks) {
  29220. EXPECT_TRUE(sees_eof(s, deadline));
  29221. }
  29222. }
  29223. }
  29224. #ifdef CPPHTTPLIB_SSL_ENABLED
  29225. namespace parking_test {
  29226. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29227. // that has opened a connection ahead of time. Freeing the session sends no
  29228. // close_notify, so the connection stays quiet.
  29229. bool handshake_only(socket_t sock) {
  29230. auto ctx = tls::create_client_context();
  29231. tls::set_verify_client(ctx, false);
  29232. auto session = tls::create_session(ctx, sock);
  29233. auto se = detail::scope_exit([&] {
  29234. tls::free_session(session);
  29235. tls::free_context(ctx);
  29236. });
  29237. tls::TlsError err;
  29238. return session &&
  29239. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29240. }
  29241. Client tls_client(int port) {
  29242. Client cli("https://127.0.0.1:" + std::to_string(port));
  29243. cli.enable_server_certificate_verification(false);
  29244. cli.set_keep_alive(true);
  29245. cli.set_connection_timeout(1);
  29246. cli.set_read_timeout(1);
  29247. return cli;
  29248. }
  29249. bool tls_get_ok(Client &cli) {
  29250. auto res = cli.Get("/");
  29251. return res && res->body == "ok";
  29252. }
  29253. } // namespace parking_test
  29254. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29255. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29256. struct {
  29257. unsigned long version;
  29258. bool safe;
  29259. } cases[] = {
  29260. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29261. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29262. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29263. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29264. };
  29265. for (const auto &c : cases) {
  29266. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29267. << std::hex << c.version;
  29268. }
  29269. }
  29270. #endif
  29271. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29272. using namespace parking_test;
  29273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29274. ASSERT_TRUE(svr.is_valid());
  29275. serve_ok(svr, threads(1));
  29276. svr.set_read_timeout(1); // so that a failing run does not take long
  29277. RunningServer running(svr);
  29278. Sockets socks;
  29279. // One served connection, some that have not started their handshake, and
  29280. // one that has finished it and gone quiet. None may keep the only worker.
  29281. auto served = tls_client(running.port);
  29282. ASSERT_TRUE(tls_get_ok(served));
  29283. for (int i = 0; i < 10; i++) {
  29284. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29285. }
  29286. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29287. auto other = tls_client(running.port);
  29288. EXPECT_TRUE(tls_get_ok(other));
  29289. EXPECT_TRUE(tls_get_ok(served));
  29290. }
  29291. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29292. using namespace parking_test;
  29293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29294. ASSERT_TRUE(svr.is_valid());
  29295. serve_ok(svr, threads(1));
  29296. RunningServer running(svr);
  29297. Sockets socks;
  29298. auto plain = socks.connect(running.port);
  29299. ASSERT_TRUE(send_get(plain));
  29300. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29301. EXPECT_NE(0, svr.ssl_last_error());
  29302. }
  29303. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29304. using namespace parking_test;
  29305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29306. ASSERT_TRUE(svr.is_valid());
  29307. serve_ok(svr, threads(2));
  29308. RunningServer running(svr);
  29309. std::vector<Client> clients;
  29310. for (int i = 0; i < 5; i++) {
  29311. clients.push_back(tls_client(running.port));
  29312. ASSERT_TRUE(tls_get_ok(clients.back()));
  29313. }
  29314. auto start = std::chrono::steady_clock::now();
  29315. svr.stop();
  29316. running.thread.join();
  29317. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29318. std::chrono::milliseconds(500));
  29319. }
  29320. #endif