test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // httpbingo.org intermittently answers with gateway errors unrelated to the
  145. // client under test.
  146. static bool is_gateway_error(const Result &res) {
  147. return res && (res->status == StatusCode::BadGateway_502 ||
  148. res->status == StatusCode::ServiceUnavailable_503 ||
  149. res->status == StatusCode::GatewayTimeout_504);
  150. }
  151. template <typename F> static Result retry_gateway_errors(F &&send) {
  152. auto res = send();
  153. for (auto wait : {1, 2}) {
  154. if (!is_gateway_error(res)) { break; }
  155. std::this_thread::sleep_for(std::chrono::seconds(wait));
  156. res = send();
  157. }
  158. return res;
  159. }
  160. #define SKIP_ON_GATEWAY_ERROR(res) \
  161. do { \
  162. if (is_gateway_error(res)) { \
  163. GTEST_SKIP() << "gateway error " << (res)->status; \
  164. } \
  165. } while (0)
  166. class UnixSocketTest : public ::testing::Test {
  167. protected:
  168. void TearDown() override { std::remove(pathname_.c_str()); }
  169. void client_GET(const std::string &addr) {
  170. httplib::Client cli{addr};
  171. cli.set_address_family(AF_UNIX);
  172. ASSERT_TRUE(cli.is_valid());
  173. const auto &result = cli.Get(pattern_);
  174. ASSERT_TRUE(result) << "error: " << result.error();
  175. const auto &resp = result.value();
  176. EXPECT_EQ(resp.status, StatusCode::OK_200);
  177. EXPECT_EQ(resp.body, content_);
  178. }
  179. static std::string make_sock_path() {
  180. const char *shard = getenv("GTEST_SHARD_INDEX");
  181. return shard ? std::string("./httplib-server-") + shard + ".sock"
  182. : "./httplib-server.sock";
  183. }
  184. const std::string pathname_{make_sock_path()};
  185. const std::string pattern_{"/hi"};
  186. const std::string content_{"Hello World!"};
  187. };
  188. TEST_F(UnixSocketTest, pathname) {
  189. httplib::Server svr;
  190. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  191. res.set_content(content_, "text/plain");
  192. });
  193. std::thread t{[&] {
  194. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  195. }};
  196. auto se = detail::scope_exit([&] {
  197. svr.stop();
  198. t.join();
  199. ASSERT_FALSE(svr.is_running());
  200. });
  201. svr.wait_until_ready();
  202. ASSERT_TRUE(svr.is_running());
  203. client_GET(pathname_);
  204. // ".//x.sock", which is not taken for a URL
  205. client_GET("./" + pathname_.substr(1));
  206. }
  207. #if defined(__linux__) || \
  208. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  209. TEST_F(UnixSocketTest, PeerPid) {
  210. httplib::Server svr;
  211. std::string remote_port_val;
  212. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  213. res.set_content(content_, "text/plain");
  214. remote_port_val = std::to_string(req.remote_port);
  215. });
  216. std::thread t{[&] {
  217. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  218. }};
  219. auto se = detail::scope_exit([&] {
  220. svr.stop();
  221. t.join();
  222. ASSERT_FALSE(svr.is_running());
  223. });
  224. svr.wait_until_ready();
  225. ASSERT_TRUE(svr.is_running());
  226. client_GET(pathname_);
  227. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  228. }
  229. #endif
  230. #ifdef __linux__
  231. TEST_F(UnixSocketTest, abstract) {
  232. constexpr char svr_path[]{"\x00httplib-server.sock"};
  233. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  234. httplib::Server svr;
  235. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  236. res.set_content(content_, "text/plain");
  237. });
  238. std::thread t{[&] {
  239. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  240. }};
  241. auto se = detail::scope_exit([&] {
  242. svr.stop();
  243. t.join();
  244. ASSERT_FALSE(svr.is_running());
  245. });
  246. svr.wait_until_ready();
  247. ASSERT_TRUE(svr.is_running());
  248. client_GET(abstract_addr);
  249. }
  250. #endif
  251. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  252. httplib::Server svr;
  253. std::string received_host_header;
  254. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  255. // Capture the Host header sent by the client
  256. auto host_iter = req.headers.find("Host");
  257. if (host_iter != req.headers.end()) {
  258. received_host_header = host_iter->second;
  259. }
  260. res.set_content(content_, "text/plain");
  261. });
  262. std::thread t{[&] {
  263. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  264. }};
  265. auto se = detail::scope_exit([&] {
  266. svr.stop();
  267. t.join();
  268. ASSERT_FALSE(svr.is_running());
  269. });
  270. svr.wait_until_ready();
  271. ASSERT_TRUE(svr.is_running());
  272. // Test that Host header is automatically set to "localhost" for Unix socket
  273. // connections
  274. httplib::Client cli{pathname_};
  275. cli.set_address_family(AF_UNIX);
  276. ASSERT_TRUE(cli.is_valid());
  277. const auto &result = cli.Get(pattern_);
  278. ASSERT_TRUE(result) << "error: " << result.error();
  279. const auto &resp = result.value();
  280. EXPECT_EQ(resp.status, StatusCode::OK_200);
  281. EXPECT_EQ(resp.body, content_);
  282. // Verify that Host header was automatically set to "localhost"
  283. EXPECT_EQ(received_host_header, "localhost");
  284. }
  285. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  286. // Another socket in the working directory, which a Location can name as
  287. // its host
  288. const auto other_path = "other-" + pathname_.substr(2);
  289. httplib::Server svr;
  290. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  291. // An absolute Location naming the Host this client sends
  292. res.set_redirect("http://localhost" + pattern_);
  293. });
  294. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  295. res.set_redirect("http://" + other_path + pattern_);
  296. });
  297. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  298. res.set_redirect("http://mapped.test" + pattern_);
  299. });
  300. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  301. res.set_header("X-Auth", req.get_header_value("Authorization"));
  302. res.set_content(content_, "text/plain");
  303. });
  304. httplib::Server other;
  305. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  306. res.set_content("other", "text/plain");
  307. });
  308. std::thread t{[&] {
  309. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  310. }};
  311. std::thread t2{[&] {
  312. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  313. }};
  314. auto se = detail::scope_exit([&] {
  315. svr.stop();
  316. other.stop();
  317. t.join();
  318. t2.join();
  319. std::remove(other_path.c_str());
  320. });
  321. svr.wait_until_ready();
  322. other.wait_until_ready();
  323. httplib::Client cli{pathname_};
  324. cli.set_address_family(AF_UNIX);
  325. cli.set_follow_location(true);
  326. cli.set_bearer_token_auth("token");
  327. // Another host: the same socket, without the credentials
  328. auto res = cli.Get("/cross");
  329. ASSERT_TRUE(res) << "error: " << res.error();
  330. EXPECT_EQ(StatusCode::OK_200, res->status);
  331. EXPECT_EQ(content_, res->body);
  332. EXPECT_EQ("", res->get_header_value("X-Auth"));
  333. // localhost is this client's own host
  334. res = cli.Get("/redirect");
  335. ASSERT_TRUE(res) << "error: " << res.error();
  336. EXPECT_EQ(StatusCode::OK_200, res->status);
  337. EXPECT_EQ(content_, res->body);
  338. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  339. // A host the caller mapped to a socket goes there
  340. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  341. res = cli.Get("/mapped");
  342. ASSERT_TRUE(res) << "error: " << res.error();
  343. EXPECT_EQ(StatusCode::OK_200, res->status);
  344. EXPECT_EQ("other", res->body);
  345. }
  346. #ifndef _WIN32
  347. TEST(SocketStream, wait_writable_UNIX) {
  348. int fds[2];
  349. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  350. const auto asSocketStream = [&](socket_t fd,
  351. std::function<bool(Stream &)> func) {
  352. return detail::process_client_socket(
  353. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  354. };
  355. asSocketStream(fds[0], [&](Stream &s0) {
  356. EXPECT_EQ(s0.socket(), fds[0]);
  357. EXPECT_TRUE(s0.wait_writable());
  358. EXPECT_TRUE(s0.is_peer_alive());
  359. EXPECT_EQ(0, close(fds[1]));
  360. EXPECT_FALSE(s0.is_peer_alive());
  361. return true;
  362. });
  363. EXPECT_EQ(0, close(fds[0]));
  364. }
  365. TEST(SocketStream, wait_writable_INET) {
  366. sockaddr_in addr;
  367. memset(&addr, 0, sizeof(addr));
  368. addr.sin_family = AF_INET;
  369. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  370. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  371. int disconnected_svr_sock = -1;
  372. std::thread svr{[&] {
  373. const int s = socket(AF_INET, SOCK_STREAM, 0);
  374. ASSERT_LE(0, s);
  375. // PORT + 1 is shared with the SSL redirect tests and with
  376. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  377. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  378. // because that happens on a worker thread the ASSERT does not stop the
  379. // test: it runs on and fails at the disconnected_svr_sock check instead.
  380. default_socket_options(s);
  381. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  382. ASSERT_EQ(0, listen(s, 1));
  383. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  384. ASSERT_EQ(0, close(s));
  385. }};
  386. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  387. std::thread cli{[&] {
  388. const int s = socket(AF_INET, SOCK_STREAM, 0);
  389. ASSERT_LE(0, s);
  390. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  391. ASSERT_EQ(0, close(s));
  392. }};
  393. cli.join();
  394. svr.join();
  395. ASSERT_NE(disconnected_svr_sock, -1);
  396. const auto asSocketStream = [&](socket_t fd,
  397. std::function<bool(Stream &)> func) {
  398. return detail::process_client_socket(
  399. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  400. };
  401. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  402. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  403. // wait_writable() returns true because select_write() only checks if the
  404. // send buffer has space. Peer disconnection is detected later by send().
  405. EXPECT_TRUE(ss.wait_writable());
  406. return true;
  407. });
  408. ASSERT_EQ(0, close(disconnected_svr_sock));
  409. }
  410. #endif // #ifndef _WIN32
  411. TEST(SetSocketOptTest, TcpNoDelay) {
  412. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  413. ASSERT_NE(sock, INVALID_SOCKET);
  414. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  415. int val = 0;
  416. socklen_t len = sizeof(val);
  417. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  418. reinterpret_cast<char *>(&val), &len));
  419. EXPECT_NE(val, 0);
  420. detail::close_socket(sock);
  421. }
  422. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  423. // accept() reports failures through WSAGetLastError() on Windows and through
  424. // errno everywhere else. Asking the wrong one is what made the accept loop
  425. // treat every recoverable failure as fatal on Windows.
  426. struct Classification {
  427. bool resource;
  428. bool transient;
  429. };
  430. auto classify = [](int err) {
  431. #ifdef _WIN32
  432. WSASetLastError(err);
  433. #else
  434. errno = err;
  435. #endif
  436. // Read both before asserting: an assertion may clobber the error slot.
  437. Classification c;
  438. c.resource = detail::is_accept_resource_error();
  439. c.transient = detail::is_accept_transient_error();
  440. return c;
  441. };
  442. #ifdef _WIN32
  443. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  444. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  445. WSAECONNRESET, WSAECONNABORTED};
  446. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  447. #else
  448. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  449. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  450. ECONNABORTED};
  451. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  452. #endif
  453. for (auto err : resource_errors) {
  454. const auto c = classify(err);
  455. EXPECT_TRUE(c.resource) << "error " << err;
  456. EXPECT_FALSE(c.transient) << "error " << err;
  457. }
  458. for (auto err : transient_errors) {
  459. const auto c = classify(err);
  460. EXPECT_TRUE(c.transient) << "error " << err;
  461. EXPECT_FALSE(c.resource) << "error " << err;
  462. }
  463. for (auto err : fatal_errors) {
  464. const auto c = classify(err);
  465. EXPECT_FALSE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. #ifdef _WIN32
  469. WSASetLastError(0);
  470. #else
  471. errno = 0;
  472. #endif
  473. }
  474. TEST(ClientTest, MoveConstructible) {
  475. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  476. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  477. }
  478. TEST(ClientTest, MoveAssignable) {
  479. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  480. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  481. }
  482. #ifdef _WIN32
  483. TEST(StartupTest, WSAStartup) {
  484. WSADATA wsaData;
  485. int ret = WSAStartup(0x0002, &wsaData);
  486. ASSERT_EQ(0, ret);
  487. }
  488. #endif
  489. TEST(DecodePathTest, PercentCharacter) {
  490. EXPECT_EQ(
  491. decode_path_component(
  492. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  493. U8("descrip=Gastos áéíóúñÑ 6"));
  494. }
  495. TEST(DecodePathTest, PercentCharacterNUL) {
  496. string expected;
  497. expected.push_back('x');
  498. expected.push_back('\0');
  499. expected.push_back('x');
  500. EXPECT_EQ(decode_path_component("x%00x"), expected);
  501. }
  502. TEST(DecodePathTest, UnicodeEncoding) {
  503. // %u0041 = 'A' (1-byte UTF-8)
  504. EXPECT_EQ("A", decode_path_component("%u0041"));
  505. // %u00E9 = 'é' (2-byte UTF-8)
  506. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  507. // %u3042 = 'あ' (3-byte UTF-8)
  508. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  509. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  510. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  511. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  512. // neighbours)
  513. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  514. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  515. }
  516. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  517. // A sign or whitespace inside the two-character escape window must not be
  518. // accepted as a valid percent-encoding; the sequence is passed through
  519. // literally, matching decode_uri_component / decode_path_component.
  520. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  521. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  522. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  523. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  524. // Well-formed escapes still decode.
  525. EXPECT_EQ("-", decode_query_component("%2D", false));
  526. EXPECT_EQ("A", decode_query_component("%41", false));
  527. }
  528. TEST(SanitizeFilenameTest, VariousPatterns) {
  529. // Path traversal
  530. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  531. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  532. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  533. // Normal and edge cases
  534. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  535. EXPECT_EQ("filename.txt",
  536. httplib::sanitize_filename("/path/to/filename.txt"));
  537. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  538. EXPECT_EQ("", httplib::sanitize_filename(".."));
  539. EXPECT_EQ("", httplib::sanitize_filename(""));
  540. // Null bytes stripped
  541. EXPECT_EQ("safe.txt",
  542. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  543. // Whitespace-only rejected
  544. EXPECT_EQ("", httplib::sanitize_filename(" "));
  545. }
  546. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  547. // before it is dropped; anywhere else it is an ordinary file name character.
  548. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  549. #ifdef _WIN32
  550. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  551. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  552. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  553. #else
  554. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  555. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  556. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  557. #endif
  558. }
  559. // Forward declaration (see the base64_encode note below): split builds move the
  560. // definition into httplib.cc, so re-declaring it here lets the test link.
  561. namespace httplib {
  562. namespace detail {
  563. bool is_chunked_transfer_encoding(const Headers &headers);
  564. } // namespace detail
  565. } // namespace httplib
  566. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  567. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  568. auto make = [](std::initializer_list<const char *> lines) {
  569. Headers h;
  570. for (auto te : lines) {
  571. if (te) { h.emplace("Transfer-Encoding", te); }
  572. }
  573. return h;
  574. };
  575. // Sole coding, matched case-insensitively.
  576. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  577. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  578. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  579. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  580. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  581. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  582. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  583. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  584. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  585. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  586. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  587. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  588. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  589. // were received, into one list. Headers preserves that order, so the answer
  590. // is decided by the last coding of the last line and the order the lines
  591. // arrived in is significant.
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  593. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  595. // The split can fall anywhere in the list.
  596. EXPECT_TRUE(
  597. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  598. EXPECT_FALSE(
  599. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  600. // A trailing line naming no coding leaves the list ending in nothing, so it
  601. // must not inherit the chunked from the line before it.
  602. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  603. }
  604. // Forward declarations (see the base64_encode note below).
  605. namespace httplib {
  606. namespace detail {
  607. bool parse_status_line(const char *line, std::string &version, int &status,
  608. std::string &reason);
  609. std::string file_extension(const std::string &path);
  610. std::string
  611. find_content_type(const std::string &path,
  612. const std::map<std::string, std::string> &user_data,
  613. const std::string &default_content_type);
  614. bool can_compress_content_type(const std::string &content_type);
  615. bool is_prohibited_header_name(const std::string &name);
  616. bool is_valid_path(const std::string &path);
  617. #ifdef CPPHTTPLIB_SSL_ENABLED
  618. bool match_hostname(const std::string &pattern, const std::string &hostname);
  619. #endif
  620. } // namespace detail
  621. } // namespace httplib
  622. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  623. struct {
  624. const char *line;
  625. const char *version;
  626. int status;
  627. const char *reason;
  628. } cases[] = {
  629. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  630. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  631. // The reason phrase may be empty, or left out along with its space.
  632. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  633. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  634. };
  635. for (const auto &c : cases) {
  636. std::string version;
  637. int status = 0;
  638. std::string reason = "unset";
  639. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  640. << c.line;
  641. EXPECT_EQ(c.version, version);
  642. EXPECT_EQ(c.status, status);
  643. EXPECT_EQ(c.reason, reason);
  644. }
  645. }
  646. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  647. const char *lines[] = {
  648. "HTTP/2 200 OK\r\n",
  649. "HTTP/1.2 200 OK\r\n",
  650. "HTTP/1.1 20 OK\r\n",
  651. "HTTP/1.1 2000 OK\r\n",
  652. "HTTP/1.1 2x0 OK\r\n",
  653. "HTTP/1.1 200 OK\r\n",
  654. "HTTP/1.1 200OK\r\n",
  655. "HTTP/1.1 200 O\rK\r\n",
  656. "HTTP/1.1 200 OK",
  657. "HTTP/1.1 200 OK\r\nX",
  658. "",
  659. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  660. "HTTP/1.1 200 OK\n",
  661. #endif
  662. };
  663. for (auto line : lines) {
  664. std::string version;
  665. int status = 0;
  666. std::string reason;
  667. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  668. << line;
  669. }
  670. }
  671. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  672. // Long enough to overflow the stack when matched with std::regex.
  673. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  674. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  675. std::string version;
  676. int status = 0;
  677. std::string reason;
  678. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  679. EXPECT_EQ(200, status);
  680. EXPECT_EQ(long_reason, reason);
  681. }
  682. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  683. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  684. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  685. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  686. EXPECT_EQ("", detail::file_extension("noext"));
  687. EXPECT_EQ("", detail::file_extension("a."));
  688. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  689. EXPECT_EQ("", detail::file_extension("a.b-c"));
  690. // Long enough to overflow the stack when matched with std::regex.
  691. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  692. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  693. }
  694. #ifdef CPPHTTPLIB_SSL_ENABLED
  695. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  696. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  697. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  698. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  699. // A wildcard needs two labels after it, in the leftmost label only
  700. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  701. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  702. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  703. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  704. EXPECT_FALSE(
  705. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  706. // No name may have an empty label
  707. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  708. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  709. }
  710. #endif
  711. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  712. detail::case_ignore::hash hash;
  713. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  714. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  715. // Long enough to overflow the stack if hashed one call per character.
  716. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  717. }
  718. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  719. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  720. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  721. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  722. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  723. // Same 26-bit hash as html, svg and js.
  724. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  725. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  726. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  727. }
  728. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  729. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  730. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  731. }
  732. }
  733. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  734. // name anywhere else.
  735. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  736. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  737. #ifdef _WIN32
  738. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  739. #else
  740. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  741. #endif
  742. }
  743. }
  744. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  745. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  746. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  747. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  748. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  749. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  750. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  751. // Same 26-bit hash as application/json.
  752. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  753. }
  754. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  755. Request req;
  756. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  757. EXPECT_TRUE(req.is_multipart_form_data());
  758. std::string boundary;
  759. EXPECT_TRUE(detail::parse_multipart_boundary(
  760. req.get_header_value("Content-Type"), boundary));
  761. EXPECT_EQ("x", boundary);
  762. }
  763. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  764. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  765. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  766. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  767. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  768. // Same 26-bit hash as REMOTE_ADDR.
  769. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  770. }
  771. // Forward declaration: in split builds split.py strips `inline` and moves the
  772. // definition into httplib.cc, so detail::base64_encode is not visible from the
  773. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  774. // in both header-only and split builds.
  775. namespace httplib {
  776. namespace detail {
  777. std::string base64_encode(const std::string &in);
  778. } // namespace detail
  779. } // namespace httplib
  780. TEST(Base64EncodeTest, KnownAnswers) {
  781. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  782. // where the accumulator's top bit is already set before the next shift.
  783. EXPECT_EQ("", detail::base64_encode(""));
  784. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  785. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  786. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  787. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  788. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  789. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  790. // High bytes keep the top bit set across several rounds.
  791. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  792. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  793. }
  794. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  795. string unescapedCharacters = "-_.!~*'()";
  796. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  797. }
  798. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  799. string reservedCharacters = ";,/?:@&=+$";
  800. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  801. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  802. }
  803. TEST(ClientQueryOrder, PreserveOrder) {
  804. // This test reproduces Issue #2259: client may reorder query parameters
  805. // when sending a GET request. The expected behavior is that the client
  806. // preserves the original query string order when the caller supplied it
  807. // as part of the path.
  808. Server svr;
  809. svr.Get("/", [&](const Request &req, Response &res) {
  810. // Echo back the raw target so the test can assert ordering
  811. res.set_content(req.target, "text/plain");
  812. });
  813. std::thread t{[&] { svr.listen(HOST, PORT); }};
  814. auto se = detail::scope_exit([&] {
  815. svr.stop();
  816. t.join();
  817. ASSERT_FALSE(svr.is_running());
  818. });
  819. svr.wait_until_ready();
  820. Client cli(HOST, PORT);
  821. ASSERT_TRUE(cli.is_valid());
  822. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  823. auto res = cli.Get(original);
  824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  825. // Expect the echoed target to exactly match the original path (order
  826. // preserved)
  827. EXPECT_EQ(res->body, original);
  828. }
  829. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  830. string chineseCharacters = U8("中国語");
  831. string russianCharacters = U8("дом");
  832. string brazilianCharacters = U8("óculos");
  833. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  834. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  835. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  836. "%D0%B4%D0%BE%D0%BC");
  837. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  838. }
  839. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  840. string unescapedCharacters = "-_.!~*'()";
  841. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  842. }
  843. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  844. string reservedCharacters = ";,/?:@&=+$";
  845. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  846. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  847. }
  848. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  849. string chineseCharacters = U8("中国語");
  850. string russianCharacters = U8("дом");
  851. string brazilianCharacters = U8("óculos");
  852. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  853. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  854. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  855. "%D0%B4%D0%BE%D0%BC");
  856. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  857. }
  858. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  859. // Issue #2082 use case: encoding path component with ampersand
  860. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  861. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  862. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  863. }
  864. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  865. string unescapedCharacters = "-_.!~*'()";
  866. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  867. }
  868. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  869. string reservedCharacters = ";,/?:@&=+$#";
  870. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  871. }
  872. TEST(EncodeUriTest, TestUTF8Characters) {
  873. string chineseCharacters = U8("中国語");
  874. string russianCharacters = U8("дом");
  875. string brazilianCharacters = U8("óculos");
  876. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  877. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  878. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  879. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  880. }
  881. TEST(EncodeUriTest, TestCompleteUri) {
  882. string uri =
  883. "https://example.com/path/to/resource?query=value&param=test#fragment";
  884. EXPECT_EQ(
  885. httplib::encode_uri(uri),
  886. "https://example.com/path/to/resource?query=value&param=test#fragment");
  887. }
  888. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  889. string uri =
  890. "https://example.com/path with spaces/file name.html?q=hello world";
  891. EXPECT_EQ(httplib::encode_uri(uri),
  892. "https://example.com/path%20with%20spaces/"
  893. "file%20name.html?q=hello%20world");
  894. }
  895. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  896. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  897. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  898. }
  899. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  900. string unescapedCharacters = "-_.!~*'()";
  901. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  902. }
  903. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  904. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  905. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  906. string encodedBrazilian = "%C3%B3culos";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  908. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  909. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  910. }
  911. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  912. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  913. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  914. "Piri Tommy Villiers - on & on");
  915. }
  916. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  917. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  918. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  919. }
  920. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  921. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  922. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  923. }
  924. TEST(DecodeUriTest, TestUTF8Characters) {
  925. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  926. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  927. string encodedBrazilian = "%C3%B3culos";
  928. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  929. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  930. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  931. }
  932. TEST(DecodeUriTest, TestCompleteUri) {
  933. string encodedUri = "https://example.com/path%20with%20spaces/"
  934. "file%20name.html?q=hello%20world";
  935. EXPECT_EQ(
  936. httplib::decode_uri(encodedUri),
  937. "https://example.com/path with spaces/file name.html?q=hello world");
  938. }
  939. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  940. string original =
  941. "https://example.com/path with spaces/file name.html?q=hello world";
  942. string encoded = httplib::encode_uri(original);
  943. string decoded = httplib::decode_uri(encoded);
  944. EXPECT_EQ(decoded, original);
  945. }
  946. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  947. // decode_uri is the inverse of encode_uri: an escaped reserved character
  948. // stays encoded so it is not promoted into a real delimiter, while
  949. // non-reserved escapes still decode (like JS decodeURI).
  950. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  951. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  952. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  953. "%3F%3A%40%26%3D%2B%24%2C%3B");
  954. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  955. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  956. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  957. "http://example.com/a%2Fb");
  958. // decode_uri_component still decodes the reserved character.
  959. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  960. }
  961. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  962. string original = "Piri Tommy Villiers - on & on";
  963. string encoded = httplib::encode_uri_component(original);
  964. string decoded = httplib::decode_uri_component(encoded);
  965. EXPECT_EQ(decoded, original);
  966. }
  967. TEST(TrimTests, TrimStringTests) {
  968. EXPECT_EQ("abc", detail::trim_copy("abc"));
  969. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  970. EXPECT_TRUE(detail::trim_copy("").empty());
  971. }
  972. TEST(AsciiTest, LocaleIndependentClassification) {
  973. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  974. // which consult the global C locale: std::isalnum(0xC5) can return true
  975. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  976. // helpers must classify every byte by the ASCII grammar alone.
  977. for (int i = 0; i < 256; i++) {
  978. auto c = static_cast<char>(i);
  979. auto is_digit = i >= '0' && i <= '9';
  980. auto is_upper = i >= 'A' && i <= 'Z';
  981. auto is_lower = i >= 'a' && i <= 'z';
  982. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  983. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  984. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  985. << "byte " << i;
  986. }
  987. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  988. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  989. // Non-ASCII bytes must be percent-encoded, never passed through as
  990. // alphanumeric.
  991. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  992. }
  993. TEST(FromCharsTest, Double) {
  994. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  995. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  996. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  997. auto parse = [](const std::string &s, double &v) {
  998. return detail::from_chars(s.data(), s.data() + s.size(), v);
  999. };
  1000. double v = -1.0;
  1001. // Representative quality values.
  1002. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1003. EXPECT_DOUBLE_EQ(v, 0.0);
  1004. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1005. EXPECT_DOUBLE_EQ(v, 1.0);
  1006. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1007. EXPECT_DOUBLE_EQ(v, 0.8);
  1008. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1009. EXPECT_DOUBLE_EQ(v, 0.001);
  1010. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1011. EXPECT_DOUBLE_EQ(v, 1.0);
  1012. // A missing integer or fractional part is tolerated.
  1013. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1014. EXPECT_DOUBLE_EQ(v, 0.5);
  1015. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1016. EXPECT_DOUBLE_EQ(v, 5.0);
  1017. // Values outside [0, 1] still parse; the caller range-checks them.
  1018. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 123.456);
  1020. // Stops at the first byte that is not part of the number and reports where.
  1021. std::string trailing = "0.9, text/html";
  1022. auto r = parse(trailing, v);
  1023. EXPECT_EQ(r.ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.9);
  1025. EXPECT_EQ(*r.ptr, ',');
  1026. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1027. // outright, and an 'e'/'E' simply ends the number.
  1028. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1029. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1030. std::string exp_input = "1.5e3";
  1031. r = parse(exp_input, v);
  1032. EXPECT_EQ(r.ec, std::errc{});
  1033. EXPECT_DOUBLE_EQ(v, 1.5);
  1034. EXPECT_EQ(*r.ptr, 'e');
  1035. // Invalid inputs.
  1036. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1037. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1038. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1040. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1041. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1042. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1043. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1044. std::errc{});
  1045. EXPECT_DOUBLE_EQ(v, 0.0);
  1046. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1047. std::errc{});
  1048. EXPECT_GE(v, 0.0);
  1049. EXPECT_LE(v, 1.0);
  1050. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1051. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1052. }
  1053. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1054. // Simple case without quality values
  1055. std::vector<std::string> result1;
  1056. EXPECT_TRUE(detail::parse_accept_header(
  1057. "text/html,application/json,text/plain", result1));
  1058. EXPECT_EQ(result1.size(), 3U);
  1059. EXPECT_EQ(result1[0], "text/html");
  1060. EXPECT_EQ(result1[1], "application/json");
  1061. EXPECT_EQ(result1[2], "text/plain");
  1062. // With quality values
  1063. std::vector<std::string> result2;
  1064. EXPECT_TRUE(detail::parse_accept_header(
  1065. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1066. EXPECT_EQ(result2.size(), 3U);
  1067. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1068. EXPECT_EQ(result2[1], "text/html");
  1069. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1070. }
  1071. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1072. // Mixed with and without quality values
  1073. std::vector<std::string> result;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1076. EXPECT_EQ(result.size(), 3U);
  1077. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1078. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1079. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1080. }
  1081. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1082. // Empty header
  1083. std::vector<std::string> empty_result;
  1084. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1085. EXPECT_TRUE(empty_result.empty());
  1086. // Single type
  1087. std::vector<std::string> single_result;
  1088. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1089. EXPECT_EQ(single_result.size(), 1U);
  1090. EXPECT_EQ(single_result[0], "application/json");
  1091. // Wildcard types
  1092. std::vector<std::string> wildcard_result;
  1093. EXPECT_TRUE(detail::parse_accept_header(
  1094. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1095. EXPECT_EQ(wildcard_result.size(), 3U);
  1096. EXPECT_EQ(wildcard_result[0], "application/json");
  1097. EXPECT_EQ(wildcard_result[1], "text/*");
  1098. EXPECT_EQ(wildcard_result[2], "*/*");
  1099. }
  1100. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1101. // Common browser Accept header
  1102. std::vector<std::string> browser_result;
  1103. EXPECT_TRUE(
  1104. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1105. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1106. browser_result));
  1107. EXPECT_EQ(browser_result.size(), 6U);
  1108. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1109. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1110. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1111. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1112. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1113. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1114. // API client header
  1115. std::vector<std::string> api_result;
  1116. EXPECT_TRUE(detail::parse_accept_header(
  1117. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1118. api_result));
  1119. EXPECT_EQ(api_result.size(), 3U);
  1120. EXPECT_EQ(api_result[0], "application/json");
  1121. EXPECT_EQ(api_result[1], "application/xml");
  1122. EXPECT_EQ(api_result[2], "text/plain");
  1123. }
  1124. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1125. // Quality value with 3 decimal places
  1126. std::vector<std::string> decimal_result;
  1127. EXPECT_TRUE(detail::parse_accept_header(
  1128. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1129. EXPECT_EQ(decimal_result.size(), 2U);
  1130. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1131. EXPECT_EQ(decimal_result[1], "text/html");
  1132. // Zero quality (should still be included but with lowest priority)
  1133. std::vector<std::string> zero_q_result;
  1134. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1135. zero_q_result));
  1136. EXPECT_EQ(zero_q_result.size(), 2U);
  1137. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1138. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1139. // No spaces around commas
  1140. std::vector<std::string> no_space_result;
  1141. EXPECT_TRUE(detail::parse_accept_header(
  1142. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1143. no_space_result));
  1144. EXPECT_EQ(no_space_result.size(), 3U);
  1145. EXPECT_EQ(no_space_result[0], "text/html");
  1146. EXPECT_EQ(no_space_result[1], "application/json");
  1147. EXPECT_EQ(no_space_result[2], "text/plain");
  1148. }
  1149. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1150. // Quality values always use '.' as the decimal separator, so parsing must
  1151. // not depend on the process locale. An embedding application may have
  1152. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1153. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1154. std::string saved = cur ? cur : "C";
  1155. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1156. "fr_FR.UTF-8"};
  1157. bool switched = false;
  1158. for (const auto loc : comma_locales) {
  1159. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1160. std::localeconv()->decimal_point[0] == ',') {
  1161. switched = true;
  1162. break;
  1163. }
  1164. }
  1165. if (!switched) {
  1166. std::setlocale(LC_NUMERIC, saved.c_str());
  1167. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1168. }
  1169. // The higher-weighted type appears later in the list, so a correct parse
  1170. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1171. // sensitive parse reads both weights as 0 and leaves the original order.
  1172. std::vector<std::string> result;
  1173. EXPECT_TRUE(detail::parse_accept_header(
  1174. "application/json;q=0.1,text/html;q=0.9", result));
  1175. ASSERT_EQ(result.size(), 2U);
  1176. EXPECT_EQ(result[0], "text/html");
  1177. EXPECT_EQ(result[1], "application/json");
  1178. std::setlocale(LC_NUMERIC, saved.c_str());
  1179. }
  1180. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1181. std::vector<std::string> result;
  1182. // Invalid quality value (> 1.0)
  1183. EXPECT_FALSE(
  1184. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1185. // Invalid quality value (< 0.0)
  1186. EXPECT_FALSE(
  1187. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1188. // Invalid quality value (not a number)
  1189. EXPECT_FALSE(detail::parse_accept_header(
  1190. "text/html;q=invalid,application/json", result));
  1191. // A valid numeric prefix does not make the entire quality value valid.
  1192. EXPECT_FALSE(detail::parse_accept_header(
  1193. "text/html;q=0.5junk,application/json", result));
  1194. // Empty quality value
  1195. EXPECT_FALSE(
  1196. detail::parse_accept_header("text/html;q=,application/json", result));
  1197. // Invalid media type format (no slash and not wildcard)
  1198. EXPECT_FALSE(
  1199. detail::parse_accept_header("invalidtype,application/json", result));
  1200. // Valid cases should still work
  1201. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1202. EXPECT_EQ(result.size(), 1U);
  1203. EXPECT_EQ(result[0], "*/*");
  1204. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1205. EXPECT_EQ(result.size(), 1U);
  1206. EXPECT_EQ(result[0], "*");
  1207. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1208. EXPECT_EQ(result.size(), 1U);
  1209. EXPECT_EQ(result[0], "text/*");
  1210. }
  1211. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1212. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1213. // and must not be answered with 400 Bad Request.
  1214. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1215. struct {
  1216. const char *value;
  1217. std::vector<std::string> expected;
  1218. } cases[] = {
  1219. {",application/json", {"application/json"}},
  1220. {"text/html,", {"text/html"}},
  1221. {"text/html,,*/*", {"text/html", "*/*"}},
  1222. // An empty element may be spelled with whitespace in it
  1223. {"text/html, , application/json", {"text/html", "application/json"}},
  1224. // Nothing but empty elements is an empty list, which means the same
  1225. // thing as no Accept header at all
  1226. {",,,", {}},
  1227. // Quality values still apply across ignored empty elements
  1228. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1229. };
  1230. for (const auto &c : cases) {
  1231. std::vector<std::string> result;
  1232. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1233. << "value: " << c.value;
  1234. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1235. }
  1236. // An invalid entry is still rejected when empty elements surround it
  1237. std::vector<std::string> result;
  1238. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1239. }
  1240. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1241. // or ';' inside one does not end the list element or the parameter. Section
  1242. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1243. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1244. struct {
  1245. const char *value;
  1246. std::vector<std::string> expected;
  1247. } cases[] = {
  1248. {"text/html;profile=\"a,b\",application/json",
  1249. {"text/html", "application/json"}},
  1250. // A "q=" inside a quoted value is not the weight
  1251. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1252. {"text/html", "application/json"}},
  1253. // The weight after a quoted value still applies
  1254. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1255. {"application/json", "text/html"}},
  1256. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1257. {"application/json", "text/html"}},
  1258. {"text/html;profile=\"a\\\"b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // An escaped backslash does not escape the '"' after it
  1261. {"text/html;profile=\"a\\\\\",application/json",
  1262. {"text/html", "application/json"}},
  1263. };
  1264. for (const auto &c : cases) {
  1265. std::vector<std::string> result;
  1266. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1267. << "value: " << c.value;
  1268. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1269. }
  1270. }
  1271. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1272. Server svr;
  1273. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1274. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1275. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1276. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1277. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1278. res.set_content("ok", "text/plain");
  1279. });
  1280. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1281. EXPECT_TRUE(false);
  1282. res.set_content("bad request", "text/plain");
  1283. });
  1284. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1285. auto se = detail::scope_exit([&] {
  1286. svr.stop();
  1287. listen_thread.join();
  1288. ASSERT_FALSE(svr.is_running());
  1289. });
  1290. svr.wait_until_ready();
  1291. Client cli("localhost", PORT);
  1292. {
  1293. auto res = cli.Get(
  1294. "/accept_ok",
  1295. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1297. EXPECT_EQ(StatusCode::OK_200, res->status);
  1298. }
  1299. {
  1300. auto res = cli.Get("/accept_bad_request",
  1301. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1303. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1304. }
  1305. }
  1306. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1307. Server svr;
  1308. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1309. res.set_content("ok", "text/plain");
  1310. });
  1311. std::atomic<int> start_count{0};
  1312. std::atomic<bool> running_when_called{false};
  1313. svr.set_start_handler([&]() {
  1314. running_when_called = svr.is_running();
  1315. start_count++;
  1316. });
  1317. auto port = svr.bind_to_any_port(HOST);
  1318. std::thread t([&]() { svr.listen_after_bind(); });
  1319. auto se = detail::scope_exit([&] {
  1320. svr.stop();
  1321. t.join();
  1322. ASSERT_FALSE(svr.is_running());
  1323. });
  1324. svr.wait_until_ready();
  1325. // A successful request proves the accept loop is running, which the start
  1326. // handler precedes; so by now the handler must have run exactly once.
  1327. Client cli(HOST, port);
  1328. cli.set_connection_timeout(std::chrono::seconds(5));
  1329. auto res = cli.Get("/");
  1330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1331. EXPECT_EQ(StatusCode::OK_200, res->status);
  1332. EXPECT_EQ(1, start_count.load());
  1333. EXPECT_TRUE(running_when_called.load());
  1334. }
  1335. TEST(DivideTest, DivideStringTests) {
  1336. auto divide = [](const std::string &str, char d) {
  1337. std::string lhs;
  1338. std::string rhs;
  1339. detail::divide(str, d,
  1340. [&](const char *lhs_data, std::size_t lhs_size,
  1341. const char *rhs_data, std::size_t rhs_size) {
  1342. lhs.assign(lhs_data, lhs_size);
  1343. rhs.assign(rhs_data, rhs_size);
  1344. });
  1345. return std::make_pair(std::move(lhs), std::move(rhs));
  1346. };
  1347. {
  1348. const auto res = divide("", '=');
  1349. EXPECT_EQ(res.first, "");
  1350. EXPECT_EQ(res.second, "");
  1351. }
  1352. {
  1353. const auto res = divide("=", '=');
  1354. EXPECT_EQ(res.first, "");
  1355. EXPECT_EQ(res.second, "");
  1356. }
  1357. {
  1358. const auto res = divide(" ", '=');
  1359. EXPECT_EQ(res.first, " ");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("a", '=');
  1364. EXPECT_EQ(res.first, "a");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide("a=", '=');
  1369. EXPECT_EQ(res.first, "a");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("=b", '=');
  1374. EXPECT_EQ(res.first, "");
  1375. EXPECT_EQ(res.second, "b");
  1376. }
  1377. {
  1378. const auto res = divide("a=b", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "b");
  1381. }
  1382. {
  1383. const auto res = divide("a=b=", '=');
  1384. EXPECT_EQ(res.first, "a");
  1385. EXPECT_EQ(res.second, "b=");
  1386. }
  1387. {
  1388. const auto res = divide("a=b=c", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b=c");
  1391. }
  1392. }
  1393. TEST(SplitTest, ParseQueryString) {
  1394. string s = "key1=val1&key2=val2&key3=val3";
  1395. Params dic;
  1396. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1397. [&](const char *b, const char *e) {
  1398. string key, val;
  1399. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1400. if (key.empty()) {
  1401. key.assign(b2, e2);
  1402. } else {
  1403. val.assign(b2, e2);
  1404. }
  1405. });
  1406. dic.emplace(key, val);
  1407. });
  1408. EXPECT_EQ("val1", dic.find("key1")->second);
  1409. EXPECT_EQ("val2", dic.find("key2")->second);
  1410. EXPECT_EQ("val3", dic.find("key3")->second);
  1411. }
  1412. TEST(SplitTest, ParseInvalidQueryTests) {
  1413. {
  1414. string s = " ";
  1415. Params dict;
  1416. detail::parse_query_text(s, dict);
  1417. EXPECT_TRUE(dict.empty());
  1418. }
  1419. {
  1420. string s = " = =";
  1421. Params dict;
  1422. detail::parse_query_text(s, dict);
  1423. EXPECT_TRUE(dict.empty());
  1424. }
  1425. }
  1426. TEST(ParseQueryTest, ParseQueryString) {
  1427. {
  1428. std::string s = "key1=val1&key2=val2&key3=val3";
  1429. Params dic;
  1430. detail::parse_query_text(s, dic);
  1431. EXPECT_EQ("val1", dic.find("key1")->second);
  1432. EXPECT_EQ("val2", dic.find("key2")->second);
  1433. EXPECT_EQ("val3", dic.find("key3")->second);
  1434. }
  1435. {
  1436. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1437. Params dic;
  1438. detail::parse_query_text(s, dic);
  1439. EXPECT_EQ("", dic.find("key1")->second);
  1440. EXPECT_EQ("val1", dic.find("key2")->second);
  1441. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1442. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1443. }
  1444. }
  1445. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1446. Params dic;
  1447. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1448. dic.emplace("key1", "val1");
  1449. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1450. dic.emplace("key2", "val2");
  1451. dic.emplace("key3", "val3");
  1452. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1453. }
  1454. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1455. Params params;
  1456. params.emplace("a", "1");
  1457. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1458. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1459. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1460. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1461. // Long enough to overflow the stack when matched with std::regex.
  1462. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1463. EXPECT_EQ("/p?" + long_query + "&a=1",
  1464. append_query_params("/p?" + long_query, params));
  1465. }
  1466. // Joins every entry of a Headers or Params into "key=value " so a whole
  1467. // traversal can be compared in one assertion. Both are instantiations of the
  1468. // same insertion-ordered container, so one helper serves both.
  1469. template <typename Map> static std::string entries_to_string(const Map &m) {
  1470. std::string s;
  1471. for (const auto &entry : m) {
  1472. s += entry.first + "=" + entry.second + " ";
  1473. }
  1474. return s;
  1475. }
  1476. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1477. // Params used to be a std::multimap, which sorted by name and handed the
  1478. // caller's query back alphabetised. A client signing its query string could
  1479. // not reproduce the order it asked for.
  1480. Params dic;
  1481. dic.emplace("zulu", "1");
  1482. dic.emplace("alpha", "2");
  1483. dic.emplace("mike", "3");
  1484. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1485. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1486. }
  1487. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1488. Params dic;
  1489. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1490. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1491. }
  1492. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1493. Request req;
  1494. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1495. req.params);
  1496. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1497. EXPECT_EQ("first", req.get_param_value("tag"));
  1498. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1499. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1500. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1501. EXPECT_EQ("", req.get_param_value("tag", 3));
  1502. }
  1503. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1504. // Params shares its container with Headers, which matches field names
  1505. // case-insensitively. Parameter names must not pick that up.
  1506. Params dic;
  1507. dic.emplace("Key", "upper");
  1508. dic.emplace("key", "lower");
  1509. EXPECT_EQ(2U, dic.size());
  1510. EXPECT_EQ(1U, dic.count("Key"));
  1511. EXPECT_EQ(1U, dic.count("key"));
  1512. EXPECT_EQ("upper", dic.find("Key")->second);
  1513. EXPECT_EQ("lower", dic.find("key")->second);
  1514. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1515. }
  1516. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1517. Server svr;
  1518. std::string order;
  1519. svr.Get("/order", [&](const Request &req, Response &res) {
  1520. order = entries_to_string(req.params);
  1521. res.set_content("ok", "text/plain");
  1522. });
  1523. auto port = svr.bind_to_any_port(HOST);
  1524. thread t = thread([&] { svr.listen_after_bind(); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. t.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, port);
  1532. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1535. }
  1536. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1537. Server svr;
  1538. std::string field_order, file_order;
  1539. svr.Post("/order", [&](const Request &req, Response &res) {
  1540. for (const auto &field : req.form.fields) {
  1541. field_order += field.first + "=" + field.second.content + " ";
  1542. }
  1543. for (const auto &file : req.form.files) {
  1544. file_order += file.first + "=" + file.second.filename + " ";
  1545. }
  1546. res.set_content("ok", "text/plain");
  1547. });
  1548. auto port = svr.bind_to_any_port(HOST);
  1549. thread t = thread([&] { svr.listen_after_bind(); });
  1550. auto se = detail::scope_exit([&] {
  1551. svr.stop();
  1552. t.join();
  1553. ASSERT_FALSE(svr.is_running());
  1554. });
  1555. svr.wait_until_ready();
  1556. UploadFormDataItems items = {
  1557. {"zulu", "1", "", ""},
  1558. {"alpha", "2", "", ""},
  1559. {"mike", "3", "", ""},
  1560. {"zebra", "z", "z.txt", "text/plain"},
  1561. {"apple", "a", "a.txt", "text/plain"},
  1562. };
  1563. Client cli(HOST, port);
  1564. auto res = cli.Post("/order", items);
  1565. ASSERT_TRUE(res);
  1566. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1567. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1568. }
  1569. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1570. Server svr;
  1571. std::vector<std::string> values;
  1572. std::string first, second, out_of_range, order;
  1573. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1574. values = req.form.get_fields("tag");
  1575. first = req.form.get_field("tag", 0);
  1576. second = req.form.get_field("tag", 1);
  1577. out_of_range = req.form.get_field("tag", 2);
  1578. for (const auto &field : req.form.fields) {
  1579. order += field.first + "=" + field.second.content + " ";
  1580. }
  1581. res.set_content("ok", "text/plain");
  1582. });
  1583. auto port = svr.bind_to_any_port(HOST);
  1584. thread t = thread([&] { svr.listen_after_bind(); });
  1585. auto se = detail::scope_exit([&] {
  1586. svr.stop();
  1587. t.join();
  1588. ASSERT_FALSE(svr.is_running());
  1589. });
  1590. svr.wait_until_ready();
  1591. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1592. // not adjacent in the container.
  1593. UploadFormDataItems items = {
  1594. {"tag", "first", "", ""},
  1595. {"other", "x", "", ""},
  1596. {"tag", "second", "", ""},
  1597. };
  1598. Client cli(HOST, port);
  1599. auto res = cli.Post("/repeated", items);
  1600. ASSERT_TRUE(res);
  1601. ASSERT_EQ(2U, values.size());
  1602. EXPECT_EQ("first", values[0]);
  1603. EXPECT_EQ("second", values[1]);
  1604. EXPECT_EQ("first", first);
  1605. EXPECT_EQ("second", second);
  1606. // std::multimap already kept entries sharing a name in insertion order, so
  1607. // everything above passes without this change too. The whole traversal is
  1608. // what tells the two apart: sorting by name would hoist "other" to the front
  1609. // and the two "tag" parts would end up adjacent.
  1610. EXPECT_EQ("tag=first other=x tag=second ", order);
  1611. // Advancing past the last entry of a name used to run off the container;
  1612. // the container's saturating increment makes it return the default instead.
  1613. EXPECT_EQ("", out_of_range);
  1614. }
  1615. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1616. Server svr;
  1617. std::string file_names;
  1618. svr.Post("/upload", [&](const Request &req, Response &res) {
  1619. for (const auto &file : req.form.files) {
  1620. file_names += file.first + "|" + file.second.filename + " ";
  1621. }
  1622. res.set_content("ok", "text/plain");
  1623. });
  1624. auto port = svr.bind_to_any_port(HOST);
  1625. thread t = thread([&] { svr.listen_after_bind(); });
  1626. auto se = detail::scope_exit([&] {
  1627. svr.stop();
  1628. t.join();
  1629. ASSERT_FALSE(svr.is_running());
  1630. });
  1631. svr.wait_until_ready();
  1632. // A trailing backslash would otherwise escape the closing quote.
  1633. UploadFormDataItems items = {
  1634. {"dir\\", "x", "a.txt", "text/plain"},
  1635. {"b", "y", "a\\\\b.txt", "text/plain"},
  1636. };
  1637. Client cli(HOST, port);
  1638. auto res = cli.Post("/upload", items);
  1639. ASSERT_TRUE(res);
  1640. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1641. }
  1642. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1643. // Server::read_content() keeps a FormFields::iterator alive across the
  1644. // content callbacks that fill the part it points at. The container is
  1645. // vector-backed, so a later emplace can reallocate and invalidate an older
  1646. // iterator; 64 parts grow the vector through seven reallocations, which
  1647. // checks that every part's content still lands in its own entry.
  1648. const size_t part_count = 64;
  1649. // One formula for both the parts sent and the values expected back, so the
  1650. // two cannot drift apart.
  1651. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1652. auto content_of = [](size_t i) {
  1653. return std::string(64, static_cast<char>('a' + (i % 26)));
  1654. };
  1655. Server svr;
  1656. std::vector<std::pair<std::string, std::string>> received;
  1657. svr.Post("/many", [&](const Request &req, Response &res) {
  1658. for (const auto &field : req.form.fields) {
  1659. received.emplace_back(field.first, field.second.content);
  1660. }
  1661. res.set_content("ok", "text/plain");
  1662. });
  1663. auto port = svr.bind_to_any_port(HOST);
  1664. thread t = thread([&] { svr.listen_after_bind(); });
  1665. auto se = detail::scope_exit([&] {
  1666. svr.stop();
  1667. t.join();
  1668. ASSERT_FALSE(svr.is_running());
  1669. });
  1670. svr.wait_until_ready();
  1671. UploadFormDataItems items;
  1672. for (size_t i = 0; i < part_count; i++) {
  1673. items.push_back({name_of(i), content_of(i), "", ""});
  1674. }
  1675. Client cli(HOST, port);
  1676. auto res = cli.Post("/many", items);
  1677. ASSERT_TRUE(res);
  1678. ASSERT_EQ(part_count, received.size());
  1679. for (size_t i = 0; i < part_count; i++) {
  1680. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1681. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1682. }
  1683. }
  1684. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1685. string content_type = "multipart/form-data; boundary=something";
  1686. string boundary;
  1687. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1688. EXPECT_TRUE(ret);
  1689. EXPECT_EQ(boundary, "something");
  1690. }
  1691. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1692. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1693. string boundary;
  1694. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1695. EXPECT_TRUE(ret);
  1696. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1697. }
  1698. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1699. string content_type =
  1700. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1701. string boundary;
  1702. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1703. EXPECT_TRUE(ret);
  1704. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1705. }
  1706. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1707. string content_type =
  1708. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1709. string boundary;
  1710. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1711. EXPECT_TRUE(ret);
  1712. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1713. }
  1714. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1715. const string boundary(70, 'a');
  1716. string content_type = "multipart/form-data; boundary=" + boundary;
  1717. string parsed;
  1718. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1719. EXPECT_TRUE(ret);
  1720. EXPECT_EQ(parsed, boundary);
  1721. }
  1722. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1723. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1724. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1725. string parsed;
  1726. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1727. EXPECT_FALSE(ret);
  1728. }
  1729. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1730. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1731. // is 72 characters on the wire and still valid.
  1732. const string boundary(70, 'a');
  1733. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1734. string parsed;
  1735. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1736. EXPECT_EQ(parsed, boundary);
  1737. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1738. parsed.clear();
  1739. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1740. }
  1741. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1742. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1743. // The parameter parser must not treat that '=' as the key/value separator.
  1744. string content_type =
  1745. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1746. "charset=UTF-8";
  1747. string parsed;
  1748. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1749. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1752. // A ';' inside the quoted-string is part of the value, not a parameter
  1753. // separator, so it must not truncate the boundary.
  1754. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1755. string parsed;
  1756. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1757. EXPECT_EQ(parsed, "a;b");
  1758. }
  1759. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1760. string parsed;
  1761. EXPECT_TRUE(detail::parse_multipart_boundary(
  1762. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1763. EXPECT_EQ("a\\b", parsed);
  1764. EXPECT_TRUE(detail::parse_multipart_boundary(
  1765. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1766. EXPECT_EQ("a\"b", parsed);
  1767. }
  1768. TEST(ParseDispositionParamsTest, QuotedValues) {
  1769. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1770. // ';' and '=' are ordinary characters inside one.
  1771. struct {
  1772. const char *value;
  1773. std::vector<std::pair<const char *, const char *>> expected;
  1774. } cases[] = {
  1775. {"name=\"file1\"; filename=\"a.txt\"",
  1776. {{"name", "file1"}, {"filename", "a.txt"}}},
  1777. // Whitespace around '=' and ';' is still trimmed
  1778. {"name=\"file2\" ;filename = \"a.html\"",
  1779. {{"name", "file2"}, {"filename", "a.html"}}},
  1780. // '=' inside the value used to leave only the text after the last one
  1781. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1782. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1783. {"name=\"x=y\"", {{"name", "x=y"}}},
  1784. // ';' inside the value used to truncate the pair and leave a bogus one
  1785. {"name=\"file3\"; filename=\"a;b.txt\"",
  1786. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1787. // An unquoted value keeps working, and so does filename*
  1788. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1789. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1790. // A parameter with no key is dropped rather than turned into one whose
  1791. // key is the value
  1792. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1793. // An escaped quote does not end the value
  1794. {"name=\"a\\\"; filename=evil.php\"",
  1795. {{"name", "a\"; filename=evil.php"}}},
  1796. // Other backslashes, as in a Windows path, are kept
  1797. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1798. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1799. };
  1800. for (const auto &c : cases) {
  1801. Params params;
  1802. detail::parse_disposition_params(c.value, params);
  1803. for (const auto &kv : c.expected) {
  1804. auto it = params.find(kv.first);
  1805. ASSERT_NE(it, params.end())
  1806. << "value: " << c.value << ", key: " << kv.first;
  1807. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1808. }
  1809. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1810. }
  1811. }
  1812. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1813. Server svr;
  1814. std::string filename;
  1815. std::string content;
  1816. svr.Post("/upload", [&](const Request &req, Response &) {
  1817. const auto &file = req.form.get_file("file");
  1818. filename = file.filename;
  1819. content = file.content;
  1820. });
  1821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1822. auto se = detail::scope_exit([&] {
  1823. svr.stop();
  1824. thread.join();
  1825. ASSERT_FALSE(svr.is_running());
  1826. });
  1827. svr.wait_until_ready();
  1828. std::string body = "--B\r\n"
  1829. "Content-Disposition: form-data; name=\"file\"; "
  1830. "filename=\"a.txt\"\r\n"
  1831. "Content-Type: text/plain\r\n"
  1832. "\r\n"
  1833. "hello\r\n"
  1834. "--B--\r\n";
  1835. Client cli(HOST, PORT);
  1836. auto res = cli.Post(
  1837. "/upload",
  1838. [&](size_t offset, DataSink &sink) {
  1839. if (offset < body.size()) {
  1840. sink.write(&body[offset], 1);
  1841. } else {
  1842. sink.done();
  1843. }
  1844. return true;
  1845. },
  1846. "multipart/form-data; boundary=B");
  1847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1848. EXPECT_EQ(StatusCode::OK_200, res->status);
  1849. EXPECT_EQ("a.txt", filename);
  1850. EXPECT_EQ("hello", content);
  1851. }
  1852. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1853. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1854. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1855. Server svr;
  1856. std::string field_value, file_name, file_filename;
  1857. bool has_field = false, has_file = false;
  1858. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1859. has_field = req.form.has_field("x=y");
  1860. field_value = req.form.get_field("x=y");
  1861. has_file = req.form.has_file("file1");
  1862. const auto &file = req.form.get_file("file1");
  1863. file_name = file.name;
  1864. file_filename = file.filename;
  1865. res.set_content("ok", "text/plain");
  1866. });
  1867. auto port = svr.bind_to_any_port(HOST);
  1868. thread t = thread([&] { svr.listen_after_bind(); });
  1869. auto se = detail::scope_exit([&] {
  1870. svr.stop();
  1871. t.join();
  1872. ASSERT_FALSE(svr.is_running());
  1873. });
  1874. svr.wait_until_ready();
  1875. UploadFormDataItems items = {
  1876. {"x=y", "field-value", "", ""},
  1877. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1878. };
  1879. Client cli(HOST, port);
  1880. auto res = cli.Post("/quoted", items);
  1881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1882. ASSERT_EQ(StatusCode::OK_200, res->status);
  1883. EXPECT_TRUE(has_field);
  1884. EXPECT_EQ("field-value", field_value);
  1885. EXPECT_TRUE(has_file);
  1886. EXPECT_EQ("file1", file_name);
  1887. EXPECT_EQ("a;b=report.pdf", file_filename);
  1888. }
  1889. TEST(GetHeaderValueTest, DefaultValue) {
  1890. Headers headers = {{"Dummy", "Dummy"}};
  1891. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1892. EXPECT_STREQ("text/plain", val);
  1893. }
  1894. TEST(GetHeaderValueTest, DefaultValueInt) {
  1895. Headers headers = {{"Dummy", "Dummy"}};
  1896. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1897. EXPECT_EQ(100ull, val);
  1898. }
  1899. TEST(GetHeaderValueTest, RegularValue) {
  1900. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1901. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1902. EXPECT_STREQ("text/html", val);
  1903. }
  1904. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1905. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1906. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1907. EXPECT_STREQ("text/html", val);
  1908. }
  1909. TEST(GetHeaderValueTest, SetContent) {
  1910. Response res;
  1911. res.set_content("html", "text/html");
  1912. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1913. res.set_content("text", "text/plain");
  1914. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1915. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1916. }
  1917. TEST(GetHeaderValueTest, RegularValueInt) {
  1918. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1919. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1920. EXPECT_EQ(100ull, val);
  1921. }
  1922. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1923. Headers headers = {{"Content-Length", "x"}};
  1924. auto is_invalid_value = false;
  1925. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1926. is_invalid_value);
  1927. EXPECT_EQ(0ull, val);
  1928. EXPECT_TRUE(is_invalid_value);
  1929. }
  1930. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1931. // An all-digit value that overflows size_t must be reported as invalid, not
  1932. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1933. // a large length to a small one on 32-bit builds, leaving the framing length
  1934. // wrong while is_invalid_value stayed false.
  1935. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1936. auto is_invalid_value = false;
  1937. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1938. is_invalid_value);
  1939. EXPECT_TRUE(is_invalid_value);
  1940. // A well-formed length is unaffected.
  1941. Headers ok = {{"Content-Length", "1234"}};
  1942. is_invalid_value = false;
  1943. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1944. is_invalid_value);
  1945. EXPECT_EQ(1234ull, val);
  1946. EXPECT_FALSE(is_invalid_value);
  1947. }
  1948. TEST(GetHeaderValueTest, Range) {
  1949. {
  1950. Headers headers = {make_range_header({{1, -1}})};
  1951. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1952. EXPECT_STREQ("bytes=1-", val);
  1953. }
  1954. {
  1955. Headers headers = {make_range_header({{-1, 1}})};
  1956. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1957. EXPECT_STREQ("bytes=-1", val);
  1958. }
  1959. {
  1960. Headers headers = {make_range_header({{1, 10}})};
  1961. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1962. EXPECT_STREQ("bytes=1-10", val);
  1963. }
  1964. {
  1965. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1966. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1967. EXPECT_STREQ("bytes=1-10, 100-", val);
  1968. }
  1969. {
  1970. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1971. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1972. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1973. }
  1974. {
  1975. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1976. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1977. EXPECT_STREQ("bytes=0-0, -1", val);
  1978. }
  1979. }
  1980. TEST(BearerTokenAuthTest, SchemeValidation) {
  1981. // A value shorter than "Bearer " must not throw from the fixed-length
  1982. // substr, and a non-Bearer scheme must not be reported as a token.
  1983. struct {
  1984. const char *value;
  1985. const char *expected;
  1986. } cases[] = {
  1987. {"x", ""},
  1988. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1989. {"Bearer abc123", "abc123"},
  1990. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1991. };
  1992. for (const auto &c : cases) {
  1993. Request req;
  1994. req.set_header("Authorization", c.value);
  1995. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1996. }
  1997. }
  1998. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1999. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2000. // to depend on the standard library (libstdc++ handed back duplicates in
  2001. // reverse insertion order, libc++ in insertion order).
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip");
  2004. req.set_header("Accept-Encoding", "deflate");
  2005. req.set_header("Accept-Encoding", "br");
  2006. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2007. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2008. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2009. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2010. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2011. }
  2012. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2013. Request req;
  2014. req.set_header("X-Test", "only");
  2015. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2016. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2017. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2018. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2019. }
  2020. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2021. Request req;
  2022. req.set_header("X-First", "1");
  2023. req.set_header("X-Test", "2");
  2024. req.params.emplace("first", "1");
  2025. req.params.emplace("test", "2");
  2026. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2027. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2028. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2029. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2030. // The second one is negative when read as a signed value
  2031. const auto max_id = (std::numeric_limits<size_t>::max)();
  2032. for (auto id : {max_id / 2, max_id}) {
  2033. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2034. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2035. EXPECT_EQ("", req.get_param_value("test", id));
  2036. EXPECT_EQ("", req.form.get_field("test", id));
  2037. EXPECT_EQ("", req.form.get_file("test", id).content);
  2038. }
  2039. }
  2040. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2041. Headers headers;
  2042. headers.emplace("Host", "example.com");
  2043. headers.emplace("Accept-Encoding", "gzip");
  2044. headers.emplace("User-Agent", "test");
  2045. headers.emplace("Accept-Encoding", "deflate");
  2046. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2047. "Accept-Encoding=deflate ",
  2048. entries_to_string(headers));
  2049. }
  2050. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2051. Headers headers = {{"Content-Type", "text/html"},
  2052. {"CONTENT-TYPE", "text/xml"}};
  2053. EXPECT_EQ(2U, headers.count("content-type"));
  2054. auto it = headers.find("content-type");
  2055. ASSERT_TRUE(it != headers.end());
  2056. EXPECT_EQ("text/html", it->second);
  2057. }
  2058. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2059. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2060. // drop only those fields and leave everything positioned between them.
  2061. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2062. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2063. auto rng = headers.equal_range("a");
  2064. headers.erase(rng.first, rng.second);
  2065. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2066. }
  2067. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2068. Headers headers = {
  2069. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2070. EXPECT_EQ(3U, headers.erase("A"));
  2071. EXPECT_EQ(0U, headers.count("A"));
  2072. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2073. }
  2074. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2075. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2076. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2077. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2078. }
  2079. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2080. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2081. headers.emplace_front("Host", "example.com");
  2082. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2083. entries_to_string(headers));
  2084. }
  2085. TEST(ParseHeaderValueTest, Range) {
  2086. {
  2087. Ranges ranges;
  2088. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2089. EXPECT_TRUE(ret);
  2090. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2091. }
  2092. {
  2093. Ranges ranges;
  2094. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2095. EXPECT_TRUE(ret);
  2096. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2097. }
  2098. {
  2099. Ranges ranges;
  2100. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2101. EXPECT_TRUE(ret);
  2102. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2103. }
  2104. {
  2105. Ranges ranges;
  2106. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2107. EXPECT_FALSE(ret);
  2108. }
  2109. {
  2110. Ranges ranges;
  2111. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2112. EXPECT_TRUE(ret);
  2113. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2114. }
  2115. {
  2116. Ranges ranges;
  2117. auto ret =
  2118. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2119. EXPECT_TRUE(ret);
  2120. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2121. }
  2122. {
  2123. Ranges ranges;
  2124. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2125. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2126. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2127. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2128. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2129. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2130. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2131. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2132. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2133. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2134. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2135. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2136. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2137. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2138. EXPECT_FALSE(
  2139. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2140. EXPECT_TRUE(ranges.empty());
  2141. }
  2142. {
  2143. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2144. // remainder of the representation, so it stays accepted.
  2145. Ranges ranges;
  2146. auto ret =
  2147. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2148. EXPECT_TRUE(ret);
  2149. ASSERT_EQ(1u, ranges.size());
  2150. EXPECT_EQ(0, ranges[0].first);
  2151. EXPECT_EQ(-1, ranges[0].second);
  2152. }
  2153. // RFC 9110 14.1: range unit names are case-insensitive.
  2154. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2155. Ranges ranges;
  2156. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2157. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2158. }
  2159. }
  2160. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2161. Request req;
  2162. req.set_header("Accept-Encoding", "gzip");
  2163. Response res;
  2164. res.set_header("Content-Type", "text/plain");
  2165. auto ret = detail::encoding_type(req, res);
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #else
  2169. EXPECT_TRUE(ret == detail::EncodingType::None);
  2170. #endif
  2171. }
  2172. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2173. Request req;
  2174. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2175. Response res;
  2176. res.set_header("Content-Type", "text/plain");
  2177. auto ret = detail::encoding_type(req, res);
  2178. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2179. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2180. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2181. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2182. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2183. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2184. #else
  2185. EXPECT_TRUE(ret == detail::EncodingType::None);
  2186. #endif
  2187. }
  2188. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2189. Request req;
  2190. req.set_header("Accept-Encoding",
  2191. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2192. Response res;
  2193. res.set_header("Content-Type", "text/plain");
  2194. auto ret = detail::encoding_type(req, res);
  2195. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2196. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2197. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2198. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2199. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2200. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2201. #else
  2202. EXPECT_TRUE(ret == detail::EncodingType::None);
  2203. #endif
  2204. }
  2205. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2206. // All supported encodings rejected with q=0 should return None
  2207. Request req;
  2208. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2209. Response res;
  2210. res.set_header("Content-Type", "text/plain");
  2211. auto ret = detail::encoding_type(req, res);
  2212. EXPECT_TRUE(ret == detail::EncodingType::None);
  2213. }
  2214. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2215. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2216. Request req;
  2217. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2218. Response res;
  2219. res.set_header("Content-Type", "text/plain");
  2220. auto ret = detail::encoding_type(req, res);
  2221. EXPECT_TRUE(ret == detail::EncodingType::None);
  2222. }
  2223. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2224. Request req;
  2225. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2226. Response res;
  2227. res.set_header("Content-Type", "text/plain");
  2228. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2229. }
  2230. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2231. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2232. Request req;
  2233. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2234. Response res;
  2235. res.set_header("Content-Type", "text/plain");
  2236. auto ret = detail::encoding_type(req, res);
  2237. EXPECT_TRUE(ret == detail::EncodingType::None);
  2238. }
  2239. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2240. // RFC 7231: Accept-Encoding values are case-insensitive
  2241. Request req;
  2242. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2243. Response res;
  2244. res.set_header("Content-Type", "text/plain");
  2245. auto ret = detail::encoding_type(req, res);
  2246. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2247. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2248. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2249. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2250. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2251. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2252. #else
  2253. EXPECT_TRUE(ret == detail::EncodingType::None);
  2254. #endif
  2255. }
  2256. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2257. // q value should determine priority, not hardcoded order
  2258. Request req;
  2259. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2260. Response res;
  2261. res.set_header("Content-Type", "text/plain");
  2262. auto ret = detail::encoding_type(req, res);
  2263. // gzip has highest q=1.0, so it should be selected even though
  2264. // br and zstd are also supported
  2265. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2266. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2267. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2268. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2269. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2270. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2271. #else
  2272. EXPECT_TRUE(ret == detail::EncodingType::None);
  2273. #endif
  2274. }
  2275. TEST(BufferStreamTest, read) {
  2276. detail::BufferStream strm1;
  2277. Stream &strm = strm1;
  2278. EXPECT_EQ(5, strm.write("hello"));
  2279. char buf[512];
  2280. EXPECT_EQ(2, strm.read(buf, 2));
  2281. EXPECT_EQ('h', buf[0]);
  2282. EXPECT_EQ('e', buf[1]);
  2283. EXPECT_EQ(2, strm.read(buf, 2));
  2284. EXPECT_EQ('l', buf[0]);
  2285. EXPECT_EQ('l', buf[1]);
  2286. EXPECT_EQ(1, strm.read(buf, 1));
  2287. EXPECT_EQ('o', buf[0]);
  2288. EXPECT_EQ(0, strm.read(buf, 1));
  2289. }
  2290. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2291. auto host = "www.httpwatch.com";
  2292. auto ip = hosted_at(host);
  2293. EXPECT_EQ("23.96.13.243", ip);
  2294. std::vector<std::string> addrs;
  2295. hosted_at(host, addrs);
  2296. EXPECT_EQ(1u, addrs.size());
  2297. }
  2298. #if 0 // It depends on each test environment...
  2299. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2300. auto host = "www.youtube.com";
  2301. std::vector<std::string> addrs;
  2302. hosted_at(host, addrs);
  2303. EXPECT_EQ(20u, addrs.size());
  2304. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2305. EXPECT_TRUE(it != addrs.end());
  2306. }
  2307. #endif
  2308. class ChunkedEncodingTest : public ::testing::Test {
  2309. protected:
  2310. ChunkedEncodingTest()
  2311. : cli_(HOST, PORT)
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. ,
  2314. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2315. #endif
  2316. {
  2317. cli_.set_connection_timeout(2);
  2318. #ifdef CPPHTTPLIB_SSL_ENABLED
  2319. cli_.enable_server_certificate_verification(false);
  2320. #endif
  2321. }
  2322. virtual void SetUp() {
  2323. read_file("./image.jpg", image_data_);
  2324. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2325. res.set_content("Hello World!", "text/plain");
  2326. });
  2327. svr_.Get(
  2328. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2329. res.set_chunked_content_provider(
  2330. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2331. size_t remaining = image_data_.size() - offset;
  2332. if (remaining == 0) {
  2333. sink.done();
  2334. } else {
  2335. constexpr size_t CHUNK_SIZE = 1024;
  2336. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2337. sink.write(&image_data_[offset], send_size);
  2338. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2339. }
  2340. return true;
  2341. });
  2342. });
  2343. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2344. svr_.wait_until_ready();
  2345. }
  2346. virtual void TearDown() {
  2347. svr_.stop();
  2348. if (!request_threads_.empty()) {
  2349. std::this_thread::sleep_for(std::chrono::seconds(1));
  2350. for (auto &t : request_threads_) {
  2351. t.join();
  2352. }
  2353. }
  2354. t_.join();
  2355. }
  2356. #ifdef CPPHTTPLIB_SSL_ENABLED
  2357. SSLClient cli_;
  2358. SSLServer svr_;
  2359. #else
  2360. Client cli_;
  2361. Server svr_;
  2362. #endif
  2363. thread t_;
  2364. std::vector<thread> request_threads_;
  2365. std::string image_data_;
  2366. };
  2367. TEST_F(ChunkedEncodingTest, NormalGet) {
  2368. auto res = cli_.Get("/chunked");
  2369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2370. std::string out;
  2371. read_file("./image.jpg", out);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ(out, res->body);
  2374. }
  2375. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2376. std::string body;
  2377. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2378. body.append(data, data_length);
  2379. return true;
  2380. });
  2381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2382. std::string out;
  2383. read_file("./image.jpg", out);
  2384. EXPECT_EQ(StatusCode::OK_200, res->status);
  2385. EXPECT_EQ(out, body);
  2386. }
  2387. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2388. std::string body;
  2389. auto res = cli_.Get(
  2390. "/chunked",
  2391. [&](const Response &response) {
  2392. EXPECT_EQ(StatusCode::OK_200, response.status);
  2393. return true;
  2394. },
  2395. [&](const char *data, size_t data_length) {
  2396. body.append(data, data_length);
  2397. return true;
  2398. });
  2399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2400. std::string out;
  2401. read_file("./image.jpg", out);
  2402. EXPECT_EQ(StatusCode::OK_200, res->status);
  2403. EXPECT_EQ(out, body);
  2404. }
  2405. TEST(RangeTest, FromHTTPBin_Online) {
  2406. auto host = "httpbingo.org";
  2407. auto path = std::string{"/range/32"};
  2408. #ifdef CPPHTTPLIB_SSL_ENABLED
  2409. auto port = 443;
  2410. SSLClient cli(host, port);
  2411. #else
  2412. auto port = 80;
  2413. Client cli(host, port);
  2414. #endif
  2415. cli.set_connection_timeout(5);
  2416. {
  2417. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  2418. SKIP_ON_GATEWAY_ERROR(res);
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. }
  2423. {
  2424. Headers headers = {make_range_header({{1, -1}})};
  2425. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2426. SKIP_ON_GATEWAY_ERROR(res);
  2427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2428. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2430. }
  2431. {
  2432. Headers headers = {make_range_header({{1, 10}})};
  2433. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2434. SKIP_ON_GATEWAY_ERROR(res);
  2435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2436. EXPECT_EQ("bcdefghijk", res->body);
  2437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2438. }
  2439. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2440. // entire resource, while the original httpbin returned 200. Both are
  2441. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2442. {
  2443. Headers headers = {make_range_header({{0, 31}})};
  2444. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2445. SKIP_ON_GATEWAY_ERROR(res);
  2446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2447. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2448. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2449. res->status == StatusCode::PartialContent_206);
  2450. }
  2451. {
  2452. Headers headers = {make_range_header({{0, -1}})};
  2453. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2454. SKIP_ON_GATEWAY_ERROR(res);
  2455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2456. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2457. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2458. res->status == StatusCode::PartialContent_206);
  2459. }
  2460. // go-httpbin returns 206 with clamped range for over-range requests,
  2461. // while the original httpbin returned 416. Both behaviors are observed
  2462. // in real servers, so we only verify the request succeeds.
  2463. {
  2464. Headers headers = {make_range_header({{0, 32}})};
  2465. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2466. SKIP_ON_GATEWAY_ERROR(res);
  2467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2468. }
  2469. }
  2470. TEST(RangeTest, IgnoredForPost) {
  2471. Server svr;
  2472. svr.Post("/", [](const Request &, Response &res) {
  2473. res.set_content("abcdefg", "text/plain");
  2474. });
  2475. auto port = svr.bind_to_any_port(HOST);
  2476. ASSERT_GT(port, 0);
  2477. thread t = thread([&] { svr.listen_after_bind(); });
  2478. auto se = detail::scope_exit([&] {
  2479. svr.stop();
  2480. t.join();
  2481. ASSERT_FALSE(svr.is_running());
  2482. });
  2483. svr.wait_until_ready();
  2484. Client cli(HOST, port);
  2485. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2486. auto res = cli.Post("/", Headers{{"Range", range}});
  2487. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2488. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2489. EXPECT_EQ("abcdefg", res->body) << range;
  2490. }
  2491. }
  2492. TEST(RangeTest, IgnoredForUnknownUnit) {
  2493. Server svr;
  2494. svr.Get("/", [](const Request &, Response &res) {
  2495. res.set_content("abcdefg", "text/plain");
  2496. });
  2497. auto port = svr.bind_to_any_port(HOST);
  2498. ASSERT_GT(port, 0);
  2499. thread t = thread([&] { svr.listen_after_bind(); });
  2500. auto se = detail::scope_exit([&] {
  2501. svr.stop();
  2502. t.join();
  2503. ASSERT_FALSE(svr.is_running());
  2504. });
  2505. svr.wait_until_ready();
  2506. Client cli(HOST, port);
  2507. for (auto range : {"items=1-2", "none=x"}) {
  2508. auto res = cli.Get("/", Headers{{"Range", range}});
  2509. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2510. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2511. EXPECT_EQ("abcdefg", res->body) << range;
  2512. }
  2513. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2514. ASSERT_TRUE(res) << to_string(res.error());
  2515. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2516. }
  2517. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2518. auto host = "unresolvableaddress.local";
  2519. auto path = std::string{"/"};
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 443;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 80;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(1);
  2528. {
  2529. auto res = cli.Get(path);
  2530. ASSERT_FALSE(res);
  2531. }
  2532. std::this_thread::sleep_for(std::chrono::seconds(8));
  2533. }
  2534. #if defined(__linux__) && defined(__GLIBC__) && \
  2535. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2536. // Forward declaration: in split builds split.py strips `inline` and moves the
  2537. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2538. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2539. // against the symbol in both header-only and split builds.
  2540. namespace httplib {
  2541. namespace detail {
  2542. int getaddrinfo_with_timeout(const char *node, const char *service,
  2543. const struct addrinfo *hints,
  2544. struct addrinfo **res, time_t timeout_sec);
  2545. } // namespace detail
  2546. } // namespace httplib
  2547. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2548. //
  2549. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2550. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2551. // gai_suspend() call hits the connection timeout the function calls
  2552. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2553. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2554. // still alive and still references the now-destroyed stack frame.
  2555. //
  2556. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2557. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2558. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2559. // and runs them in a container.
  2560. namespace {
  2561. bool should_run_issue_2431_tests() {
  2562. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2563. return v && *v && std::string(v) != "0";
  2564. }
  2565. std::string unique_unresolvable_host(int n) {
  2566. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2567. // glibc still asks the configured nameserver — which is exactly the path
  2568. // we want to exercise. A unique label per call avoids the resolver cache.
  2569. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2570. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2571. std::to_string(n) + ".invalid";
  2572. }
  2573. } // namespace
  2574. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2575. if (!should_run_issue_2431_tests()) {
  2576. GTEST_SKIP()
  2577. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2578. }
  2579. for (int i = 0; i < 8; ++i) {
  2580. struct addrinfo hints;
  2581. memset(&hints, 0, sizeof(hints));
  2582. hints.ai_family = AF_UNSPEC;
  2583. hints.ai_socktype = SOCK_STREAM;
  2584. auto host = unique_unresolvable_host(i);
  2585. struct addrinfo *result = nullptr;
  2586. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2587. &result, /*timeout_sec=*/1);
  2588. if (rc == 0 && result) { freeaddrinfo(result); }
  2589. }
  2590. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2591. // stack region they still believe holds their gaicb.
  2592. std::this_thread::sleep_for(std::chrono::seconds(3));
  2593. }
  2594. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2595. if (!should_run_issue_2431_tests()) {
  2596. GTEST_SKIP()
  2597. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2598. }
  2599. std::atomic<bool> stop{false};
  2600. std::vector<std::thread> threads;
  2601. for (int t = 0; t < 8; ++t) {
  2602. threads.emplace_back([t, &stop] {
  2603. int i = 0;
  2604. while (!stop.load(std::memory_order_relaxed)) {
  2605. struct addrinfo hints;
  2606. memset(&hints, 0, sizeof(hints));
  2607. hints.ai_family = AF_UNSPEC;
  2608. hints.ai_socktype = SOCK_STREAM;
  2609. auto host = unique_unresolvable_host(t * 100000 + i++);
  2610. struct addrinfo *result = nullptr;
  2611. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2612. &result, /*timeout_sec=*/1);
  2613. if (rc == 0 && result) { freeaddrinfo(result); }
  2614. }
  2615. });
  2616. }
  2617. std::this_thread::sleep_for(std::chrono::seconds(8));
  2618. stop.store(true, std::memory_order_relaxed);
  2619. for (auto &th : threads) {
  2620. th.join();
  2621. }
  2622. std::this_thread::sleep_for(std::chrono::seconds(3));
  2623. }
  2624. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2625. if (!should_run_issue_2431_tests()) {
  2626. GTEST_SKIP()
  2627. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2628. }
  2629. std::atomic<bool> stop{false};
  2630. std::vector<std::thread> threads;
  2631. for (int t = 0; t < 8; ++t) {
  2632. threads.emplace_back([t, &stop] {
  2633. int i = 0;
  2634. while (!stop.load(std::memory_order_relaxed)) {
  2635. auto host = unique_unresolvable_host(t * 100000 + i++);
  2636. Client cli(host, 80);
  2637. cli.set_connection_timeout(1, 0);
  2638. cli.set_read_timeout(1, 0);
  2639. cli.set_write_timeout(1, 0);
  2640. (void)cli.Get("/");
  2641. }
  2642. });
  2643. }
  2644. std::this_thread::sleep_for(std::chrono::seconds(8));
  2645. stop.store(true, std::memory_order_relaxed);
  2646. for (auto &th : threads) {
  2647. th.join();
  2648. }
  2649. std::this_thread::sleep_for(std::chrono::seconds(3));
  2650. }
  2651. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2652. TEST(ConnectionErrorTest, InvalidHost) {
  2653. auto host = "-abcde.com";
  2654. #ifdef CPPHTTPLIB_SSL_ENABLED
  2655. auto port = 443;
  2656. SSLClient cli(host, port);
  2657. #else
  2658. auto port = 80;
  2659. Client cli(host, port);
  2660. #endif
  2661. cli.set_connection_timeout(std::chrono::seconds(2));
  2662. auto res = cli.Get("/");
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_EQ(Error::Connection, res.error());
  2665. }
  2666. TEST(ConnectionErrorTest, InvalidHost2) {
  2667. auto host = "httpcan.org/";
  2668. #ifdef CPPHTTPLIB_SSL_ENABLED
  2669. SSLClient cli(host);
  2670. #else
  2671. Client cli(host);
  2672. #endif
  2673. cli.set_connection_timeout(std::chrono::seconds(2));
  2674. auto res = cli.Get("/");
  2675. ASSERT_TRUE(!res);
  2676. EXPECT_EQ(Error::Connection, res.error());
  2677. }
  2678. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2679. auto host = "httpcan.org/";
  2680. #ifdef CPPHTTPLIB_SSL_ENABLED
  2681. SSLClient cli(host);
  2682. #else
  2683. Client cli(host);
  2684. #endif
  2685. cli.set_connection_timeout(std::chrono::seconds(2));
  2686. auto res = cli.Get("/");
  2687. ASSERT_TRUE(!res);
  2688. stringstream s;
  2689. s << "error code: " << res.error();
  2690. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2691. }
  2692. TEST(ConnectionErrorTest, InvalidPort) {
  2693. auto host = "localhost";
  2694. auto port = 44380;
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. SSLClient cli(host, port);
  2697. #else
  2698. Client cli(host, port);
  2699. #endif
  2700. cli.set_connection_timeout(std::chrono::seconds(2));
  2701. auto res = cli.Get("/");
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_TRUE(Error::Connection == res.error() ||
  2704. Error::ConnectionTimeout == res.error());
  2705. }
  2706. TEST(ConnectionErrorTest, Timeout_Online) {
  2707. auto host = "google.com";
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. auto port = 44380;
  2710. SSLClient cli(host, port);
  2711. #else
  2712. auto port = 8080;
  2713. Client cli(host, port);
  2714. #endif
  2715. cli.set_connection_timeout(std::chrono::seconds(2));
  2716. // only probe one address type so that the error reason
  2717. // correlates to the timed-out IPv4, not the unsupported
  2718. // IPv6 connection attempt
  2719. cli.set_address_family(AF_INET);
  2720. auto res = cli.Get("/");
  2721. ASSERT_TRUE(!res);
  2722. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2723. }
  2724. TEST(CancelTest, NoCancel_Online) {
  2725. auto host = "httpbingo.org";
  2726. auto path = std::string{"/range/32"};
  2727. #ifdef CPPHTTPLIB_SSL_ENABLED
  2728. auto port = 443;
  2729. SSLClient cli(host, port);
  2730. #else
  2731. auto port = 80;
  2732. Client cli(host, port);
  2733. #endif
  2734. cli.set_connection_timeout(std::chrono::seconds(5));
  2735. auto res = retry_gateway_errors(
  2736. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2737. SKIP_ON_GATEWAY_ERROR(res);
  2738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2739. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. }
  2742. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2743. // Use /bytes with a large payload so that the DownloadProgress callback
  2744. // (which only fires for Content-Length responses) is invoked before the
  2745. // entire body is received, giving cancellation a chance to fire.
  2746. auto host = "httpbingo.org";
  2747. auto path = std::string{"/bytes/524288"};
  2748. #ifdef CPPHTTPLIB_SSL_ENABLED
  2749. auto port = 443;
  2750. SSLClient cli(host, port);
  2751. #else
  2752. auto port = 80;
  2753. Client cli(host, port);
  2754. #endif
  2755. auto res = retry_gateway_errors(
  2756. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2757. SKIP_ON_GATEWAY_ERROR(res);
  2758. cli.set_connection_timeout(std::chrono::seconds(5));
  2759. ASSERT_TRUE(!res);
  2760. EXPECT_EQ(Error::Canceled, res.error());
  2761. }
  2762. TEST(CancelTest, WithCancelLargePayload_Online) {
  2763. auto host = "httpbingo.org";
  2764. auto path = std::string{"/bytes/524288"};
  2765. #ifdef CPPHTTPLIB_SSL_ENABLED
  2766. auto port = 443;
  2767. SSLClient cli(host, port);
  2768. #else
  2769. auto port = 80;
  2770. Client cli(host, port);
  2771. #endif
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res = retry_gateway_errors([&] {
  2774. auto count = 0;
  2775. return cli.Get(path,
  2776. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2777. });
  2778. SKIP_ON_GATEWAY_ERROR(res);
  2779. ASSERT_TRUE(!res);
  2780. EXPECT_EQ(Error::Canceled, res.error());
  2781. }
  2782. TEST(CancelTest, NoCancelPost) {
  2783. Server svr;
  2784. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content("Hello World!", "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_connection_timeout(std::chrono::seconds(5));
  2796. auto res =
  2797. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2798. "application/json", [](uint64_t, uint64_t) { return true; });
  2799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2800. EXPECT_EQ("Hello World!", res->body);
  2801. EXPECT_EQ(StatusCode::OK_200, res->status);
  2802. }
  2803. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2804. Server svr;
  2805. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2809. auto se = detail::scope_exit([&] {
  2810. svr.stop();
  2811. thread.join();
  2812. ASSERT_FALSE(svr.is_running());
  2813. });
  2814. svr.wait_until_ready();
  2815. Client cli(HOST, PORT);
  2816. cli.set_connection_timeout(std::chrono::seconds(5));
  2817. auto res =
  2818. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2819. "application/json", [](uint64_t, uint64_t) { return false; });
  2820. ASSERT_TRUE(!res);
  2821. EXPECT_EQ(Error::Canceled, res.error());
  2822. }
  2823. TEST(CancelTest, WithCancelLargePayloadPost) {
  2824. Server svr;
  2825. svr.set_payload_max_length(200 * 1024 * 1024);
  2826. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2827. res.set_content(LARGE_DATA, "text/plain");
  2828. });
  2829. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2830. auto se = detail::scope_exit([&] {
  2831. svr.stop();
  2832. thread.join();
  2833. ASSERT_FALSE(svr.is_running());
  2834. });
  2835. svr.wait_until_ready();
  2836. Client cli(HOST, PORT);
  2837. cli.set_payload_max_length(200 * 1024 * 1024);
  2838. cli.set_connection_timeout(std::chrono::seconds(5));
  2839. auto res =
  2840. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2841. "application/json", [](uint64_t, uint64_t) { return false; });
  2842. ASSERT_TRUE(!res);
  2843. EXPECT_EQ(Error::Canceled, res.error());
  2844. }
  2845. TEST(CancelTest, NoCancelPut) {
  2846. Server svr;
  2847. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2848. res.set_content("Hello World!", "text/plain");
  2849. });
  2850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2851. auto se = detail::scope_exit([&] {
  2852. svr.stop();
  2853. thread.join();
  2854. ASSERT_FALSE(svr.is_running());
  2855. });
  2856. svr.wait_until_ready();
  2857. Client cli(HOST, PORT);
  2858. cli.set_connection_timeout(std::chrono::seconds(5));
  2859. auto res =
  2860. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2861. "application/json", [](uint64_t, uint64_t) { return true; });
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. EXPECT_EQ("Hello World!", res->body);
  2864. EXPECT_EQ(StatusCode::OK_200, res->status);
  2865. }
  2866. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2867. Server svr;
  2868. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2869. res.set_content("Hello World!", "text/plain");
  2870. });
  2871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2872. auto se = detail::scope_exit([&] {
  2873. svr.stop();
  2874. thread.join();
  2875. ASSERT_FALSE(svr.is_running());
  2876. });
  2877. svr.wait_until_ready();
  2878. Client cli(HOST, PORT);
  2879. cli.set_connection_timeout(std::chrono::seconds(5));
  2880. auto res =
  2881. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2882. "application/json", [](uint64_t, uint64_t) { return false; });
  2883. ASSERT_TRUE(!res);
  2884. EXPECT_EQ(Error::Canceled, res.error());
  2885. }
  2886. TEST(CancelTest, WithCancelLargePayloadPut) {
  2887. Server svr;
  2888. svr.set_payload_max_length(200 * 1024 * 1024);
  2889. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2890. res.set_content(LARGE_DATA, "text/plain");
  2891. });
  2892. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2893. auto se = detail::scope_exit([&] {
  2894. svr.stop();
  2895. thread.join();
  2896. ASSERT_FALSE(svr.is_running());
  2897. });
  2898. svr.wait_until_ready();
  2899. Client cli(HOST, PORT);
  2900. cli.set_payload_max_length(200 * 1024 * 1024);
  2901. cli.set_connection_timeout(std::chrono::seconds(5));
  2902. auto res =
  2903. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2904. "application/json", [](uint64_t, uint64_t) { return false; });
  2905. ASSERT_TRUE(!res);
  2906. EXPECT_EQ(Error::Canceled, res.error());
  2907. }
  2908. TEST(CancelTest, NoCancelPatch) {
  2909. Server svr;
  2910. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2911. res.set_content("Hello World!", "text/plain");
  2912. });
  2913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2914. auto se = detail::scope_exit([&] {
  2915. svr.stop();
  2916. thread.join();
  2917. ASSERT_FALSE(svr.is_running());
  2918. });
  2919. svr.wait_until_ready();
  2920. Client cli(HOST, PORT);
  2921. cli.set_connection_timeout(std::chrono::seconds(5));
  2922. auto res =
  2923. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2924. "application/json", [](uint64_t, uint64_t) { return true; });
  2925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2926. EXPECT_EQ("Hello World!", res->body);
  2927. EXPECT_EQ(StatusCode::OK_200, res->status);
  2928. }
  2929. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2930. Server svr;
  2931. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2932. res.set_content("Hello World!", "text/plain");
  2933. });
  2934. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2935. auto se = detail::scope_exit([&] {
  2936. svr.stop();
  2937. thread.join();
  2938. ASSERT_FALSE(svr.is_running());
  2939. });
  2940. svr.wait_until_ready();
  2941. Client cli(HOST, PORT);
  2942. cli.set_connection_timeout(std::chrono::seconds(5));
  2943. auto res =
  2944. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2945. "application/json", [](uint64_t, uint64_t) { return false; });
  2946. ASSERT_TRUE(!res);
  2947. EXPECT_EQ(Error::Canceled, res.error());
  2948. }
  2949. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2950. Server svr;
  2951. svr.set_payload_max_length(200 * 1024 * 1024);
  2952. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2953. res.set_content(LARGE_DATA, "text/plain");
  2954. });
  2955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2956. auto se = detail::scope_exit([&] {
  2957. svr.stop();
  2958. thread.join();
  2959. ASSERT_FALSE(svr.is_running());
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, PORT);
  2963. cli.set_payload_max_length(200 * 1024 * 1024);
  2964. cli.set_connection_timeout(std::chrono::seconds(5));
  2965. auto res =
  2966. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2967. "application/json", [](uint64_t, uint64_t) { return false; });
  2968. ASSERT_TRUE(!res);
  2969. EXPECT_EQ(Error::Canceled, res.error());
  2970. }
  2971. TEST(CancelTest, NoCancelDelete) {
  2972. Server svr;
  2973. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2974. res.set_content("Hello World!", "text/plain");
  2975. });
  2976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. thread.join();
  2980. ASSERT_FALSE(svr.is_running());
  2981. });
  2982. svr.wait_until_ready();
  2983. Client cli(HOST, PORT);
  2984. cli.set_connection_timeout(std::chrono::seconds(5));
  2985. auto res =
  2986. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2987. "application/json", [](uint64_t, uint64_t) { return true; });
  2988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2989. EXPECT_EQ("Hello World!", res->body);
  2990. EXPECT_EQ(StatusCode::OK_200, res->status);
  2991. }
  2992. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2993. Server svr;
  2994. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2995. res.set_content("Hello World!", "text/plain");
  2996. });
  2997. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2998. auto se = detail::scope_exit([&] {
  2999. svr.stop();
  3000. thread.join();
  3001. ASSERT_FALSE(svr.is_running());
  3002. });
  3003. svr.wait_until_ready();
  3004. Client cli(HOST, PORT);
  3005. cli.set_connection_timeout(std::chrono::seconds(5));
  3006. auto res =
  3007. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3008. "application/json", [](uint64_t, uint64_t) { return false; });
  3009. ASSERT_TRUE(!res);
  3010. EXPECT_EQ(Error::Canceled, res.error());
  3011. }
  3012. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3013. Server svr;
  3014. svr.set_payload_max_length(200 * 1024 * 1024);
  3015. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3016. res.set_content(LARGE_DATA, "text/plain");
  3017. });
  3018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3019. auto se = detail::scope_exit([&] {
  3020. svr.stop();
  3021. thread.join();
  3022. ASSERT_FALSE(svr.is_running());
  3023. });
  3024. svr.wait_until_ready();
  3025. Client cli(HOST, PORT);
  3026. cli.set_payload_max_length(200 * 1024 * 1024);
  3027. cli.set_connection_timeout(std::chrono::seconds(5));
  3028. auto res =
  3029. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3030. "application/json", [](uint64_t, uint64_t) { return false; });
  3031. ASSERT_TRUE(!res);
  3032. EXPECT_EQ(Error::Canceled, res.error());
  3033. }
  3034. // One stop() from another thread ends a request that waits for the response
  3035. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3036. Server svr;
  3037. std::atomic<bool> received{false};
  3038. std::atomic<bool> done{false};
  3039. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3040. received.store(true);
  3041. while (!done.load()) {
  3042. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3043. }
  3044. res.set_content("Hello World!", "text/plain");
  3045. });
  3046. auto port = svr.bind_to_any_port(HOST);
  3047. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3048. Client cli(HOST, port);
  3049. cli.set_read_timeout(std::chrono::seconds(30));
  3050. std::future<Result> request;
  3051. auto se = detail::scope_exit([&] {
  3052. done.store(true);
  3053. svr.stop();
  3054. thread.join();
  3055. ASSERT_FALSE(svr.is_running());
  3056. });
  3057. svr.wait_until_ready();
  3058. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3059. for (int i = 0; i < 500 && !received.load(); ++i) {
  3060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3061. }
  3062. ASSERT_TRUE(received.load());
  3063. // Let the client block in the wait for the response
  3064. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3065. auto start = std::chrono::steady_clock::now();
  3066. cli.stop();
  3067. ASSERT_EQ(std::future_status::ready,
  3068. request.wait_for(std::chrono::seconds(5)));
  3069. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3070. auto res = request.get();
  3071. ASSERT_TRUE(!res);
  3072. EXPECT_EQ(Error::Read, res.error());
  3073. }
  3074. // A listener whose backlog completes the TCP connections of clients, and that
  3075. // never answers them
  3076. struct SilentListener {
  3077. socket_t sock = INVALID_SOCKET;
  3078. sockaddr_in addr{};
  3079. int port = 0;
  3080. explicit SilentListener(int backlog = 1) {
  3081. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3082. addr.sin_family = AF_INET;
  3083. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3084. socklen_t len = sizeof(addr);
  3085. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3086. ::listen(sock, backlog) != 0 ||
  3087. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3088. detail::close_socket(sock);
  3089. sock = INVALID_SOCKET;
  3090. }
  3091. port = ntohs(addr.sin_port);
  3092. }
  3093. ~SilentListener() { detail::close_socket(sock); }
  3094. // The next connection, whose reads give up after 5 seconds
  3095. socket_t accept() const {
  3096. auto peer = ::accept(sock, nullptr, nullptr);
  3097. if (peer != INVALID_SOCKET) {
  3098. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3099. }
  3100. return peer;
  3101. }
  3102. };
  3103. static bool receives_a_byte(socket_t peer) {
  3104. char c = 0;
  3105. return detail::read_socket(peer, &c, 1, 0) == 1;
  3106. }
  3107. // Runs op, stops cli once the listener receives the first byte op sends, and
  3108. // expects op to end with error soon after
  3109. template <typename ClientType, typename Op>
  3110. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3111. Op op, Error error = Error::Canceled) {
  3112. auto ended = std::async(std::launch::async, op);
  3113. auto peer = listener.accept();
  3114. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3115. ASSERT_NE(INVALID_SOCKET, peer);
  3116. ASSERT_TRUE(receives_a_byte(peer));
  3117. cli.stop();
  3118. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3119. EXPECT_EQ(error, ended.get());
  3120. }
  3121. // Stops itself from another thread as the connection opens, the last moment a
  3122. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3123. // waits for the connection fails the test instead of hanging it.
  3124. class StoppedAsConnectedClient : public ClientImpl {
  3125. public:
  3126. using ClientImpl::ClientImpl;
  3127. protected:
  3128. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3129. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3130. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3131. stopper_.wait_for(std::chrono::seconds(1));
  3132. return true;
  3133. }
  3134. private:
  3135. std::future<void> stopper_;
  3136. };
  3137. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3138. SilentListener listener;
  3139. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3140. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3141. cli.set_read_timeout(std::chrono::seconds(3));
  3142. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3143. auto peer = listener.accept();
  3144. EXPECT_FALSE(receives_a_byte(peer));
  3145. detail::close_socket(peer);
  3146. auto handle = cli.open_stream("GET", "/");
  3147. EXPECT_FALSE(handle.is_valid());
  3148. EXPECT_EQ(Error::Canceled, handle.error);
  3149. peer = listener.accept();
  3150. EXPECT_FALSE(receives_a_byte(peer));
  3151. detail::close_socket(peer);
  3152. }
  3153. #ifdef __linux__
  3154. // A connect that a listener with a full backlog never completes
  3155. TEST(ClientStopTest, StopEndsAConnect) {
  3156. SilentListener listener(0);
  3157. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3158. std::vector<socket_t> backlog;
  3159. auto close_backlog = detail::scope_exit([&] {
  3160. for (auto sock : backlog) {
  3161. detail::close_socket(sock);
  3162. }
  3163. });
  3164. for (int i = 0; i < 8; i++) {
  3165. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3166. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3167. sizeof(listener.addr));
  3168. backlog.push_back(sock);
  3169. }
  3170. Client cli("127.0.0.1", listener.port);
  3171. cli.set_connection_timeout(std::chrono::seconds(3));
  3172. auto ended =
  3173. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3174. // A stop() before the request starts does not apply to it, so it repeats
  3175. auto status = std::future_status::timeout;
  3176. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3177. cli.stop();
  3178. status = ended.wait_for(std::chrono::milliseconds(10));
  3179. }
  3180. EXPECT_EQ(std::future_status::ready, status);
  3181. EXPECT_EQ(Error::Canceled, ended.get());
  3182. }
  3183. #endif
  3184. // The stream holds the socket while it waits for the head, out of the reach
  3185. // of shutdown()
  3186. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3187. SilentListener listener;
  3188. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3189. Client cli("127.0.0.1", listener.port);
  3190. cli.set_read_timeout(std::chrono::seconds(3));
  3191. expect_stop_ends(
  3192. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3193. Error::Read);
  3194. }
  3195. #ifdef CPPHTTPLIB_SSL_ENABLED
  3196. // A server that never answers the ClientHello
  3197. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3198. SilentListener listener;
  3199. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3200. SSLClient cli("127.0.0.1", listener.port);
  3201. cli.enable_server_certificate_verification(false);
  3202. cli.set_connection_timeout(std::chrono::seconds(3));
  3203. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3204. expect_stop_ends(cli, listener,
  3205. [&] { return cli.open_stream("GET", "/").error; });
  3206. }
  3207. // A proxy that takes the CONNECT and never answers it
  3208. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3209. SilentListener listener;
  3210. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3211. SSLClient cli("example.com", 443);
  3212. cli.set_proxy("127.0.0.1", listener.port);
  3213. cli.set_read_timeout(std::chrono::seconds(3));
  3214. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3215. }
  3216. #endif
  3217. // A read timeout past what the clock reaches waits for the response
  3218. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3219. SilentListener listener;
  3220. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3221. Client cli("127.0.0.1", listener.port);
  3222. cli.set_read_timeout(
  3223. static_cast<time_t>((std::min)(static_cast<long long>(
  3224. (std::numeric_limits<time_t>::max)()),
  3225. 10000000000LL)),
  3226. 0);
  3227. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3228. auto peer = listener.accept();
  3229. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3230. ASSERT_NE(INVALID_SOCKET, peer);
  3231. ASSERT_TRUE(receives_a_byte(peer));
  3232. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3233. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3234. "Connection: close\r\n\r\nok";
  3235. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3236. auto result = res.get();
  3237. ASSERT_TRUE(result);
  3238. EXPECT_EQ("ok", result->body);
  3239. }
  3240. static std::string remove_whitespace(const std::string &input) {
  3241. std::string output;
  3242. output.reserve(input.size());
  3243. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3244. [](unsigned char c) { return !std::isspace(c); });
  3245. return output;
  3246. }
  3247. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3248. auto host = "httpbingo.org";
  3249. auto path = std::string{"/basic-auth/hello/world"};
  3250. #ifdef CPPHTTPLIB_SSL_ENABLED
  3251. auto port = 443;
  3252. SSLClient cli(host, port);
  3253. #else
  3254. auto port = 80;
  3255. Client cli(host, port);
  3256. #endif
  3257. {
  3258. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3259. SKIP_ON_GATEWAY_ERROR(res);
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3262. }
  3263. {
  3264. auto res = retry_gateway_errors([&] {
  3265. return cli.Get(
  3266. path, Headers{make_basic_authentication_header("hello", "world")});
  3267. });
  3268. SKIP_ON_GATEWAY_ERROR(res);
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. auto body = remove_whitespace(res->body);
  3271. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3272. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3273. EXPECT_EQ(StatusCode::OK_200, res->status);
  3274. }
  3275. {
  3276. cli.set_basic_auth("hello", "world");
  3277. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3278. SKIP_ON_GATEWAY_ERROR(res);
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. auto body = remove_whitespace(res->body);
  3281. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3282. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. }
  3285. {
  3286. cli.set_basic_auth("hello", "bad");
  3287. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3288. SKIP_ON_GATEWAY_ERROR(res);
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3291. }
  3292. {
  3293. cli.set_basic_auth("bad", "world");
  3294. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3295. SKIP_ON_GATEWAY_ERROR(res);
  3296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3297. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3298. }
  3299. }
  3300. #ifdef CPPHTTPLIB_SSL_ENABLED
  3301. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3302. auto host = "httpbingo.org";
  3303. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3304. auto paths = std::vector<std::string>{
  3305. "/digest-auth/auth/hello/world/MD5",
  3306. "/digest-auth/auth/hello/world/SHA-256",
  3307. };
  3308. auto port = 443;
  3309. SSLClient cli(host, port);
  3310. {
  3311. auto res = retry_gateway_errors([&] { return cli.Get(unauth_path); });
  3312. SKIP_ON_GATEWAY_ERROR(res);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3315. }
  3316. {
  3317. cli.set_digest_auth("hello", "world");
  3318. for (const auto &path : paths) {
  3319. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3320. SKIP_ON_GATEWAY_ERROR(res);
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. auto body = remove_whitespace(res->body);
  3323. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3324. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3325. EXPECT_EQ(StatusCode::OK_200, res->status);
  3326. }
  3327. cli.set_digest_auth("hello", "bad");
  3328. for (const auto &path : paths) {
  3329. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3330. SKIP_ON_GATEWAY_ERROR(res);
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3333. }
  3334. }
  3335. }
  3336. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3337. // comma-separated list of challenges, and each challenge may itself carry a
  3338. // comma-separated auth-param list, so a server can legally offer Basic
  3339. // before Digest, either as two field lines or packed into one. Runs one 401
  3340. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3341. // value() joins them in receipt order) and checks that the retry carries a
  3342. // well-formed Digest Authorization header naming expected_realm.
  3343. static void
  3344. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3345. const std::string &expected_realm) {
  3346. std::atomic<int> hits{0};
  3347. Server svr;
  3348. svr.Get("/x", [&](const Request &req, Response &res) {
  3349. if (++hits == 1) {
  3350. res.status = StatusCode::Unauthorized_401;
  3351. for (const auto &challenge : challenges) {
  3352. res.set_header("WWW-Authenticate", challenge);
  3353. }
  3354. } else {
  3355. auto authorization = req.get_header_value("Authorization");
  3356. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3357. EXPECT_NE(std::string::npos,
  3358. authorization.find("realm=\"" + expected_realm + "\""));
  3359. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3360. res.set_content("ok", "text/plain");
  3361. }
  3362. });
  3363. auto port = svr.bind_to_any_port(HOST);
  3364. std::thread t([&]() { svr.listen_after_bind(); });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. t.join();
  3368. });
  3369. svr.wait_until_ready();
  3370. Client cli(HOST, port);
  3371. cli.set_digest_auth("hello", "world");
  3372. auto res = cli.Get("/x");
  3373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3374. EXPECT_EQ(2, hits.load());
  3375. }
  3376. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3377. static const char *kDigestChallenge =
  3378. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3379. "algorithm=MD5";
  3380. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3381. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3382. "testrealm");
  3383. }
  3384. // Same challenge list with the schemes in the opposite order, to make sure
  3385. // the fix above didn't just special-case "Basic first".
  3386. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3387. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3388. "testrealm");
  3389. }
  3390. // A comma inside a quoted auth-param value must not be mistaken for the
  3391. // separator between two challenges (or two auth-params).
  3392. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3393. run_digest_challenge_list_test(
  3394. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3395. "algorithm=MD5"},
  3396. "test,realm");
  3397. }
  3398. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3399. // the params and leaves out the fragment.
  3400. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3401. Server svr;
  3402. std::string uri, target;
  3403. svr.Get("/a b", [&](const Request &req, Response &res) {
  3404. auto auth = req.get_header_value("Authorization");
  3405. if (auth.empty()) {
  3406. res.status = StatusCode::Unauthorized_401;
  3407. res.set_header("WWW-Authenticate",
  3408. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3409. return;
  3410. }
  3411. auto b = auth.find("uri=\"") + 5;
  3412. uri = auth.substr(b, auth.find('"', b) - b);
  3413. target = req.target;
  3414. });
  3415. auto port = svr.bind_to_any_port(HOST);
  3416. std::thread t([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. t.join();
  3420. });
  3421. svr.wait_until_ready();
  3422. Client cli(HOST, port);
  3423. cli.set_digest_auth("hello", "world");
  3424. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3426. EXPECT_EQ("/a%20b?x=1", target);
  3427. EXPECT_EQ(target, uri);
  3428. }
  3429. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3430. // make_digest_authentication_header() dereferences both unconditionally, so
  3431. // a server sending a challenge missing either one must not be treated as
  3432. // usable -- doing so used to crash the client with std::out_of_range.
  3433. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3434. Server svr;
  3435. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3436. res.status = StatusCode::Unauthorized_401;
  3437. res.set_header("WWW-Authenticate", challenge);
  3438. });
  3439. auto port = svr.bind_to_any_port(HOST);
  3440. std::thread t([&]() { svr.listen_after_bind(); });
  3441. auto se = detail::scope_exit([&] {
  3442. svr.stop();
  3443. t.join();
  3444. });
  3445. svr.wait_until_ready();
  3446. Client cli(HOST, port);
  3447. cli.set_digest_auth("hello", "world");
  3448. auto res = cli.Get("/x");
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3451. }
  3452. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3453. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3454. }
  3455. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3456. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3457. }
  3458. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3459. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3460. }
  3461. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3462. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3463. // when storing the values, so the header builder has to re-escape them (and
  3464. // keep algorithm a bare token); otherwise the value breaks out of its
  3465. // quoted-string and injects extra auth-params into the client's Authorization.
  3466. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3467. std::atomic<int> hits{0};
  3468. std::string authorization;
  3469. Server svr;
  3470. svr.Get("/x", [&](const Request &req, Response &res) {
  3471. if (++hits == 1) {
  3472. res.status = StatusCode::Unauthorized_401;
  3473. // On the wire the quotes embedded in the values are backslash-escaped.
  3474. res.set_header("WWW-Authenticate",
  3475. "Digest realm=\"testrealm\", "
  3476. "nonce=\"n\\\"; injected=\\\"x\", "
  3477. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3478. } else {
  3479. authorization = req.get_header_value("Authorization");
  3480. res.set_content("ok", "text/plain");
  3481. }
  3482. });
  3483. auto port = svr.bind_to_any_port(HOST);
  3484. std::thread t([&]() { svr.listen_after_bind(); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. t.join();
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_digest_auth("hello", "world");
  3492. auto res = cli.Get("/x");
  3493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3494. EXPECT_EQ(2, hits.load());
  3495. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3496. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3497. // inside its quoted-string rather than starting an "injected" auth-param.
  3498. EXPECT_NE(std::string::npos,
  3499. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3500. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3501. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3502. }
  3503. #endif
  3504. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3505. auto host = "google.com";
  3506. auto another_host = "example.com";
  3507. auto wrong_ip = "0.0.0.0";
  3508. #ifdef CPPHTTPLIB_SSL_ENABLED
  3509. SSLClient cli(host);
  3510. #else
  3511. Client cli(host);
  3512. #endif
  3513. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3514. auto res = cli.Get("/");
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3517. }
  3518. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3519. auto host = "google.com";
  3520. auto wrong_ip = "0.0.0.0";
  3521. #ifdef CPPHTTPLIB_SSL_ENABLED
  3522. SSLClient cli(host);
  3523. #else
  3524. Client cli(host);
  3525. #endif
  3526. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3527. auto res = cli.Get("/");
  3528. ASSERT_TRUE(!res);
  3529. EXPECT_EQ(Error::Connection, res.error());
  3530. }
  3531. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3532. // A mapped value that is not an IP literal must be resolved. "localhost"
  3533. // resolves from the hosts file, so this test needs no external DNS.
  3534. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3535. auto host = "target.invalid";
  3536. Server svr;
  3537. std::string received_host;
  3538. svr.Get("/hi", [&](const Request &req, Response &res) {
  3539. received_host = req.get_header_value("Host");
  3540. res.set_content("Hello World!", "text/plain");
  3541. });
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3544. auto se = detail::scope_exit([&] {
  3545. svr.stop();
  3546. thread.join();
  3547. ASSERT_FALSE(svr.is_running());
  3548. });
  3549. svr.wait_until_ready();
  3550. Client cli(host, port);
  3551. cli.set_direct_hostname_addr_map({{host, HOST}});
  3552. auto res = cli.Get("/hi");
  3553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3554. EXPECT_EQ(StatusCode::OK_200, res->status);
  3555. // The mapping only redirects the connection; the identity stays host_.
  3556. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3557. }
  3558. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3559. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3560. auto host = "target.invalid";
  3561. Server svr;
  3562. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3563. res.set_content("Hello World!", "text/plain");
  3564. });
  3565. auto port = svr.bind_to_any_port("127.0.0.1");
  3566. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client cli(host, port);
  3574. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3575. auto res = cli.Get("/hi");
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ(StatusCode::OK_200, res->status);
  3578. }
  3579. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3580. // An empty mapped value must leave host_ as the connection target. Without
  3581. // that guard the empty value would become the host argument, getaddrinfo
  3582. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3583. // loopback - silently connecting somewhere the caller never asked for.
  3584. // The server listens on loopback, so such a fallback would succeed and is
  3585. // therefore observable as a failure of this test.
  3586. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3587. Server svr;
  3588. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3589. res.set_content("Hello World!", "text/plain");
  3590. });
  3591. auto port = svr.bind_to_any_port(HOST);
  3592. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3593. auto se = detail::scope_exit([&] {
  3594. svr.stop();
  3595. thread.join();
  3596. ASSERT_FALSE(svr.is_running());
  3597. });
  3598. svr.wait_until_ready();
  3599. Client cli(blackhole, port);
  3600. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3601. cli.set_connection_timeout(1);
  3602. auto res = cli.Get("/hi");
  3603. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3604. }
  3605. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3606. auto host = "target.invalid";
  3607. Server svr;
  3608. std::string received_host;
  3609. svr.Get("/hi", [&](const Request &req, Response &res) {
  3610. received_host = req.get_header_value("Host");
  3611. res.set_content("Hello World!", "text/plain");
  3612. });
  3613. auto port = svr.bind_to_any_port("127.0.0.1");
  3614. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3615. auto se = detail::scope_exit([&] {
  3616. svr.stop();
  3617. thread.join();
  3618. ASSERT_FALSE(svr.is_running());
  3619. });
  3620. svr.wait_until_ready();
  3621. Client cli(host, port);
  3622. #pragma GCC diagnostic push
  3623. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3624. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3625. #pragma GCC diagnostic pop
  3626. auto res = cli.Get("/hi");
  3627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3628. EXPECT_EQ(StatusCode::OK_200, res->status);
  3629. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3630. }
  3631. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3632. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3633. Server svr;
  3634. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3635. res.set_content("Hello World!", "text/plain");
  3636. });
  3637. auto port = svr.bind_to_any_port("127.0.0.1");
  3638. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3639. auto se = detail::scope_exit([&] {
  3640. svr.stop();
  3641. thread.join();
  3642. ASSERT_FALSE(svr.is_running());
  3643. });
  3644. svr.wait_until_ready();
  3645. Client cli("127.0.0.1", port);
  3646. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3647. cli.set_connection_timeout(1);
  3648. auto res = cli.Get("/hi");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::OK_200, res->status);
  3651. }
  3652. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3653. auto host = "httpbingo.org";
  3654. auto path = std::string{"/absolute-redirect/3"};
  3655. #ifdef CPPHTTPLIB_SSL_ENABLED
  3656. SSLClient cli(host);
  3657. #else
  3658. Client cli(host);
  3659. #endif
  3660. cli.set_follow_location(true);
  3661. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3662. SKIP_ON_GATEWAY_ERROR(res);
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. }
  3666. TEST(RedirectTest, Redirect_Online) {
  3667. auto host = "httpbingo.org";
  3668. auto path = std::string{"/redirect/3"};
  3669. #ifdef CPPHTTPLIB_SSL_ENABLED
  3670. SSLClient cli(host);
  3671. #else
  3672. Client cli(host);
  3673. #endif
  3674. cli.set_follow_location(true);
  3675. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3676. SKIP_ON_GATEWAY_ERROR(res);
  3677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3678. EXPECT_EQ(StatusCode::OK_200, res->status);
  3679. }
  3680. TEST(RelativeRedirectTest, Redirect_Online) {
  3681. auto host = "httpbingo.org";
  3682. auto path = std::string{"/relative-redirect/3"};
  3683. #ifdef CPPHTTPLIB_SSL_ENABLED
  3684. SSLClient cli(host);
  3685. #else
  3686. Client cli(host);
  3687. #endif
  3688. cli.set_follow_location(true);
  3689. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3690. SKIP_ON_GATEWAY_ERROR(res);
  3691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3692. EXPECT_EQ(StatusCode::OK_200, res->status);
  3693. }
  3694. TEST(TooManyRedirectTest, Redirect_Online) {
  3695. auto host = "httpbingo.org";
  3696. auto path = std::string{"/redirect/21"};
  3697. #ifdef CPPHTTPLIB_SSL_ENABLED
  3698. SSLClient cli(host);
  3699. #else
  3700. Client cli(host);
  3701. #endif
  3702. cli.set_follow_location(true);
  3703. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3704. SKIP_ON_GATEWAY_ERROR(res);
  3705. ASSERT_TRUE(!res);
  3706. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3707. }
  3708. #ifdef CPPHTTPLIB_SSL_ENABLED
  3709. TEST(YahooRedirectTest, Redirect_Online) {
  3710. Client cli("yahoo.com");
  3711. auto res = cli.Get("/");
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3714. cli.set_follow_location(true);
  3715. res = cli.Get("/");
  3716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3717. EXPECT_EQ(StatusCode::OK_200, res->status);
  3718. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3719. }
  3720. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3721. #define REDIR_HOST "httpbingo.org"
  3722. #define REDIR_PATH "/redirect-to"
  3723. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3724. SSLClient cli(REDIR_HOST);
  3725. cli.set_follow_location(true);
  3726. auto res = retry_gateway_errors([&] {
  3727. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3728. });
  3729. SKIP_ON_GATEWAY_ERROR(res);
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. }
  3733. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3734. SSLClient cli(REDIR_HOST);
  3735. cli.set_follow_location(true);
  3736. Params params;
  3737. params.emplace("url", "http://example.com");
  3738. params.emplace("status_code", "302");
  3739. auto res = retry_gateway_errors(
  3740. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3741. SKIP_ON_GATEWAY_ERROR(res);
  3742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3743. EXPECT_EQ(StatusCode::OK_200, res->status);
  3744. }
  3745. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3746. SSLClient cli(REDIR_HOST);
  3747. cli.set_follow_location(true);
  3748. Params params;
  3749. params.emplace("url", "http://example.com");
  3750. auto res = retry_gateway_errors([&] {
  3751. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3752. });
  3753. SKIP_ON_GATEWAY_ERROR(res);
  3754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3755. EXPECT_EQ(StatusCode::OK_200, res->status);
  3756. }
  3757. TEST(UrlWithSpace, Redirect_Online) {
  3758. SSLClient cli("edge.forgecdn.net");
  3759. cli.set_follow_location(true);
  3760. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3764. }
  3765. #endif
  3766. #if !defined(_WIN32) && !defined(_WIN64)
  3767. TEST(ReceiveSignals, Signal) {
  3768. auto setupSignalHandlers = []() {
  3769. struct sigaction act;
  3770. sigemptyset(&act.sa_mask);
  3771. act.sa_flags = SA_SIGINFO;
  3772. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3773. switch (sig) {
  3774. case SIGINT:
  3775. default: break;
  3776. }
  3777. };
  3778. ::sigaction(SIGINT, &act, nullptr);
  3779. };
  3780. Server svr;
  3781. int port = 0;
  3782. auto thread = std::thread([&]() {
  3783. setupSignalHandlers();
  3784. port = svr.bind_to_any_port(HOST);
  3785. svr.listen_after_bind();
  3786. });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. ASSERT_TRUE(svr.is_running());
  3794. pthread_kill(thread.native_handle(), SIGINT);
  3795. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3796. ASSERT_TRUE(svr.is_running());
  3797. }
  3798. #endif
  3799. TEST(RedirectToDifferentPort, Redirect) {
  3800. Server svr1;
  3801. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3802. res.set_content("Hello World!", "text/plain");
  3803. });
  3804. int svr1_port = 0;
  3805. auto thread1 = std::thread([&]() {
  3806. svr1_port = svr1.bind_to_any_port(HOST);
  3807. svr1.listen_after_bind();
  3808. });
  3809. Server svr2;
  3810. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3811. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3812. });
  3813. int svr2_port = 0;
  3814. auto thread2 = std::thread([&]() {
  3815. svr2_port = svr2.bind_to_any_port(HOST);
  3816. svr2.listen_after_bind();
  3817. });
  3818. auto se = detail::scope_exit([&] {
  3819. svr2.stop();
  3820. thread2.join();
  3821. svr1.stop();
  3822. thread1.join();
  3823. ASSERT_FALSE(svr2.is_running());
  3824. ASSERT_FALSE(svr1.is_running());
  3825. });
  3826. svr1.wait_until_ready();
  3827. svr2.wait_until_ready();
  3828. Client cli("localhost", svr2_port);
  3829. cli.set_follow_location(true);
  3830. auto res = cli.Get("/2");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("Hello World!", res->body);
  3834. }
  3835. // GET /redir on one server redirects to /target on another port, so the
  3836. // client follows it with a new client.
  3837. static Result
  3838. GetThroughRedirectToDifferentPort(Server::Handler target,
  3839. const std::function<void(Client &)> &setup,
  3840. const Headers &headers = Headers()) {
  3841. Server target_svr;
  3842. target_svr.Get("/target", target);
  3843. int target_port = 0;
  3844. auto target_thread = std::thread([&]() {
  3845. target_port = target_svr.bind_to_any_port(HOST);
  3846. target_svr.listen_after_bind();
  3847. });
  3848. Server origin_svr;
  3849. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3850. res.set_redirect(
  3851. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3852. });
  3853. int origin_port = 0;
  3854. auto origin_thread = std::thread([&]() {
  3855. origin_port = origin_svr.bind_to_any_port(HOST);
  3856. origin_svr.listen_after_bind();
  3857. });
  3858. auto se = detail::scope_exit([&] {
  3859. origin_svr.stop();
  3860. origin_thread.join();
  3861. target_svr.stop();
  3862. target_thread.join();
  3863. });
  3864. target_svr.wait_until_ready();
  3865. origin_svr.wait_until_ready();
  3866. Client cli("localhost", origin_port);
  3867. cli.set_follow_location(true);
  3868. setup(cli);
  3869. return cli.Get("/redir", headers);
  3870. }
  3871. static void
  3872. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3873. std::string captured_authorization;
  3874. auto result = GetThroughRedirectToDifferentPort(
  3875. [&](const Request &req, Response &res) {
  3876. captured_authorization = req.get_header_value("Authorization");
  3877. res.set_content("OK", "text/plain");
  3878. },
  3879. set_auth);
  3880. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3881. EXPECT_EQ(StatusCode::OK_200, result->status);
  3882. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3883. EXPECT_TRUE(captured_authorization.empty());
  3884. }
  3885. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3886. TestDoNotForwardCredentialsOnRedirect(
  3887. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3888. }
  3889. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3890. TestDoNotForwardCredentialsOnRedirect(
  3891. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3892. }
  3893. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3894. std::string captured_cookie;
  3895. auto result = GetThroughRedirectToDifferentPort(
  3896. [&](const Request &req, Response &res) {
  3897. captured_cookie = req.get_header_value("Cookie");
  3898. res.set_content("OK", "text/plain");
  3899. },
  3900. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3901. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3902. EXPECT_EQ(StatusCode::OK_200, result->status);
  3903. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3904. EXPECT_TRUE(captured_cookie.empty());
  3905. }
  3906. TEST(RedirectToSamePort, ForwardCookie) {
  3907. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3908. // header so that ordinary session flows keep working.
  3909. Server svr;
  3910. std::string captured_cookie;
  3911. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3912. res.set_redirect("/target", 302);
  3913. });
  3914. svr.Get("/target", [&](const Request &req, Response &res) {
  3915. captured_cookie = req.get_header_value("Cookie");
  3916. res.set_content("OK", "text/plain");
  3917. });
  3918. auto port = svr.bind_to_any_port(HOST);
  3919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3920. auto se = detail::scope_exit([&] {
  3921. svr.stop();
  3922. thread.join();
  3923. ASSERT_FALSE(svr.is_running());
  3924. });
  3925. svr.wait_until_ready();
  3926. Client cli(HOST, port);
  3927. cli.set_follow_location(true);
  3928. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3929. auto res = cli.Get("/redir", headers);
  3930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3933. }
  3934. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3935. // The Location alone names the next target, on any origin.
  3936. Server target_svr;
  3937. std::string cross_target;
  3938. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3939. cross_target = req.target;
  3940. res.set_content("OK", "text/plain");
  3941. });
  3942. auto target_port = target_svr.bind_to_any_port(HOST);
  3943. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3944. Server origin_svr;
  3945. std::string same_target;
  3946. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3947. res.set_redirect(
  3948. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3949. });
  3950. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3951. res.set_redirect("/landing", 302);
  3952. });
  3953. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3954. same_target = req.target;
  3955. res.set_content("OK", "text/plain");
  3956. });
  3957. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3958. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3959. auto se = detail::scope_exit([&] {
  3960. origin_svr.stop();
  3961. origin_thread.join();
  3962. target_svr.stop();
  3963. target_thread.join();
  3964. });
  3965. target_svr.wait_until_ready();
  3966. origin_svr.wait_until_ready();
  3967. Client cli("localhost", origin_port);
  3968. cli.set_follow_location(true);
  3969. Request req;
  3970. req.method = "GET";
  3971. req.params = {{"api_key", "SECRET"}};
  3972. req.path = "/cross";
  3973. auto res = cli.send(req);
  3974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3975. EXPECT_EQ("/landing", cross_target);
  3976. req.path = "/same";
  3977. res = cli.send(req);
  3978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3979. EXPECT_EQ("/landing", same_target);
  3980. }
  3981. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3982. std::string authorization;
  3983. std::string trace_id;
  3984. auto result = GetThroughRedirectToDifferentPort(
  3985. [&](const Request &req, Response &res) {
  3986. authorization = req.get_header_value("Authorization");
  3987. trace_id = req.get_header_value("X-Trace-Id");
  3988. res.set_content("OK", "text/plain");
  3989. },
  3990. [](Client &cli) {
  3991. cli.set_default_headers(
  3992. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3993. });
  3994. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3995. EXPECT_EQ(StatusCode::OK_200, result->status);
  3996. // Like a header given with the request, a default one goes along unless it
  3997. // carries credentials (RFC 9110 15.4).
  3998. EXPECT_TRUE(authorization.empty());
  3999. EXPECT_EQ("42", trace_id);
  4000. }
  4001. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4002. auto result = GetThroughRedirectToDifferentPort(
  4003. [](const Request &, Response &res) {
  4004. res.set_content(std::string(2048, 'x'), "text/plain");
  4005. },
  4006. [](Client &cli) { cli.set_payload_max_length(1024); });
  4007. EXPECT_FALSE(result);
  4008. }
  4009. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4010. auto result = GetThroughRedirectToDifferentPort(
  4011. [](const Request &req, Response &res) {
  4012. // Answer after a second, or once the client gives up.
  4013. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4014. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4015. }
  4016. res.set_content("late", "text/plain");
  4017. },
  4018. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4019. ASSERT_FALSE(result);
  4020. EXPECT_EQ(Error::Read, result.error());
  4021. }
  4022. #ifdef CPPHTTPLIB_SSL_ENABLED
  4023. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4024. auto result = GetThroughRedirectToDifferentPort(
  4025. [](const Request &, Response &res) {
  4026. res.status = StatusCode::Unauthorized_401;
  4027. res.set_header("WWW-Authenticate",
  4028. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4029. },
  4030. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4031. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4032. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4033. }
  4034. #endif
  4035. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4036. Server svr;
  4037. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4038. // Port number that overflows int — should not crash
  4039. res.set_redirect("http://localhost:99999999999999999999/target");
  4040. });
  4041. auto port = svr.bind_to_any_port(HOST);
  4042. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4043. auto se = detail::scope_exit([&] {
  4044. svr.stop();
  4045. thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. });
  4048. svr.wait_until_ready();
  4049. Client cli(HOST, port);
  4050. cli.set_follow_location(true);
  4051. auto res = cli.Get("/redir");
  4052. // Should fail gracefully, not crash (no valid response due to bad port)
  4053. EXPECT_FALSE(res);
  4054. }
  4055. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4056. Server svr;
  4057. auto port = svr.bind_to_any_port(HOST);
  4058. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4059. // The server's own port followed by junk must not be followed
  4060. res.set_redirect("http://" + std::string(HOST) + ":" +
  4061. std::to_string(port) + "junk/target");
  4062. });
  4063. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4064. res.set_content("target", "text/plain");
  4065. });
  4066. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4067. auto se = detail::scope_exit([&] {
  4068. svr.stop();
  4069. thread.join();
  4070. ASSERT_FALSE(svr.is_running());
  4071. });
  4072. svr.wait_until_ready();
  4073. Client cli(HOST, port);
  4074. cli.set_follow_location(true);
  4075. auto res = cli.Get("/redir");
  4076. EXPECT_FALSE(res);
  4077. }
  4078. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4079. Server target_svr;
  4080. std::atomic<int> target_hits{0};
  4081. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4082. target_hits++;
  4083. res.set_content("target", "text/plain");
  4084. });
  4085. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4086. res.set_content("target", "text/plain");
  4087. });
  4088. int target_port = 0;
  4089. auto target_thread = std::thread([&]() {
  4090. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4091. target_svr.listen_after_bind();
  4092. });
  4093. Server origin_svr;
  4094. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4095. res.set_redirect(req.get_param_value("to"));
  4096. });
  4097. int origin_port = 0;
  4098. auto origin_thread = std::thread([&]() {
  4099. origin_port = origin_svr.bind_to_any_port(HOST);
  4100. origin_svr.listen_after_bind();
  4101. });
  4102. auto se = detail::scope_exit([&] {
  4103. origin_svr.stop();
  4104. origin_thread.join();
  4105. target_svr.stop();
  4106. target_thread.join();
  4107. ASSERT_FALSE(origin_svr.is_running());
  4108. ASSERT_FALSE(target_svr.is_running());
  4109. });
  4110. target_svr.wait_until_ready();
  4111. origin_svr.wait_until_ready();
  4112. auto port = std::to_string(target_port);
  4113. for (const auto &to :
  4114. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4115. Client cli(HOST, origin_port);
  4116. cli.set_follow_location(true);
  4117. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4118. EXPECT_FALSE(res) << to;
  4119. }
  4120. EXPECT_EQ(0, target_hits);
  4121. Client cli(HOST, origin_port);
  4122. cli.set_follow_location(true);
  4123. auto res = cli.Get("/redir?to=" +
  4124. encode_query_component("//127.0.0.1:" + port + "/target"));
  4125. ASSERT_TRUE(res) << to_string(res.error());
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. EXPECT_EQ("target", res->body);
  4128. }
  4129. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4130. Server svr;
  4131. std::atomic<bool> followed{false};
  4132. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4133. res.status = StatusCode::NotModified_304;
  4134. res.set_header("Location", "/target");
  4135. });
  4136. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4137. res.status = StatusCode::UseProxy_305;
  4138. res.set_header("Location", "/target");
  4139. });
  4140. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4141. followed = true;
  4142. res.set_content("target", "text/plain");
  4143. });
  4144. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4145. auto se = detail::scope_exit([&] {
  4146. svr.stop();
  4147. th.join();
  4148. ASSERT_FALSE(svr.is_running());
  4149. });
  4150. svr.wait_until_ready();
  4151. Client cli("localhost", PORT);
  4152. cli.set_follow_location(true);
  4153. auto res = cli.Get("/304");
  4154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4155. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4156. res = cli.Get("/305");
  4157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4158. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4159. EXPECT_FALSE(followed);
  4160. }
  4161. TEST(RedirectFromPageWithContent, Redirect) {
  4162. Server svr;
  4163. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4164. res.set_content("___", "text/plain");
  4165. res.set_redirect("/2");
  4166. });
  4167. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4168. res.set_content("Hello World!", "text/plain");
  4169. });
  4170. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4171. auto se = detail::scope_exit([&] {
  4172. svr.stop();
  4173. th.join();
  4174. ASSERT_FALSE(svr.is_running());
  4175. });
  4176. svr.wait_until_ready();
  4177. {
  4178. Client cli("localhost", PORT);
  4179. cli.set_follow_location(true);
  4180. std::string body;
  4181. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4182. body.append(data, data_length);
  4183. return true;
  4184. });
  4185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ("Hello World!", body);
  4188. }
  4189. {
  4190. Client cli("localhost", PORT);
  4191. std::string body;
  4192. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4193. body.append(data, data_length);
  4194. return true;
  4195. });
  4196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4197. EXPECT_EQ(StatusCode::Found_302, res->status);
  4198. EXPECT_EQ("___", body);
  4199. }
  4200. }
  4201. // A server can close the connection after a request with "Connection: close"
  4202. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4203. // redirected request must go out on a new connection.
  4204. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4205. #ifndef _WIN32
  4206. signal(SIGPIPE, SIG_IGN);
  4207. #endif
  4208. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4209. default_socket_options(srv);
  4210. sockaddr_in addr{};
  4211. addr.sin_family = AF_INET;
  4212. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4213. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4214. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4215. ASSERT_EQ(0, ::listen(srv, 2));
  4216. auto send_text = [](socket_t sock, const std::string &text) {
  4217. ::send(sock,
  4218. #ifdef _WIN32
  4219. static_cast<const char *>(text.c_str()),
  4220. static_cast<int>(text.size()),
  4221. #else
  4222. text.c_str(), text.size(),
  4223. #endif
  4224. 0);
  4225. };
  4226. auto reused = false;
  4227. auto server_thread = std::thread([&] {
  4228. char buf[4096];
  4229. auto first = ::accept(srv, nullptr, nullptr);
  4230. if (first == INVALID_SOCKET) { return; }
  4231. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4232. ::recv(first, buf, sizeof(buf), 0);
  4233. send_text(
  4234. first,
  4235. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4236. auto next = first;
  4237. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4238. reused = true;
  4239. } else {
  4240. detail::close_socket(first);
  4241. next = ::accept(srv, nullptr, nullptr);
  4242. if (next == INVALID_SOCKET) { return; }
  4243. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4244. ::recv(next, buf, sizeof(buf), 0);
  4245. }
  4246. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4247. "Connection: close\r\n\r\nok");
  4248. detail::close_socket(next);
  4249. });
  4250. Client cli("127.0.0.1", PORT + 2);
  4251. cli.set_follow_location(true);
  4252. cli.set_read_timeout(5, 0);
  4253. auto res = cli.Get("/1");
  4254. server_thread.join();
  4255. detail::close_socket(srv);
  4256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4257. EXPECT_EQ(StatusCode::OK_200, res->status);
  4258. EXPECT_EQ("ok", res->body);
  4259. EXPECT_FALSE(reused);
  4260. }
  4261. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4262. Server svr;
  4263. auto port_str = std::to_string(PORT);
  4264. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4265. auto expected_host = "[::1]:" + port_str;
  4266. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4267. res.set_content("___", "text/plain");
  4268. // res.set_redirect("/2");
  4269. res.set_redirect(redirect_url);
  4270. });
  4271. svr.Get("/2", [&](const Request &req, Response &res) {
  4272. auto host_header = req.headers.find("Host");
  4273. ASSERT_TRUE(host_header != req.headers.end());
  4274. EXPECT_EQ(expected_host, host_header->second);
  4275. res.set_content("Hello World!", "text/plain");
  4276. });
  4277. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4278. auto se = detail::scope_exit([&] {
  4279. svr.stop();
  4280. th.join();
  4281. ASSERT_FALSE(svr.is_running());
  4282. });
  4283. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4284. // actually starts anything, so the condition !svr.is_running() will
  4285. // always remain true, and the loop never stops.
  4286. // This basically counts how many milliseconds have passed since the
  4287. // call to svr.listen(), and if after 5 seconds nothing started yet
  4288. // aborts the test.
  4289. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4290. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4291. ASSERT_LT(milliseconds, 5000U);
  4292. }
  4293. {
  4294. Client cli("::1", PORT);
  4295. cli.set_follow_location(true);
  4296. std::string body;
  4297. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4298. body.append(data, data_length);
  4299. return true;
  4300. });
  4301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("Hello World!", body);
  4304. }
  4305. {
  4306. Client cli("::1", PORT);
  4307. std::string body;
  4308. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4309. body.append(data, data_length);
  4310. return true;
  4311. });
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::Found_302, res->status);
  4314. EXPECT_EQ("___", body);
  4315. }
  4316. }
  4317. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4318. Server svr;
  4319. svr.Get("/foo", [](const Request &req, Response &res) {
  4320. auto a = req.params.find("a");
  4321. if (a != req.params.end()) {
  4322. res.set_content((*a).second, "text/plain");
  4323. res.status = StatusCode::OK_200;
  4324. } else {
  4325. res.status = StatusCode::BadRequest_400;
  4326. }
  4327. });
  4328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4329. auto se = detail::scope_exit([&] {
  4330. svr.stop();
  4331. thread.join();
  4332. ASSERT_FALSE(svr.is_running());
  4333. });
  4334. svr.wait_until_ready();
  4335. {
  4336. Client cli(HOST, PORT);
  4337. cli.set_path_encode(false);
  4338. auto res = cli.Get("/foo?a=explicitly+encoded");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. // This expects it back with a space, as the `+` won't have been
  4342. // url-encoded, and server-side the params get decoded turning `+`
  4343. // into spaces.
  4344. EXPECT_EQ("explicitly encoded", res->body);
  4345. }
  4346. }
  4347. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4348. // When path encoding is disabled the client must transmit the supplied
  4349. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4350. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4351. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4352. // than a space (0x20). Assert on the raw wire target to catch this.
  4353. Server svr;
  4354. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4355. svr.Get("/foo", [&](const Request &req, Response &res) {
  4356. EXPECT_EQ(expected_target, req.target);
  4357. res.status = StatusCode::OK_200;
  4358. });
  4359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4360. auto se = detail::scope_exit([&] {
  4361. svr.stop();
  4362. thread.join();
  4363. ASSERT_FALSE(svr.is_running());
  4364. });
  4365. svr.wait_until_ready();
  4366. {
  4367. Client cli(HOST, PORT);
  4368. cli.set_path_encode(false);
  4369. auto res = cli.Get(expected_target.c_str());
  4370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4371. EXPECT_EQ(StatusCode::OK_200, res->status);
  4372. }
  4373. }
  4374. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4375. // `open_stream()` used to skip the path encoding that the buffered send
  4376. // path applies, so the same `path` produced different bytes in the request
  4377. // line depending on which API was used. Assert the two agree.
  4378. Server svr;
  4379. std::string target;
  4380. svr.Get(".*", [&](const Request &req, Response &res) {
  4381. target = req.target;
  4382. res.status = StatusCode::OK_200;
  4383. });
  4384. auto port = svr.bind_to_any_port(HOST);
  4385. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4386. auto se = detail::scope_exit([&] {
  4387. svr.stop();
  4388. thread.join();
  4389. ASSERT_FALSE(svr.is_running());
  4390. });
  4391. svr.wait_until_ready();
  4392. struct {
  4393. const char *path;
  4394. const char *expected;
  4395. } cases[] = {
  4396. {"/a b?x=1", "/a%20b?x=1"},
  4397. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4398. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4399. };
  4400. for (const auto &c : cases) {
  4401. Client cli(HOST, port);
  4402. target.clear();
  4403. auto res = cli.Get(c.path);
  4404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4405. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4406. auto buffered_target = target;
  4407. target.clear();
  4408. auto handle = cli.open_stream("GET", c.path);
  4409. EXPECT_TRUE(handle.is_valid())
  4410. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4411. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4412. }
  4413. }
  4414. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4415. // The `set_path_encode(false)` contract — transmit the supplied target
  4416. // verbatim — must hold for the streaming API too.
  4417. Server svr;
  4418. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4419. std::string target;
  4420. svr.Get("/foo", [&](const Request &req, Response &res) {
  4421. target = req.target;
  4422. res.status = StatusCode::OK_200;
  4423. });
  4424. auto port = svr.bind_to_any_port(HOST);
  4425. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4426. auto se = detail::scope_exit([&] {
  4427. svr.stop();
  4428. thread.join();
  4429. ASSERT_FALSE(svr.is_running());
  4430. });
  4431. svr.wait_until_ready();
  4432. {
  4433. Client cli(HOST, port);
  4434. cli.set_path_encode(false);
  4435. auto handle = cli.open_stream("GET", expected_target);
  4436. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4437. EXPECT_EQ(expected_target, target);
  4438. }
  4439. }
  4440. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4441. // With path encoding enabled a CR/LF in the target is percent-encoded
  4442. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4443. // write_request_line still backstops `set_path_encode(false)`, which is
  4444. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4445. Server svr;
  4446. // Captured before routing: the decoded path contains a newline, which a
  4447. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4448. std::string target;
  4449. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4450. target = req.target;
  4451. res.status = StatusCode::OK_200;
  4452. return Server::HandlerResponse::Handled;
  4453. });
  4454. auto port = svr.bind_to_any_port(HOST);
  4455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4456. auto se = detail::scope_exit([&] {
  4457. svr.stop();
  4458. thread.join();
  4459. ASSERT_FALSE(svr.is_running());
  4460. });
  4461. svr.wait_until_ready();
  4462. {
  4463. Client cli(HOST, port);
  4464. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4465. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4466. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4467. }
  4468. }
  4469. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4470. // Every control character is percent-encoded, not just CR/LF, so the target
  4471. // passes the request-target check in write_request_line.
  4472. Server svr;
  4473. std::string target;
  4474. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4475. target = req.target;
  4476. res.status = StatusCode::OK_200;
  4477. return Server::HandlerResponse::Handled;
  4478. });
  4479. auto port = svr.bind_to_any_port(HOST);
  4480. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. {
  4488. Client cli(HOST, port);
  4489. auto res = cli.Get("/a\tb\x1b\x7f");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ("/a%09b%1B%7F", target);
  4492. }
  4493. }
  4494. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4495. // Nothing may reach the wire: a raw CR/LF target would split the request
  4496. // line and inject headers.
  4497. Server svr;
  4498. // Pre-routing so that "not called" means nothing reached the server at all,
  4499. // rather than merely failing to match a handler pattern.
  4500. auto handler_called = false;
  4501. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4502. handler_called = true;
  4503. res.status = StatusCode::OK_200;
  4504. return Server::HandlerResponse::Handled;
  4505. });
  4506. auto port = svr.bind_to_any_port(HOST);
  4507. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4508. auto se = detail::scope_exit([&] {
  4509. svr.stop();
  4510. thread.join();
  4511. ASSERT_FALSE(svr.is_running());
  4512. });
  4513. svr.wait_until_ready();
  4514. {
  4515. Client cli(HOST, port);
  4516. cli.set_path_encode(false);
  4517. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4518. EXPECT_FALSE(handle.is_valid());
  4519. EXPECT_EQ(Error::Write, handle.error);
  4520. EXPECT_FALSE(handler_called);
  4521. }
  4522. }
  4523. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4524. // Which of the two branches runs is decided by whether the query component
  4525. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4526. // an empty query and must still fall back to building one from
  4527. // `req.params`, while a non-empty query must win over `req.params`.
  4528. Server svr;
  4529. std::string target;
  4530. svr.Get("/foo", [&](const Request &req, Response &res) {
  4531. target = req.target;
  4532. res.status = StatusCode::OK_200;
  4533. });
  4534. auto port = svr.bind_to_any_port(HOST);
  4535. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. // Trailing `?` -> empty query component -> `req.params` is used.
  4544. Client cli(HOST, port);
  4545. Request req;
  4546. req.method = "GET";
  4547. req.path = "/foo?";
  4548. req.params.emplace("a", "1");
  4549. target.clear();
  4550. auto res = cli.send(req);
  4551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4552. EXPECT_EQ("/foo?a=1", target);
  4553. }
  4554. {
  4555. // Non-empty query in `req.path` -> `req.params` is not appended.
  4556. Client cli(HOST, port);
  4557. Request req;
  4558. req.method = "GET";
  4559. req.path = "/foo?b=2";
  4560. req.params.emplace("a", "1");
  4561. target.clear();
  4562. auto res = cli.send(req);
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("/foo?b=2", target);
  4565. }
  4566. }
  4567. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4568. Server svr;
  4569. svr.Get("/", [](const Request &req, Response &) {
  4570. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4571. });
  4572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, PORT);
  4581. cli.set_path_encode(false);
  4582. auto res = cli.Get("/?something=%0A");
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. }
  4586. }
  4587. TEST(BindServerTest, BindDualStack) {
  4588. Server svr;
  4589. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4590. res.set_content("Hello World!", "text/plain");
  4591. });
  4592. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4593. auto se = detail::scope_exit([&] {
  4594. svr.stop();
  4595. thread.join();
  4596. ASSERT_FALSE(svr.is_running());
  4597. });
  4598. svr.wait_until_ready();
  4599. {
  4600. Client cli("127.0.0.1", PORT);
  4601. auto res = cli.Get("/1");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. EXPECT_EQ("Hello World!", res->body);
  4605. }
  4606. {
  4607. Client cli("::1", PORT);
  4608. auto res = cli.Get("/1");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("Hello World!", res->body);
  4612. }
  4613. }
  4614. TEST(BindServerTest, BindAndListenSeparately) {
  4615. Server svr;
  4616. int port = svr.bind_to_any_port("0.0.0.0");
  4617. ASSERT_TRUE(svr.is_valid());
  4618. ASSERT_TRUE(port > 0);
  4619. svr.stop();
  4620. }
  4621. // Reports whether anything is still listening on a loopback port. A plain
  4622. // connect() is used instead of a Client request because a socket left bound by
  4623. // mistake accepts the connection into its backlog and never answers, which
  4624. // would hang the test instead of failing it.
  4625. static bool is_loopback_port_accepting(int port) {
  4626. sockaddr_in addr{};
  4627. addr.sin_family = AF_INET;
  4628. addr.sin_port = htons(static_cast<uint16_t>(port));
  4629. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4630. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4631. EXPECT_NE(sock, INVALID_SOCKET);
  4632. if (sock == INVALID_SOCKET) { return false; }
  4633. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4634. static_cast<socklen_t>(sizeof(addr)));
  4635. detail::close_socket(sock);
  4636. return ret == 0;
  4637. }
  4638. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4639. Server svr;
  4640. auto port = svr.bind_to_any_port("127.0.0.1");
  4641. ASSERT_TRUE(port > 0);
  4642. svr.stop();
  4643. // bind_to_any_port() already called listen(2), so until stop() closed the
  4644. // descriptor the port kept accepting connections into the backlog. ASSERT
  4645. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4646. // below blocks forever in the accept loop.
  4647. ASSERT_FALSE(is_loopback_port_accepting(port));
  4648. // Nothing is left to accept on, so listen_after_bind() must report failure
  4649. // instead of returning success without ever serving.
  4650. EXPECT_FALSE(svr.listen_after_bind());
  4651. // The failed listen marks the server decommissioned, so a waiter returns
  4652. // instead of spinning forever.
  4653. svr.wait_until_ready();
  4654. }
  4655. #ifdef CPPHTTPLIB_SSL_ENABLED
  4656. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4658. CLIENT_CA_CERT_DIR);
  4659. int port = svr.bind_to_any_port("0.0.0.0");
  4660. ASSERT_TRUE(svr.is_valid());
  4661. ASSERT_TRUE(port > 0);
  4662. svr.stop();
  4663. }
  4664. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4665. // or a rejected CustomRoute() registration would not stop the server binding.
  4666. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4668. CLIENT_CA_CERT_DIR);
  4669. ASSERT_TRUE(svr.is_valid());
  4670. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4671. EXPECT_FALSE(svr.is_valid());
  4672. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4673. }
  4674. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4675. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4676. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4677. int port = svr.bind_to_any_port("0.0.0.0");
  4678. ASSERT_TRUE(svr.is_valid());
  4679. ASSERT_TRUE(port > 0);
  4680. svr.stop();
  4681. }
  4682. TEST(BindServerTest, UpdateCertsPem) {
  4683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4684. int port = svr.bind_to_any_port("0.0.0.0");
  4685. ASSERT_TRUE(svr.is_valid());
  4686. ASSERT_TRUE(port > 0);
  4687. // Read PEM files
  4688. std::string cert_pem, key_pem, ca_pem;
  4689. read_file(SERVER_CERT_FILE, cert_pem);
  4690. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4691. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4692. // Update server certificates using PEM API
  4693. ASSERT_TRUE(
  4694. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4695. ASSERT_TRUE(svr.is_valid());
  4696. svr.stop();
  4697. }
  4698. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4699. // Start server with client CA (enables client auth)
  4700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4701. ASSERT_TRUE(svr.is_valid());
  4702. bool handler_called = false;
  4703. svr.Get("/test", [&](const Request &req, Response &res) {
  4704. handler_called = true;
  4705. // Verify client certificate is present
  4706. auto cert = req.peer_cert();
  4707. EXPECT_TRUE(static_cast<bool>(cert));
  4708. res.set_content("ok", "text/plain");
  4709. });
  4710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4711. auto se = detail::scope_exit([&] {
  4712. svr.stop();
  4713. t.join();
  4714. ASSERT_FALSE(svr.is_running());
  4715. });
  4716. svr.wait_until_ready();
  4717. // Read PEM files
  4718. std::string cert_pem, key_pem, ca_pem;
  4719. read_file(SERVER_CERT_FILE, cert_pem);
  4720. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4721. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4722. // Update server certificates and client CA using PEM API while server running
  4723. ASSERT_TRUE(
  4724. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4725. // Connect with client certificate
  4726. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4727. cli.enable_server_certificate_verification(false);
  4728. cli.set_connection_timeout(30);
  4729. auto res = cli.Get("/test");
  4730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4731. ASSERT_EQ(StatusCode::OK_200, res->status);
  4732. ASSERT_TRUE(handler_called);
  4733. EXPECT_EQ("ok", res->body);
  4734. }
  4735. // Puts a CA that did not sign the client's certificate in the old one's place.
  4736. static bool replace_client_ca(SSLServer &svr) {
  4737. std::string cert_pem, key_pem, ca_pem;
  4738. read_file(SERVER_CERT_FILE, cert_pem);
  4739. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4740. read_file(SERVER_CERT2_FILE, ca_pem);
  4741. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4742. ca_pem.c_str());
  4743. }
  4744. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4746. ASSERT_TRUE(svr.is_valid());
  4747. svr.Get("/test", [](const Request &, Response &res) {
  4748. res.set_content("ok", "text/plain");
  4749. });
  4750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4751. auto se = detail::scope_exit([&] {
  4752. svr.stop();
  4753. t.join();
  4754. ASSERT_FALSE(svr.is_running());
  4755. });
  4756. svr.wait_until_ready();
  4757. auto get = [] {
  4758. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4759. cli.enable_server_certificate_verification(false);
  4760. return cli.Get("/test");
  4761. };
  4762. ASSERT_TRUE(get());
  4763. ASSERT_TRUE(replace_client_ca(svr));
  4764. EXPECT_FALSE(get());
  4765. }
  4766. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4767. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4769. ASSERT_TRUE(svr.is_valid());
  4770. tls::set_verify_callback(svr.tls_context(),
  4771. [](const tls::VerifyContext &) -> bool {
  4772. throw std::runtime_error("verify");
  4773. });
  4774. svr.Get("/test", [](const Request &, Response &res) {
  4775. res.set_content("ok", "text/plain");
  4776. });
  4777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4778. auto se = detail::scope_exit([&] {
  4779. svr.stop();
  4780. t.join();
  4781. ASSERT_FALSE(svr.is_running());
  4782. });
  4783. svr.wait_until_ready();
  4784. auto get = [] {
  4785. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4786. cli.enable_server_certificate_verification(false);
  4787. return cli.Get("/test");
  4788. };
  4789. EXPECT_FALSE(get());
  4790. // The handshake is over, so an update does not wait for it.
  4791. std::string cert_pem, key_pem;
  4792. read_file(SERVER_CERT_FILE, cert_pem);
  4793. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4794. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4795. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4796. return v.preverify_ok;
  4797. });
  4798. auto res = get();
  4799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4800. EXPECT_EQ("ok", res->body);
  4801. }
  4802. #endif
  4803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4804. // Sends each request over a new connection with a client certificate,
  4805. // resuming the session of the one before when there is one.
  4806. class ResumingClient {
  4807. public:
  4808. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4809. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4810. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4811. SSL_FILETYPE_PEM);
  4812. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4813. // callback, not through SSL_get1_session().
  4814. SSL_CTX_set_app_data(ctx_, this);
  4815. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4816. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4817. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4818. auto self = static_cast<ResumingClient *>(
  4819. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4820. SSL_SESSION_free(self->session_);
  4821. self->session_ = session;
  4822. return 1; // Keeps the reference
  4823. });
  4824. }
  4825. ~ResumingClient() {
  4826. SSL_SESSION_free(session_);
  4827. SSL_CTX_free(ctx_);
  4828. }
  4829. // Tells whether the request was answered.
  4830. bool get() {
  4831. auto error = Error::Success;
  4832. auto sock = detail::create_client_socket(
  4833. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4834. /*connection_timeout_sec=*/5, 0,
  4835. /*read_timeout_sec=*/5, 0,
  4836. /*write_timeout_sec=*/5, 0, std::string(), error);
  4837. if (sock == INVALID_SOCKET) { return false; }
  4838. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4839. auto ssl = SSL_new(ctx_);
  4840. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4841. SSL_set_fd(ssl, static_cast<int>(sock));
  4842. if (session_) { SSL_set_session(ssl, session_); }
  4843. if (SSL_connect(ssl) != 1) { return false; }
  4844. reused_ = SSL_session_reused(ssl) == 1;
  4845. // Reading the response also takes in a TLS 1.3 session ticket.
  4846. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4847. "Connection: close\r\n\r\n";
  4848. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4849. std::string res;
  4850. char buf[256];
  4851. int n;
  4852. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4853. res.append(buf, static_cast<size_t>(n));
  4854. }
  4855. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4856. SSL_shutdown(ssl);
  4857. return res.find("200 OK") != std::string::npos;
  4858. }
  4859. // Whether the last connection resumed a session
  4860. bool reused() const { return reused_; }
  4861. private:
  4862. SSL_CTX *ctx_;
  4863. SSL_SESSION *session_ = nullptr;
  4864. bool reused_ = false;
  4865. };
  4866. // A client that resumes its session gets through, but not once the client CA
  4867. // has changed, as a resumed session does not show the certificate again.
  4868. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4870. ASSERT_TRUE(svr.is_valid());
  4871. svr.Get("/test", [](const Request &, Response &res) {
  4872. res.set_content("ok", "text/plain");
  4873. });
  4874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4875. auto se = detail::scope_exit([&] {
  4876. svr.stop();
  4877. t.join();
  4878. ASSERT_FALSE(svr.is_running());
  4879. });
  4880. svr.wait_until_ready();
  4881. ResumingClient cli;
  4882. ASSERT_TRUE(cli.get());
  4883. ASSERT_TRUE(cli.get());
  4884. EXPECT_TRUE(cli.reused());
  4885. ASSERT_TRUE(replace_client_ca(svr));
  4886. EXPECT_FALSE(cli.get());
  4887. }
  4888. // A resumed session does not show the certificate again, so the server does
  4889. // not resume one with a verify callback to run on it.
  4890. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4892. ASSERT_TRUE(svr.is_valid());
  4893. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4894. return v.preverify_ok;
  4895. });
  4896. svr.Get("/test", [](const Request &, Response &res) {
  4897. res.set_content("ok", "text/plain");
  4898. });
  4899. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4900. auto se = detail::scope_exit([&] {
  4901. svr.stop();
  4902. t.join();
  4903. ASSERT_FALSE(svr.is_running());
  4904. });
  4905. svr.wait_until_ready();
  4906. ResumingClient cli;
  4907. ASSERT_TRUE(cli.get());
  4908. ASSERT_TRUE(cli.get());
  4909. EXPECT_FALSE(cli.reused());
  4910. }
  4911. #endif
  4912. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4913. // wolfSSL shares its session cache between contexts, so a resumed session
  4914. // could carry a client certificate checked against another server's CA, or
  4915. // against a client CA since replaced.
  4916. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4918. ASSERT_TRUE(svr.is_valid());
  4919. // Trusts a CA that did not sign the client's certificate.
  4920. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4921. ASSERT_TRUE(other.is_valid());
  4922. for (auto s : {&svr, &other}) {
  4923. s->Get("/test", [](const Request &, Response &res) {
  4924. res.set_content("ok", "text/plain");
  4925. });
  4926. }
  4927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4928. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4929. auto se = detail::scope_exit([&] {
  4930. other.stop();
  4931. svr.stop();
  4932. t2.join();
  4933. t.join();
  4934. });
  4935. svr.wait_until_ready();
  4936. other.wait_until_ready();
  4937. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4938. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4939. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4940. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4941. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4942. ASSERT_EQ(WOLFSSL_SUCCESS,
  4943. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4944. WOLFSSL_FILETYPE_PEM));
  4945. WOLFSSL_SESSION *session = nullptr;
  4946. auto session_se = detail::scope_exit([&] {
  4947. if (session) { wolfSSL_SESSION_free(session); }
  4948. });
  4949. // A request over a new connection, resuming `session` when there is one and
  4950. // keeping the connection's own in its place. Tells whether it was answered.
  4951. auto get = [&](int port) {
  4952. auto error = Error::Success;
  4953. auto sock = detail::create_client_socket(
  4954. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4955. /*connection_timeout_sec=*/5, 0,
  4956. /*read_timeout_sec=*/5, 0,
  4957. /*write_timeout_sec=*/5, 0, std::string(), error);
  4958. if (sock == INVALID_SOCKET) { return false; }
  4959. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4960. auto ssl = wolfSSL_new(ctx);
  4961. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4962. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4963. if (session) { wolfSSL_set_session(ssl, session); }
  4964. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4965. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4966. "Connection: close\r\n\r\n";
  4967. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4968. std::string res;
  4969. char buf[256];
  4970. int n;
  4971. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4972. res.append(buf, static_cast<size_t>(n));
  4973. }
  4974. wolfSSL_shutdown(ssl);
  4975. if (session) { wolfSSL_SESSION_free(session); }
  4976. session = wolfSSL_get1_session(ssl);
  4977. return res.find("200 OK") != std::string::npos;
  4978. };
  4979. ASSERT_TRUE(get(PORT));
  4980. EXPECT_FALSE(get(PORT + 1));
  4981. ASSERT_TRUE(get(PORT));
  4982. ASSERT_TRUE(replace_client_ca(svr));
  4983. EXPECT_FALSE(get(PORT));
  4984. }
  4985. #endif
  4986. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4988. ASSERT_TRUE(svr.is_valid());
  4989. // Keep-alive parking would wait for the ClientHello without a handshake.
  4990. svr.set_keep_alive_parking(false);
  4991. svr.Get("/test", [](const Request &, Response &res) {
  4992. res.set_content("ok", "text/plain");
  4993. });
  4994. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4995. auto se = detail::scope_exit([&] {
  4996. svr.stop();
  4997. t.join();
  4998. ASSERT_FALSE(svr.is_running());
  4999. });
  5000. svr.wait_until_ready();
  5001. // A connection that sends no ClientHello keeps its handshake in progress,
  5002. // once the server has had a moment to start it.
  5003. auto error = Error::Success;
  5004. auto sock = detail::create_client_socket(
  5005. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5006. /*connection_timeout_sec=*/5, 0,
  5007. /*read_timeout_sec=*/5, 0,
  5008. /*write_timeout_sec=*/5, 0, std::string(), error);
  5009. ASSERT_NE(INVALID_SOCKET, sock);
  5010. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5011. std::string cert_pem, key_pem;
  5012. read_file(SERVER_CERT_FILE, cert_pem);
  5013. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5014. auto update = std::async(std::launch::async, [&]() {
  5015. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5016. });
  5017. EXPECT_EQ(std::future_status::timeout,
  5018. update.wait_for(std::chrono::milliseconds(200)));
  5019. detail::close_socket(sock);
  5020. EXPECT_TRUE(update.get());
  5021. SSLClient cli(HOST, PORT);
  5022. cli.enable_server_certificate_verification(false);
  5023. auto res = cli.Get("/test");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. }
  5027. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5029. ASSERT_TRUE(svr.is_valid());
  5030. // Keep-alive parking would wait for the ClientHello without a handshake.
  5031. svr.set_keep_alive_parking(false);
  5032. svr.set_read_timeout(10, 0);
  5033. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5034. auto se = detail::scope_exit([&] {
  5035. svr.stop();
  5036. if (t.joinable()) { t.join(); }
  5037. });
  5038. svr.wait_until_ready();
  5039. // A connection that sends no ClientHello keeps its handshake in progress,
  5040. // once the server has had a moment to start it.
  5041. auto error = Error::Success;
  5042. auto sock = detail::create_client_socket(
  5043. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5044. /*connection_timeout_sec=*/5, 0,
  5045. /*read_timeout_sec=*/5, 0,
  5046. /*write_timeout_sec=*/5, 0, std::string(), error);
  5047. ASSERT_NE(INVALID_SOCKET, sock);
  5048. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5049. auto start = std::chrono::steady_clock::now();
  5050. svr.stop();
  5051. t.join();
  5052. auto elapsed = std::chrono::steady_clock::now() - start;
  5053. detail::close_socket(sock);
  5054. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5055. }
  5056. #endif
  5057. TEST(ErrorHandlerTest, ContentLength) {
  5058. Server svr;
  5059. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5060. res.status = StatusCode::OK_200;
  5061. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5062. "text/html"); // <= Content-Length still 13
  5063. });
  5064. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5065. res.set_content("Hello World!\n", "text/plain");
  5066. res.status = 524;
  5067. });
  5068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5069. auto se = detail::scope_exit([&] {
  5070. svr.stop();
  5071. thread.join();
  5072. ASSERT_FALSE(svr.is_running());
  5073. });
  5074. svr.wait_until_ready();
  5075. {
  5076. Client cli(HOST, PORT);
  5077. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5079. EXPECT_EQ(StatusCode::OK_200, res->status);
  5080. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5081. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5082. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5083. }
  5084. }
  5085. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5086. TEST(ExceptionTest, WithoutExceptionHandler) {
  5087. Server svr;
  5088. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5089. throw std::runtime_error("exception...");
  5090. });
  5091. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5092. throw std::runtime_error("exception\r\n...");
  5093. });
  5094. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5095. auto se = detail::scope_exit([&] {
  5096. svr.stop();
  5097. listen_thread.join();
  5098. ASSERT_FALSE(svr.is_running());
  5099. });
  5100. svr.wait_until_ready();
  5101. Client cli("localhost", PORT);
  5102. {
  5103. auto res = cli.Get("/exception");
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5106. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5107. }
  5108. {
  5109. auto res = cli.Get("/unknown");
  5110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5112. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5113. }
  5114. }
  5115. TEST(ExceptionTest, WithExceptionHandler) {
  5116. Server svr;
  5117. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5118. std::exception_ptr ep) {
  5119. EXPECT_FALSE(ep == nullptr);
  5120. try {
  5121. std::rethrow_exception(ep);
  5122. } catch (std::exception &e) {
  5123. EXPECT_EQ("abc", std::string(e.what()));
  5124. } catch (...) {}
  5125. res.status = StatusCode::InternalServerError_500;
  5126. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5127. "text/html"); // <= Content-Length still 13 at this point
  5128. });
  5129. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5130. res.set_content("Hello World!\n", "text/plain");
  5131. throw std::runtime_error("abc");
  5132. });
  5133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5134. auto se = detail::scope_exit([&] {
  5135. svr.stop();
  5136. thread.join();
  5137. ASSERT_FALSE(svr.is_running());
  5138. });
  5139. svr.wait_until_ready();
  5140. for (size_t i = 0; i < 10; i++) {
  5141. Client cli(HOST, PORT);
  5142. for (size_t j = 0; j < 100; j++) {
  5143. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5145. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5146. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5147. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5148. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5149. }
  5150. cli.set_keep_alive(true);
  5151. for (size_t j = 0; j < 100; j++) {
  5152. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5155. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5156. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5157. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5158. }
  5159. }
  5160. }
  5161. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5162. Server svr;
  5163. svr.set_exception_handler(
  5164. [](const Request &, Response &res, std::exception_ptr) {
  5165. res.set_content("oops", "text/plain");
  5166. });
  5167. svr.Get("/throw", [](const Request &, Response &) {
  5168. throw std::runtime_error("throw");
  5169. });
  5170. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5171. res.status = StatusCode::Created_201;
  5172. throw std::runtime_error("created-then-throw");
  5173. });
  5174. auto port = svr.bind_to_any_port(HOST);
  5175. ASSERT_GT(port, 0);
  5176. thread t = thread([&] { svr.listen_after_bind(); });
  5177. auto se = detail::scope_exit([&] {
  5178. svr.stop();
  5179. t.join();
  5180. ASSERT_FALSE(svr.is_running());
  5181. });
  5182. svr.wait_until_ready();
  5183. Client cli(HOST, port);
  5184. for (auto path : {"/throw", "/created-then-throw"}) {
  5185. auto res = cli.Get(path);
  5186. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5187. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5188. }
  5189. }
  5190. TEST(ExceptionTest, AndErrorHandler) {
  5191. Server svr;
  5192. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5193. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5194. });
  5195. svr.set_exception_handler(
  5196. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5197. EXPECT_FALSE(ep == nullptr);
  5198. try {
  5199. std::rethrow_exception(ep);
  5200. } catch (std::exception &e) {
  5201. res.set_content(e.what(), "text/html");
  5202. } catch (...) {}
  5203. res.status = StatusCode::InternalServerError_500;
  5204. });
  5205. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5206. throw std::runtime_error("EXCEPTION");
  5207. });
  5208. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5209. res.set_content("ERROR", "text/html");
  5210. res.status = StatusCode::InternalServerError_500;
  5211. });
  5212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5213. auto se = detail::scope_exit([&] {
  5214. svr.stop();
  5215. thread.join();
  5216. ASSERT_FALSE(svr.is_running());
  5217. });
  5218. svr.wait_until_ready();
  5219. Client cli(HOST, PORT);
  5220. {
  5221. auto res = cli.Get("/exception");
  5222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5223. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5224. EXPECT_EQ("EXCEPTION", res->body);
  5225. }
  5226. {
  5227. auto res = cli.Get("/error");
  5228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5229. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5230. EXPECT_EQ("ERROR", res->body);
  5231. }
  5232. {
  5233. auto res = cli.Get("/invalid");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5236. EXPECT_EQ("NOT_FOUND", res->body);
  5237. }
  5238. }
  5239. #endif
  5240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5241. // An exception from a user callback outside process_request()'s try/catch
  5242. // used to unwind into the task queue - which does not catch - and terminate
  5243. // the process. Each test below runs the server on a single worker thread: a
  5244. // guard that catches the exception but still loses the thread would otherwise
  5245. // be hidden by a spare worker serving the follow-up request. Note that a
  5246. // regression here aborts the whole test binary rather than failing one test.
  5247. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5248. Server svr;
  5249. svr.new_task_queue = [] { return new ThreadPool(1); };
  5250. std::atomic<int> reported{0};
  5251. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5252. if (err == Error::UserCallbackException) { reported++; }
  5253. });
  5254. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5255. res.set_content_provider(
  5256. 1024, "text/plain",
  5257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5258. sink.write("hello", 5);
  5259. throw std::runtime_error("from the content provider");
  5260. });
  5261. });
  5262. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5263. res.set_content("ok", "text/plain");
  5264. });
  5265. auto port = svr.bind_to_any_port(HOST);
  5266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5267. auto se = detail::scope_exit([&] {
  5268. svr.stop();
  5269. listen_thread.join();
  5270. ASSERT_FALSE(svr.is_running());
  5271. });
  5272. svr.wait_until_ready();
  5273. {
  5274. Client cli(HOST, port);
  5275. cli.set_read_timeout(5, 0);
  5276. EXPECT_FALSE(cli.Get("/throw"));
  5277. }
  5278. EXPECT_TRUE(svr.is_running());
  5279. EXPECT_EQ(1, reported.load());
  5280. // A request on a fresh connection is still served.
  5281. {
  5282. Client cli(HOST, port);
  5283. auto res = cli.Get("/ok");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("ok", res->body);
  5287. }
  5288. }
  5289. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5290. Server svr;
  5291. svr.new_task_queue = [] { return new ThreadPool(1); };
  5292. std::atomic<bool> should_throw{true};
  5293. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5294. res.set_content("hi", "text/plain");
  5295. });
  5296. svr.set_post_routing_handler(
  5297. [&](const Request & /*req*/, Response & /*res*/) {
  5298. if (should_throw) {
  5299. throw std::runtime_error("from the post-routing handler");
  5300. }
  5301. });
  5302. auto port = svr.bind_to_any_port(HOST);
  5303. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5304. auto se = detail::scope_exit([&] {
  5305. svr.stop();
  5306. listen_thread.join();
  5307. ASSERT_FALSE(svr.is_running());
  5308. });
  5309. svr.wait_until_ready();
  5310. {
  5311. Client cli(HOST, port);
  5312. cli.set_read_timeout(5, 0);
  5313. EXPECT_FALSE(cli.Get("/hi"));
  5314. }
  5315. EXPECT_TRUE(svr.is_running());
  5316. should_throw = false;
  5317. {
  5318. Client cli(HOST, port);
  5319. auto res = cli.Get("/hi");
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. EXPECT_EQ("hi", res->body);
  5323. }
  5324. }
  5325. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5326. // The guard reports the caught exception through the error logger, which is
  5327. // a user callback too. A logger that throws has to be contained as well, or
  5328. // the process would terminate from inside the catch.
  5329. Server svr;
  5330. svr.new_task_queue = [] { return new ThreadPool(1); };
  5331. std::atomic<int> reported{0};
  5332. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5333. if (err == Error::UserCallbackException) {
  5334. reported++;
  5335. throw std::runtime_error("from the error logger");
  5336. }
  5337. });
  5338. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5339. res.set_content_provider(
  5340. 1024, "text/plain",
  5341. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5342. sink.write("hello", 5);
  5343. throw std::runtime_error("from the content provider");
  5344. });
  5345. });
  5346. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5347. res.set_content("ok", "text/plain");
  5348. });
  5349. auto port = svr.bind_to_any_port(HOST);
  5350. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5351. auto se = detail::scope_exit([&] {
  5352. svr.stop();
  5353. listen_thread.join();
  5354. ASSERT_FALSE(svr.is_running());
  5355. });
  5356. svr.wait_until_ready();
  5357. {
  5358. Client cli(HOST, port);
  5359. cli.set_read_timeout(5, 0);
  5360. EXPECT_FALSE(cli.Get("/throw"));
  5361. }
  5362. EXPECT_TRUE(svr.is_running());
  5363. EXPECT_EQ(1, reported.load());
  5364. {
  5365. Client cli(HOST, port);
  5366. auto res = cli.Get("/ok");
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. EXPECT_EQ(StatusCode::OK_200, res->status);
  5369. EXPECT_EQ("ok", res->body);
  5370. }
  5371. }
  5372. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5373. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5374. // so the exception unwinds through the ws::WebSocket object on its way to
  5375. // the guard. None of the HTTP cases above cross that.
  5376. Server svr;
  5377. svr.new_task_queue = [] { return new ThreadPool(1); };
  5378. std::atomic<int> reported{0};
  5379. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5380. if (err == Error::UserCallbackException) { reported++; }
  5381. });
  5382. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5383. throw std::runtime_error("from the WebSocket handler");
  5384. });
  5385. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5386. res.set_content("ok", "text/plain");
  5387. });
  5388. auto port = svr.bind_to_any_port(HOST);
  5389. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5390. auto se = detail::scope_exit([&] {
  5391. svr.stop();
  5392. listen_thread.join();
  5393. ASSERT_FALSE(svr.is_running());
  5394. });
  5395. svr.wait_until_ready();
  5396. {
  5397. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5398. "/ws");
  5399. auto res = client.connect();
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. // The server dropped the connection instead of dying.
  5402. std::string msg;
  5403. EXPECT_FALSE(client.read(msg));
  5404. client.close();
  5405. }
  5406. EXPECT_TRUE(svr.is_running());
  5407. EXPECT_EQ(1, reported.load());
  5408. {
  5409. Client cli(HOST, port);
  5410. auto res = cli.Get("/ok");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. EXPECT_EQ("ok", res->body);
  5414. }
  5415. }
  5416. #ifdef CPPHTTPLIB_SSL_ENABLED
  5417. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5418. // SSLServer::process_and_close_socket() is a separate overload with its own
  5419. // guard, so it is exercised on its own.
  5420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5421. ASSERT_TRUE(svr.is_valid());
  5422. svr.new_task_queue = [] { return new ThreadPool(1); };
  5423. std::atomic<int> reported{0};
  5424. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5425. if (err == Error::UserCallbackException) { reported++; }
  5426. });
  5427. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5428. res.set_content_provider(
  5429. 1024, "text/plain",
  5430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5431. sink.write("hello", 5);
  5432. throw std::runtime_error("from the content provider");
  5433. });
  5434. });
  5435. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5436. res.set_content("ok", "text/plain");
  5437. });
  5438. auto port = svr.bind_to_any_port(HOST);
  5439. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5440. auto se = detail::scope_exit([&] {
  5441. svr.stop();
  5442. listen_thread.join();
  5443. ASSERT_FALSE(svr.is_running());
  5444. });
  5445. svr.wait_until_ready();
  5446. {
  5447. SSLClient cli(HOST, port);
  5448. cli.enable_server_certificate_verification(false);
  5449. cli.set_read_timeout(5, 0);
  5450. EXPECT_FALSE(cli.Get("/throw"));
  5451. }
  5452. EXPECT_TRUE(svr.is_running());
  5453. EXPECT_EQ(1, reported.load());
  5454. {
  5455. SSLClient cli(HOST, port);
  5456. cli.enable_server_certificate_verification(false);
  5457. auto res = cli.Get("/ok");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. EXPECT_EQ("ok", res->body);
  5461. }
  5462. }
  5463. #endif
  5464. #endif
  5465. TEST(NoContentTest, ContentLength) {
  5466. Server svr;
  5467. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5468. res.status = StatusCode::NoContent_204;
  5469. });
  5470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5471. auto se = detail::scope_exit([&] {
  5472. svr.stop();
  5473. thread.join();
  5474. ASSERT_FALSE(svr.is_running());
  5475. });
  5476. svr.wait_until_ready();
  5477. {
  5478. Client cli(HOST, PORT);
  5479. auto res = cli.Get("/hi");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5482. // RFC 9110 8.6: none in a 204 response
  5483. EXPECT_FALSE(res->has_header("Content-Length"));
  5484. }
  5485. }
  5486. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5487. Server svr;
  5488. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5489. res.set_header("Content-Length", "5");
  5490. res.set_content("hello world", "text/plain");
  5491. });
  5492. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5493. // A body that reads as the last chunk, were it taken as chunked
  5494. res.set_header("Transfer-Encoding", "chunked");
  5495. res.set_content("0\r\n\r\n", "text/plain");
  5496. });
  5497. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5498. res.set_header("Content-Length", "2");
  5499. res.set_content_provider(5, "text/plain",
  5500. [](size_t offset, size_t length, DataSink &sink) {
  5501. sink.write(&"hello"[offset], length);
  5502. return true;
  5503. });
  5504. });
  5505. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5506. res.set_header("Content-Length", "1234");
  5507. });
  5508. thread t = thread([&] { svr.listen(HOST, PORT); });
  5509. auto se = detail::scope_exit([&] {
  5510. svr.stop();
  5511. t.join();
  5512. ASSERT_FALSE(svr.is_running());
  5513. });
  5514. svr.wait_until_ready();
  5515. Client cli(HOST, PORT);
  5516. cli.set_read_timeout(1, 0);
  5517. auto expect_body = [&](const Result &res, const std::string &body) {
  5518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5519. EXPECT_EQ(body, res->body);
  5520. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5521. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5522. };
  5523. Headers identity{{"Accept-Encoding", ""}};
  5524. expect_body(cli.Get("/body", identity), "hello world");
  5525. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5526. expect_body(cli.Get("/body",
  5527. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5528. "he");
  5529. expect_body(cli.Get("/provider", identity), "hello");
  5530. expect_body(cli.Get("/empty", identity), "");
  5531. // A HEAD response may give the length of the body a GET would get.
  5532. auto res = cli.Head("/empty");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5535. }
  5536. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5537. Server svr;
  5538. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5539. res.set_content("short", "text/plain");
  5540. });
  5541. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5542. res.body += " with a footer";
  5543. res.set_header("Transfer-Encoding", "chunked");
  5544. });
  5545. thread t = thread([&] { svr.listen(HOST, PORT); });
  5546. auto se = detail::scope_exit([&] {
  5547. svr.stop();
  5548. t.join();
  5549. ASSERT_FALSE(svr.is_running());
  5550. });
  5551. svr.wait_until_ready();
  5552. Client cli(HOST, PORT);
  5553. cli.set_read_timeout(1, 0);
  5554. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ("short with a footer", res->body);
  5557. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5558. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5559. }
  5560. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5561. Server svr;
  5562. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5563. res.set_header("Content-Length", "3");
  5564. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5565. sink.write("abc", 3);
  5566. sink.done();
  5567. return true;
  5568. });
  5569. });
  5570. thread t = thread([&] { svr.listen(HOST, PORT); });
  5571. auto se = detail::scope_exit([&] {
  5572. svr.stop();
  5573. t.join();
  5574. ASSERT_FALSE(svr.is_running());
  5575. });
  5576. svr.wait_until_ready();
  5577. Client cli(HOST, PORT);
  5578. cli.set_keep_alive(true);
  5579. auto res = cli.Get("/");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ("abc", res->body);
  5582. EXPECT_FALSE(res->has_header("Content-Length"));
  5583. EXPECT_EQ("close", res->get_header_value("Connection"));
  5584. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5585. // No body to delimit
  5586. auto head = cli.Head("/");
  5587. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5588. EXPECT_FALSE(head->has_header("Connection"));
  5589. }
  5590. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5591. #ifdef CPPHTTPLIB_SSL_ENABLED
  5592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5593. ASSERT_TRUE(svr.is_valid());
  5594. #else
  5595. Server svr;
  5596. #endif
  5597. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5598. if (req.path == "/routing_handler") {
  5599. res.set_header("PRE_ROUTING", "on");
  5600. res.set_content("Routing Handler", "text/plain");
  5601. return httplib::Server::HandlerResponse::Handled;
  5602. }
  5603. return httplib::Server::HandlerResponse::Unhandled;
  5604. });
  5605. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5606. res.set_content("Error", "text/html");
  5607. });
  5608. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5609. if (req.path == "/routing_handler") {
  5610. res.set_header("POST_ROUTING", "on");
  5611. }
  5612. });
  5613. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5614. res.set_content("Hello World!\n", "text/plain");
  5615. });
  5616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5617. auto se = detail::scope_exit([&] {
  5618. svr.stop();
  5619. thread.join();
  5620. ASSERT_FALSE(svr.is_running());
  5621. });
  5622. svr.wait_until_ready();
  5623. {
  5624. #ifdef CPPHTTPLIB_SSL_ENABLED
  5625. SSLClient cli(HOST, PORT);
  5626. cli.enable_server_certificate_verification(false);
  5627. #else
  5628. Client cli(HOST, PORT);
  5629. #endif
  5630. auto res = cli.Get("/routing_handler");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("Routing Handler", res->body);
  5634. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5635. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5636. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5637. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5638. }
  5639. {
  5640. #ifdef CPPHTTPLIB_SSL_ENABLED
  5641. SSLClient cli(HOST, PORT);
  5642. cli.enable_server_certificate_verification(false);
  5643. #else
  5644. Client cli(HOST, PORT);
  5645. #endif
  5646. auto res = cli.Get("/hi");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. EXPECT_EQ(StatusCode::OK_200, res->status);
  5649. EXPECT_EQ("Hello World!\n", res->body);
  5650. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5651. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5652. }
  5653. {
  5654. #ifdef CPPHTTPLIB_SSL_ENABLED
  5655. SSLClient cli(HOST, PORT);
  5656. cli.enable_server_certificate_verification(false);
  5657. #else
  5658. Client cli(HOST, PORT);
  5659. #endif
  5660. auto res = cli.Get("/aaa");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5663. EXPECT_EQ("Error", res->body);
  5664. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5665. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5666. }
  5667. }
  5668. TEST(RequestHandlerTest, PreRequestHandler) {
  5669. auto route_path = "/user/:user";
  5670. Server svr;
  5671. svr.Get("/hi", [](const Request &, Response &res) {
  5672. res.set_content("hi", "text/plain");
  5673. });
  5674. svr.Get(route_path, [](const Request &req, Response &res) {
  5675. res.set_content(req.path_params.at("user"), "text/plain");
  5676. });
  5677. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5678. if (req.matched_route == route_path) {
  5679. auto user = req.path_params.at("user");
  5680. if (user != "john") {
  5681. res.status = StatusCode::Forbidden_403;
  5682. res.set_content("error", "text/html");
  5683. return Server::HandlerResponse::Handled;
  5684. }
  5685. }
  5686. return Server::HandlerResponse::Unhandled;
  5687. });
  5688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5689. auto se = detail::scope_exit([&] {
  5690. svr.stop();
  5691. thread.join();
  5692. ASSERT_FALSE(svr.is_running());
  5693. });
  5694. svr.wait_until_ready();
  5695. Client cli(HOST, PORT);
  5696. {
  5697. auto res = cli.Get("/hi");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ("hi", res->body);
  5701. }
  5702. {
  5703. auto res = cli.Get("/user/john");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ("john", res->body);
  5707. }
  5708. {
  5709. auto res = cli.Get("/user/invalid-user");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5712. EXPECT_EQ("error", res->body);
  5713. }
  5714. }
  5715. // The pre-request handler must run before the request body is read, so a
  5716. // rejected request never forces the server to buffer a (potentially large)
  5717. // body. Here the posted body is larger than the payload limit: if the body
  5718. // were read first the server would answer 413, but because the pre-request
  5719. // handler runs first it answers 403 and the body is never read.
  5720. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5721. Server svr;
  5722. svr.set_payload_max_length(8);
  5723. auto handler_ran = false;
  5724. svr.Post("/reject", [&](const Request &req, Response &res) {
  5725. handler_ran = true;
  5726. res.set_content(req.body, "text/plain");
  5727. });
  5728. svr.Post("/accept", [](const Request &req, Response &res) {
  5729. res.set_content(req.body, "text/plain");
  5730. });
  5731. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5732. if (req.matched_route == "/reject") {
  5733. res.status = StatusCode::Forbidden_403;
  5734. res.set_content("denied", "text/plain");
  5735. return Server::HandlerResponse::Handled;
  5736. }
  5737. return Server::HandlerResponse::Unhandled;
  5738. });
  5739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5740. auto se = detail::scope_exit([&] {
  5741. svr.stop();
  5742. thread.join();
  5743. ASSERT_FALSE(svr.is_running());
  5744. });
  5745. svr.wait_until_ready();
  5746. Client cli(HOST, PORT);
  5747. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5748. // rejects with 403 before the body is read, so 413 is never reached.
  5749. {
  5750. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5753. EXPECT_EQ("denied", res->body);
  5754. EXPECT_FALSE(handler_ran);
  5755. }
  5756. // An approved route still reads the body and enforces the payload limit.
  5757. {
  5758. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5761. }
  5762. }
  5763. TEST(UserDataTest, BasicOperations) {
  5764. httplib::UserData ud;
  5765. // Initially empty
  5766. EXPECT_FALSE(ud.has("key"));
  5767. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5768. // set and get
  5769. ud.set("key", 42);
  5770. EXPECT_TRUE(ud.has("key"));
  5771. auto *p = ud.get<int>("key");
  5772. ASSERT_NE(nullptr, p);
  5773. EXPECT_EQ(42, *p);
  5774. // Type mismatch → nullptr
  5775. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5776. // Overwrite with different type
  5777. ud.set("key", std::string("hello"));
  5778. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5779. auto *s = ud.get<std::string>("key");
  5780. ASSERT_NE(nullptr, s);
  5781. EXPECT_EQ("hello", *s);
  5782. // erase
  5783. ud.erase("key");
  5784. EXPECT_FALSE(ud.has("key"));
  5785. // clear
  5786. ud.set("a", 1);
  5787. ud.set("b", 2);
  5788. ud.clear();
  5789. EXPECT_FALSE(ud.has("a"));
  5790. EXPECT_FALSE(ud.has("b"));
  5791. }
  5792. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5793. struct AuthCtx {
  5794. std::string user_id;
  5795. };
  5796. Server svr;
  5797. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5798. res.user_data.set("auth", AuthCtx{"alice"});
  5799. return Server::HandlerResponse::Unhandled;
  5800. });
  5801. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5802. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5803. ASSERT_NE(nullptr, ctx);
  5804. res.set_content("Hello " + ctx->user_id, "text/plain");
  5805. });
  5806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5807. auto se = detail::scope_exit([&] {
  5808. svr.stop();
  5809. thread.join();
  5810. ASSERT_FALSE(svr.is_running());
  5811. });
  5812. svr.wait_until_ready();
  5813. Client cli(HOST, PORT);
  5814. auto res = cli.Get("/me");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("Hello alice", res->body);
  5818. }
  5819. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5820. struct RoleCtx {
  5821. std::string role;
  5822. };
  5823. Server svr;
  5824. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5825. res.user_data.set("role", RoleCtx{"admin"});
  5826. return Server::HandlerResponse::Unhandled;
  5827. });
  5828. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5829. auto *ctx = res.user_data.get<RoleCtx>("role");
  5830. ASSERT_NE(nullptr, ctx);
  5831. res.set_content(ctx->role, "text/plain");
  5832. });
  5833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5834. auto se = detail::scope_exit([&] {
  5835. svr.stop();
  5836. thread.join();
  5837. ASSERT_FALSE(svr.is_running());
  5838. });
  5839. svr.wait_until_ready();
  5840. Client cli(HOST, PORT);
  5841. auto res = cli.Get("/role");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("admin", res->body);
  5845. }
  5846. TEST(InvalidFormatTest, StatusCode) {
  5847. Server svr;
  5848. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5849. res.set_content("Hello World!\n", "text/plain");
  5850. res.status = 9999; // Status should be a three-digit code...
  5851. });
  5852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5853. auto se = detail::scope_exit([&] {
  5854. svr.stop();
  5855. thread.join();
  5856. ASSERT_FALSE(svr.is_running());
  5857. });
  5858. svr.wait_until_ready();
  5859. {
  5860. Client cli(HOST, PORT);
  5861. auto res = cli.Get("/hi");
  5862. ASSERT_FALSE(res);
  5863. }
  5864. }
  5865. TEST(URLFragmentTest, WithFragment) {
  5866. Server svr;
  5867. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5868. EXPECT_TRUE(req.target == "/hi");
  5869. });
  5870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5871. auto se = detail::scope_exit([&] {
  5872. svr.stop();
  5873. thread.join();
  5874. ASSERT_FALSE(svr.is_running());
  5875. });
  5876. svr.wait_until_ready();
  5877. {
  5878. Client cli(HOST, PORT);
  5879. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5880. EXPECT_TRUE(res);
  5881. EXPECT_EQ(StatusCode::OK_200, res->status);
  5882. res = cli.Get("/hi%23key1=val1=key2=val2");
  5883. EXPECT_TRUE(res);
  5884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5885. }
  5886. }
  5887. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5888. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5889. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5890. Server svr;
  5891. std::vector<std::string> targets;
  5892. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5893. targets.push_back(req.target);
  5894. });
  5895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5896. auto se = detail::scope_exit([&] {
  5897. svr.stop();
  5898. thread.join();
  5899. ASSERT_FALSE(svr.is_running());
  5900. });
  5901. svr.wait_until_ready();
  5902. Client cli(HOST, PORT);
  5903. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5904. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5905. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5906. // A '?' after the '#' belongs to the fragment, not to the query.
  5907. Request req;
  5908. req.method = "GET";
  5909. req.path = "/hi#f?x=1";
  5910. req.params.emplace("a", "1");
  5911. Response res;
  5912. auto error = Error::Success;
  5913. EXPECT_TRUE(cli.send(req, res, error));
  5914. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5915. "/hi?a=1"}),
  5916. targets);
  5917. }
  5918. TEST(HeaderWriter, SetHeaderWriter) {
  5919. Server svr;
  5920. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5921. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5922. return detail::write_headers(strm, hdrs);
  5923. });
  5924. svr.Get("/hi", [](const Request &req, Response &res) {
  5925. auto it = req.headers.find("CustomClientHeader");
  5926. EXPECT_TRUE(it != req.headers.end());
  5927. EXPECT_EQ(it->second, "CustomClientValue");
  5928. res.set_content("Hello World!\n", "text/plain");
  5929. });
  5930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5931. auto se = detail::scope_exit([&] {
  5932. svr.stop();
  5933. thread.join();
  5934. ASSERT_FALSE(svr.is_running());
  5935. });
  5936. svr.wait_until_ready();
  5937. {
  5938. Client cli(HOST, PORT);
  5939. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5940. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5941. return detail::write_headers(strm, hdrs);
  5942. });
  5943. auto res = cli.Get("/hi");
  5944. EXPECT_TRUE(res);
  5945. EXPECT_EQ(StatusCode::OK_200, res->status);
  5946. auto it = res->headers.find("CustomServerHeader");
  5947. EXPECT_TRUE(it != res->headers.end());
  5948. EXPECT_EQ(it->second, "CustomServerValue");
  5949. }
  5950. }
  5951. class ServerTest : public ::testing::Test {
  5952. protected:
  5953. ServerTest()
  5954. : cli_(HOST, PORT)
  5955. #ifdef CPPHTTPLIB_SSL_ENABLED
  5956. ,
  5957. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5958. #endif
  5959. {
  5960. #ifdef CPPHTTPLIB_SSL_ENABLED
  5961. cli_.enable_server_certificate_verification(false);
  5962. #endif
  5963. // Allow LARGE_DATA (100MB) responses
  5964. cli_.set_payload_max_length(200 * 1024 * 1024);
  5965. }
  5966. virtual void SetUp() {
  5967. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5968. svr_.set_payload_max_length(200 * 1024 * 1024);
  5969. svr_.set_mount_point("/", "./www");
  5970. svr_.set_mount_point("/mount", "./www2");
  5971. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5972. svr_.Get("/hi",
  5973. [&](const Request & /*req*/, Response &res) {
  5974. res.set_content("Hello World!", "text/plain");
  5975. })
  5976. .Get("/file_content",
  5977. [&](const Request & /*req*/, Response &res) {
  5978. res.set_file_content("./www/dir/test.html");
  5979. })
  5980. .Get("/file_content_with_content_type",
  5981. [&](const Request & /*req*/, Response &res) {
  5982. res.set_file_content("./www/file", "text/plain");
  5983. })
  5984. .Get("/invalid_file_content",
  5985. [&](const Request & /*req*/, Response &res) {
  5986. res.set_file_content("./www/dir/invalid_file_path");
  5987. })
  5988. .Get("/http_response_splitting",
  5989. [&](const Request & /*req*/, Response &res) {
  5990. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5991. EXPECT_EQ(0U, res.headers.size());
  5992. EXPECT_FALSE(res.has_header("a"));
  5993. res.set_header("a", "1\nSet-Cookie: a=1");
  5994. EXPECT_EQ(0U, res.headers.size());
  5995. EXPECT_FALSE(res.has_header("a"));
  5996. res.set_header("a", "1\rSet-Cookie: a=1");
  5997. EXPECT_EQ(0U, res.headers.size());
  5998. EXPECT_FALSE(res.has_header("a"));
  5999. res.set_header("a\r\nb", "0");
  6000. EXPECT_EQ(0U, res.headers.size());
  6001. EXPECT_FALSE(res.has_header("a"));
  6002. res.set_header("a\rb", "0");
  6003. EXPECT_EQ(0U, res.headers.size());
  6004. EXPECT_FALSE(res.has_header("a"));
  6005. res.set_header("a\nb", "0");
  6006. EXPECT_EQ(0U, res.headers.size());
  6007. EXPECT_FALSE(res.has_header("a"));
  6008. res.set_redirect("1\r\nSet-Cookie: a=1");
  6009. EXPECT_EQ(0U, res.headers.size());
  6010. EXPECT_FALSE(res.has_header("Location"));
  6011. })
  6012. .Get("/slow",
  6013. [&](const Request & /*req*/, Response &res) {
  6014. std::this_thread::sleep_for(std::chrono::seconds(4));
  6015. res.set_content("slow", "text/plain");
  6016. })
  6017. #if 0
  6018. .Post("/slowpost",
  6019. [&](const Request & /*req*/, Response &res) {
  6020. std::this_thread::sleep_for(std::chrono::seconds(2));
  6021. res.set_content("slow", "text/plain");
  6022. })
  6023. #endif
  6024. .Get("/remote_addr",
  6025. [&](const Request &req, Response &res) {
  6026. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6027. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6028. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6029. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6030. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6031. #endif
  6032. res.set_content(req.remote_addr, "text/plain");
  6033. })
  6034. .Get("/local_addr",
  6035. [&](const Request &req, Response &res) {
  6036. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6037. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6038. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6039. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6040. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6041. #endif
  6042. auto local_addr = req.local_addr;
  6043. auto local_port = std::to_string(req.local_port);
  6044. res.set_content(local_addr.append(":").append(local_port),
  6045. "text/plain");
  6046. })
  6047. .Get("/endwith%",
  6048. [&](const Request & /*req*/, Response &res) {
  6049. res.set_content("Hello World!", "text/plain");
  6050. })
  6051. .Get("/a\\+\\+b",
  6052. [&](const Request &req, Response &res) {
  6053. ASSERT_TRUE(req.has_param("a +b"));
  6054. auto val = req.get_param_value("a +b");
  6055. res.set_content(val, "text/plain");
  6056. })
  6057. .Get("/", [&](const Request & /*req*/,
  6058. Response &res) { res.set_redirect("/hi"); })
  6059. .Post("/1",
  6060. [](const Request & /*req*/, Response &res) {
  6061. res.set_redirect("/2", StatusCode::SeeOther_303);
  6062. })
  6063. .Get("/2",
  6064. [](const Request & /*req*/, Response &res) {
  6065. res.set_content("redirected.", "text/plain");
  6066. res.status = StatusCode::OK_200;
  6067. })
  6068. .Post("/person",
  6069. [&](const Request &req, Response &res) {
  6070. if (req.has_param("name") && req.has_param("note")) {
  6071. persons_[req.get_param_value("name")] =
  6072. req.get_param_value("note");
  6073. } else {
  6074. res.status = StatusCode::BadRequest_400;
  6075. }
  6076. })
  6077. .Put("/person",
  6078. [&](const Request &req, Response &res) {
  6079. if (req.has_param("name") && req.has_param("note")) {
  6080. persons_[req.get_param_value("name")] =
  6081. req.get_param_value("note");
  6082. } else {
  6083. res.status = StatusCode::BadRequest_400;
  6084. }
  6085. })
  6086. .Get("/person/(.*)",
  6087. [&](const Request &req, Response &res) {
  6088. string name = req.matches[1];
  6089. if (persons_.find(name) != persons_.end()) {
  6090. auto note = persons_[name];
  6091. res.set_content(note, "text/plain");
  6092. } else {
  6093. res.status = StatusCode::NotFound_404;
  6094. }
  6095. })
  6096. .Delete("/person",
  6097. [&](const Request &req, Response &res) {
  6098. if (req.has_param("name")) {
  6099. string name = req.get_param_value("name");
  6100. if (persons_.find(name) != persons_.end()) {
  6101. persons_.erase(name);
  6102. res.set_content("DELETED", "text/plain");
  6103. } else {
  6104. res.status = StatusCode::NotFound_404;
  6105. }
  6106. } else {
  6107. res.status = StatusCode::BadRequest_400;
  6108. }
  6109. })
  6110. .Post("/x-www-form-urlencoded-json",
  6111. [&](const Request &req, Response &res) {
  6112. auto json = req.get_param_value("json");
  6113. ASSERT_EQ(JSON_DATA, json);
  6114. res.set_content(json, "appliation/json");
  6115. res.status = StatusCode::OK_200;
  6116. })
  6117. .Get("/streamed-chunked",
  6118. [&](const Request & /*req*/, Response &res) {
  6119. res.set_chunked_content_provider(
  6120. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6121. sink.os << "123";
  6122. sink.os << "456";
  6123. sink.os << "789";
  6124. sink.done();
  6125. return true;
  6126. });
  6127. })
  6128. .Get("/streamed-chunked-with-prohibited-trailer",
  6129. [&](const Request & /*req*/, Response &res) {
  6130. auto i = new int(0);
  6131. // Declare both a prohibited trailer (Content-Length) and an
  6132. // allowed one
  6133. res.set_header("Trailer", "Content-Length, X-Allowed");
  6134. res.set_chunked_content_provider(
  6135. "text/plain",
  6136. [i](size_t /*offset*/, DataSink &sink) {
  6137. switch (*i) {
  6138. case 0: sink.os << "123"; break;
  6139. case 1: sink.os << "456"; break;
  6140. case 2: sink.os << "789"; break;
  6141. case 3: {
  6142. sink.done_with_trailer(
  6143. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6144. } break;
  6145. }
  6146. (*i)++;
  6147. return true;
  6148. },
  6149. [i](bool success) {
  6150. EXPECT_TRUE(success);
  6151. delete i;
  6152. });
  6153. })
  6154. .Get("/streamed-chunked2",
  6155. [&](const Request & /*req*/, Response &res) {
  6156. auto i = new int(0);
  6157. res.set_chunked_content_provider(
  6158. "text/plain",
  6159. [i](size_t /*offset*/, DataSink &sink) {
  6160. switch (*i) {
  6161. case 0: sink.os << "123"; break;
  6162. case 1: sink.os << "456"; break;
  6163. case 2: sink.os << "789"; break;
  6164. case 3: sink.done(); break;
  6165. }
  6166. (*i)++;
  6167. return true;
  6168. },
  6169. [i](bool success) {
  6170. EXPECT_TRUE(success);
  6171. delete i;
  6172. });
  6173. })
  6174. .Get("/streamed-chunked-with-trailer",
  6175. [&](const Request & /*req*/, Response &res) {
  6176. auto i = new int(0);
  6177. res.set_header("Trailer", "Dummy1, Dummy2");
  6178. res.set_chunked_content_provider(
  6179. "text/plain",
  6180. [i](size_t /*offset*/, DataSink &sink) {
  6181. switch (*i) {
  6182. case 0: sink.os << "123"; break;
  6183. case 1: sink.os << "456"; break;
  6184. case 2: sink.os << "789"; break;
  6185. case 3: {
  6186. sink.done_with_trailer(
  6187. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6188. } break;
  6189. }
  6190. (*i)++;
  6191. return true;
  6192. },
  6193. [i](bool success) {
  6194. EXPECT_TRUE(success);
  6195. delete i;
  6196. });
  6197. })
  6198. .Get("/streamed",
  6199. [&](const Request & /*req*/, Response &res) {
  6200. res.set_content_provider(
  6201. 6, "text/plain",
  6202. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6203. sink.os << (offset < 3 ? "a" : "b");
  6204. return true;
  6205. });
  6206. })
  6207. .Get("/streamed-without-length",
  6208. [&](const Request & /*req*/, Response &res) {
  6209. auto data = new std::string("abcdefg");
  6210. res.set_content_provider(
  6211. "text/plain",
  6212. [data](size_t offset, DataSink &sink) {
  6213. if (offset < data->size()) {
  6214. sink.os << data->substr(offset);
  6215. }
  6216. sink.done();
  6217. return true;
  6218. },
  6219. [data](bool success) {
  6220. EXPECT_TRUE(success);
  6221. delete data;
  6222. });
  6223. })
  6224. .Get("/streamed-with-range",
  6225. [&](const Request &req, Response &res) {
  6226. auto data = new std::string("abcdefg");
  6227. // An explicit status keeps the server from picking the 206 it
  6228. // would otherwise choose for a ranged request, so the response
  6229. // is not a partial representation.
  6230. auto status = req.get_param_value("status");
  6231. if (status == "200") {
  6232. res.status = StatusCode::OK_200;
  6233. } else if (status == "403") {
  6234. res.status = StatusCode::Forbidden_403;
  6235. }
  6236. res.set_content_provider(
  6237. data->size(), "text/plain",
  6238. [data](size_t offset, size_t length, DataSink &sink) {
  6239. size_t DATA_CHUNK_SIZE = 4;
  6240. const auto &d = *data;
  6241. auto out_len =
  6242. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6243. auto ret =
  6244. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6245. EXPECT_TRUE(ret);
  6246. return true;
  6247. },
  6248. [data, &req](bool success) {
  6249. EXPECT_EQ(success, !req.has_param("error"));
  6250. delete data;
  6251. });
  6252. })
  6253. .Get("/streamed-cancel",
  6254. [&](const Request & /*req*/, Response &res) {
  6255. res.set_content_provider(
  6256. size_t(-1), "text/plain",
  6257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6258. sink.os << "data_chunk";
  6259. return true;
  6260. });
  6261. })
  6262. .Get("/regex-with-delimiter",
  6263. [&](const Request &req, Response & /*res*/) {
  6264. ASSERT_TRUE(req.has_param("key"));
  6265. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6266. })
  6267. .Get("/with-range",
  6268. [&](const Request & /*req*/, Response &res) {
  6269. res.set_content("abcdefg", "text/plain");
  6270. })
  6271. .Get("/test-start-time",
  6272. [&](const Request &req, Response & /*res*/) {
  6273. EXPECT_NE(req.start_time_,
  6274. std::chrono::steady_clock::time_point::min());
  6275. })
  6276. .Get("/with-range-customized-response",
  6277. [&](const Request & /*req*/, Response &res) {
  6278. res.status = StatusCode::BadRequest_400;
  6279. res.set_content(JSON_DATA, "application/json");
  6280. })
  6281. .Post("/chunked",
  6282. [&](const Request &req, Response & /*res*/) {
  6283. EXPECT_EQ(req.body, "dechunked post body");
  6284. })
  6285. .Post("/large-chunked",
  6286. [&](const Request &req, Response & /*res*/) {
  6287. std::string expected(6 * 30 * 1024u, 'a');
  6288. EXPECT_EQ(req.body, expected);
  6289. })
  6290. .Post("/multipart",
  6291. [&](const Request &req, Response & /*res*/) {
  6292. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6293. req.form.get_field_count("text2") +
  6294. req.form.get_field_count("file3") +
  6295. req.form.get_field_count("file4"));
  6296. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6297. req.form.get_file_count("file2"));
  6298. ASSERT_TRUE(!req.form.has_file("???"));
  6299. ASSERT_TRUE(!req.form.has_field("???"));
  6300. ASSERT_TRUE(req.body.empty());
  6301. {
  6302. const auto &text = req.form.get_field("text1");
  6303. EXPECT_EQ("text default", text);
  6304. }
  6305. {
  6306. const auto &text = req.form.get_field("text2");
  6307. EXPECT_EQ("aωb", text);
  6308. }
  6309. {
  6310. const auto &file = req.form.get_file("file1");
  6311. EXPECT_EQ("hello.txt", file.filename);
  6312. EXPECT_EQ("text/plain", file.content_type);
  6313. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6314. }
  6315. {
  6316. const auto &file = req.form.get_file("file2");
  6317. EXPECT_EQ("world.json", file.filename);
  6318. EXPECT_EQ("application/json", file.content_type);
  6319. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6320. }
  6321. {
  6322. const auto &text = req.form.get_field("file3");
  6323. EXPECT_EQ(0u, text.size());
  6324. }
  6325. {
  6326. const auto &text = req.form.get_field("file4");
  6327. EXPECT_EQ(0u, text.size());
  6328. }
  6329. })
  6330. .Post("/multipart/multi_file_values",
  6331. [&](const Request &req, Response & /*res*/) {
  6332. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6333. req.form.get_field_count("multi_text1"));
  6334. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6335. ASSERT_TRUE(!req.form.has_file("???"));
  6336. ASSERT_TRUE(!req.form.has_field("???"));
  6337. ASSERT_TRUE(req.body.empty());
  6338. {
  6339. const auto &text = req.form.get_field("text");
  6340. EXPECT_EQ("default text", text);
  6341. }
  6342. {
  6343. const auto &text1_values = req.form.get_fields("multi_text1");
  6344. EXPECT_EQ(2u, text1_values.size());
  6345. EXPECT_EQ("aaaaa", text1_values[0]);
  6346. EXPECT_EQ("bbbbb", text1_values[1]);
  6347. }
  6348. {
  6349. const auto &file1_values = req.form.get_files("multi_file1");
  6350. EXPECT_EQ(2u, file1_values.size());
  6351. auto file1 = file1_values[0];
  6352. EXPECT_EQ(file1.filename, "hello.txt");
  6353. EXPECT_EQ(file1.content_type, "text/plain");
  6354. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6355. auto file2 = file1_values[1];
  6356. EXPECT_EQ(file2.filename, "world.json");
  6357. EXPECT_EQ(file2.content_type, "application/json");
  6358. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6359. }
  6360. })
  6361. .Post("/empty",
  6362. [&](const Request &req, Response &res) {
  6363. EXPECT_EQ(req.body, "");
  6364. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6365. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6366. res.set_content("empty", "text/plain");
  6367. })
  6368. .Post("/empty-no-content-type",
  6369. [&](const Request &req, Response &res) {
  6370. EXPECT_EQ(req.body, "");
  6371. EXPECT_FALSE(req.has_header("Content-Type"));
  6372. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6373. res.set_content("empty-no-content-type", "text/plain");
  6374. })
  6375. .Post("/path-only",
  6376. [&](const Request &req, Response &res) {
  6377. EXPECT_EQ(req.body, "");
  6378. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6379. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6380. res.set_content("path-only", "text/plain");
  6381. })
  6382. .Post("/path-headers-only",
  6383. [&](const Request &req, Response &res) {
  6384. EXPECT_EQ(req.body, "");
  6385. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6386. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6387. EXPECT_EQ("world", req.get_header_value("hello"));
  6388. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6389. res.set_content("path-headers-only", "text/plain");
  6390. })
  6391. .Post("/post-large",
  6392. [&](const Request &req, Response &res) {
  6393. EXPECT_EQ(req.body, LARGE_DATA);
  6394. res.set_content(req.body, "text/plain");
  6395. })
  6396. .Post("/post-loopback",
  6397. [&](const Request &, Response &res,
  6398. ContentReader const &content_reader) {
  6399. std::string body;
  6400. content_reader([&](const char *data, size_t data_length) {
  6401. body.append(data, data_length);
  6402. return true;
  6403. });
  6404. res.set_content(body, "text/plain");
  6405. })
  6406. .Put("/put-loopback",
  6407. [&](const Request &, Response &res,
  6408. ContentReader const &content_reader) {
  6409. std::string body;
  6410. content_reader([&](const char *data, size_t data_length) {
  6411. body.append(data, data_length);
  6412. return true;
  6413. });
  6414. res.set_content(body, "text/plain");
  6415. })
  6416. .Patch("/patch-loopback",
  6417. [&](const Request &, Response &res,
  6418. ContentReader const &content_reader) {
  6419. std::string body;
  6420. content_reader([&](const char *data, size_t data_length) {
  6421. body.append(data, data_length);
  6422. return true;
  6423. });
  6424. res.set_content(body, "text/plain");
  6425. })
  6426. .Put("/empty-no-content-type",
  6427. [&](const Request &req, Response &res) {
  6428. EXPECT_EQ(req.body, "");
  6429. EXPECT_FALSE(req.has_header("Content-Type"));
  6430. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6431. res.set_content("empty-no-content-type", "text/plain");
  6432. })
  6433. .Put("/put",
  6434. [&](const Request &req, Response &res) {
  6435. EXPECT_EQ(req.body, "PUT");
  6436. res.set_content(req.body, "text/plain");
  6437. })
  6438. .Put("/put-large",
  6439. [&](const Request &req, Response &res) {
  6440. EXPECT_EQ(req.body, LARGE_DATA);
  6441. res.set_content(req.body, "text/plain");
  6442. })
  6443. .Patch("/patch",
  6444. [&](const Request &req, Response &res) {
  6445. EXPECT_EQ(req.body, "PATCH");
  6446. res.set_content(req.body, "text/plain");
  6447. })
  6448. .Delete("/delete",
  6449. [&](const Request & /*req*/, Response &res) {
  6450. res.set_content("DELETE", "text/plain");
  6451. })
  6452. .Delete("/delete-body",
  6453. [&](const Request &req, Response &res) {
  6454. EXPECT_EQ(req.body, "content");
  6455. res.set_content(req.body, "text/plain");
  6456. })
  6457. .Options(R"(\*)",
  6458. [&](const Request & /*req*/, Response &res) {
  6459. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6460. })
  6461. .CustomRoute("PROPFIND", "/dav/:id",
  6462. [&](const Request &req, Response &res) {
  6463. res.set_header("x-body-size",
  6464. std::to_string(req.body.size()));
  6465. res.set_header("x-matched-route", req.matched_route);
  6466. res.set_header("x-dav-id", req.path_params.at("id"));
  6467. res.status = StatusCode::MultiStatus_207;
  6468. res.set_content(req.body, "application/xml");
  6469. })
  6470. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6471. [&](const Request &req, Response &res) {
  6472. res.set_header("x-dav-match", req.matches[1]);
  6473. res.status = StatusCode::MultiStatus_207;
  6474. })
  6475. .CustomRoute("MKCOL", "/dav-mkcol",
  6476. [&](const Request &req, Response &res) {
  6477. EXPECT_TRUE(req.body.empty());
  6478. res.status = StatusCode::Created_201;
  6479. })
  6480. .CustomRoute(
  6481. "REPORT", "/dav-report",
  6482. [&](const Request & /*req*/, Response &res,
  6483. const ContentReader &content_reader) {
  6484. std::string body;
  6485. content_reader([&](const char *data, size_t data_length) {
  6486. body.append(data, data_length);
  6487. return true;
  6488. });
  6489. res.set_header("x-body-size", std::to_string(body.size()));
  6490. res.status = StatusCode::MultiStatus_207;
  6491. res.set_content(body, "application/xml");
  6492. })
  6493. .Get("/request-target",
  6494. [&](const Request &req, Response & /*res*/) {
  6495. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6496. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6497. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6498. })
  6499. .Get("/long-query-value",
  6500. [&](const Request &req, Response & /*res*/) {
  6501. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6502. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6503. })
  6504. .Get("/too-long-query-value",
  6505. [&](const Request &req, Response & /*res*/) {
  6506. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6507. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6508. })
  6509. .Get("/array-param",
  6510. [&](const Request &req, Response & /*res*/) {
  6511. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6512. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6513. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6514. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6515. })
  6516. .Get("/array-param-values",
  6517. [&](const Request &req, Response & /*res*/) {
  6518. auto values = req.get_param_values("array");
  6519. EXPECT_EQ(3u, values.size());
  6520. EXPECT_EQ("value1", values[0]);
  6521. EXPECT_EQ("value2", values[1]);
  6522. EXPECT_EQ("value3", values[2]);
  6523. auto empty = req.get_param_values("nonexistent");
  6524. EXPECT_TRUE(empty.empty());
  6525. })
  6526. .Post("/validate-no-multiple-headers",
  6527. [&](const Request &req, Response & /*res*/) {
  6528. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6529. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6530. })
  6531. .Post("/content_receiver",
  6532. [&](const Request &req, Response &res,
  6533. const ContentReader &content_reader) {
  6534. if (req.is_multipart_form_data()) {
  6535. std::vector<FormData> items;
  6536. content_reader(
  6537. [&](const FormData &file) {
  6538. items.push_back(file);
  6539. return true;
  6540. },
  6541. [&](const char *data, size_t data_length) {
  6542. items.back().content.append(data, data_length);
  6543. return true;
  6544. });
  6545. EXPECT_EQ(5u, items.size());
  6546. {
  6547. const auto &file = get_file_value(items, "text1");
  6548. EXPECT_TRUE(file.filename.empty());
  6549. EXPECT_EQ("text default", file.content);
  6550. }
  6551. {
  6552. const auto &file = get_file_value(items, "text2");
  6553. EXPECT_TRUE(file.filename.empty());
  6554. EXPECT_EQ("aωb", file.content);
  6555. }
  6556. {
  6557. const auto &file = get_file_value(items, "file1");
  6558. EXPECT_EQ("hello.txt", file.filename);
  6559. EXPECT_EQ("text/plain", file.content_type);
  6560. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6561. }
  6562. {
  6563. const auto &file = get_file_value(items, "file2");
  6564. EXPECT_EQ("world.json", file.filename);
  6565. EXPECT_EQ("application/json", file.content_type);
  6566. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6567. }
  6568. {
  6569. const auto &file = get_file_value(items, "file3");
  6570. EXPECT_TRUE(file.filename.empty());
  6571. EXPECT_EQ("application/octet-stream", file.content_type);
  6572. EXPECT_EQ(0u, file.content.size());
  6573. }
  6574. } else {
  6575. std::string body;
  6576. content_reader([&](const char *data, size_t data_length) {
  6577. EXPECT_EQ(7U, data_length);
  6578. body.append(data, data_length);
  6579. return true;
  6580. });
  6581. EXPECT_EQ(body, "content");
  6582. res.set_content(body, "text/plain");
  6583. }
  6584. })
  6585. .Put("/content_receiver",
  6586. [&](const Request & /*req*/, Response &res,
  6587. const ContentReader &content_reader) {
  6588. std::string body;
  6589. content_reader([&](const char *data, size_t data_length) {
  6590. body.append(data, data_length);
  6591. return true;
  6592. });
  6593. EXPECT_EQ(body, "content");
  6594. res.set_content(body, "text/plain");
  6595. })
  6596. .Patch("/content_receiver",
  6597. [&](const Request & /*req*/, Response &res,
  6598. const ContentReader &content_reader) {
  6599. std::string body;
  6600. content_reader([&](const char *data, size_t data_length) {
  6601. body.append(data, data_length);
  6602. return true;
  6603. });
  6604. EXPECT_EQ(body, "content");
  6605. res.set_content(body, "text/plain");
  6606. })
  6607. .Post("/query-string-and-body",
  6608. [&](const Request &req, Response & /*res*/) {
  6609. ASSERT_TRUE(req.has_param("key"));
  6610. EXPECT_EQ(req.get_param_value("key"), "value");
  6611. EXPECT_EQ(req.body, "content");
  6612. })
  6613. .Get("/last-request",
  6614. [&](const Request &req, Response & /*res*/) {
  6615. EXPECT_EQ("close", req.get_header_value("Connection"));
  6616. })
  6617. .Get(R"(/redirect/(\d+))",
  6618. [&](const Request &req, Response &res) {
  6619. auto num = std::stoi(req.matches[1]) + 1;
  6620. std::string url = "/redirect/" + std::to_string(num);
  6621. res.set_redirect(url);
  6622. })
  6623. .Post("/binary",
  6624. [&](const Request &req, Response &res) {
  6625. EXPECT_EQ(4U, req.body.size());
  6626. EXPECT_EQ("application/octet-stream",
  6627. req.get_header_value("Content-Type"));
  6628. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6629. res.set_content(req.body, "application/octet-stream");
  6630. })
  6631. .Put("/binary",
  6632. [&](const Request &req, Response &res) {
  6633. EXPECT_EQ(4U, req.body.size());
  6634. EXPECT_EQ("application/octet-stream",
  6635. req.get_header_value("Content-Type"));
  6636. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6637. res.set_content(req.body, "application/octet-stream");
  6638. })
  6639. .Patch("/binary",
  6640. [&](const Request &req, Response &res) {
  6641. EXPECT_EQ(4U, req.body.size());
  6642. EXPECT_EQ("application/octet-stream",
  6643. req.get_header_value("Content-Type"));
  6644. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6645. res.set_content(req.body, "application/octet-stream");
  6646. })
  6647. .Delete("/binary",
  6648. [&](const Request &req, Response &res) {
  6649. EXPECT_EQ(4U, req.body.size());
  6650. EXPECT_EQ("application/octet-stream",
  6651. req.get_header_value("Content-Type"));
  6652. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6653. res.set_content(req.body, "application/octet-stream");
  6654. })
  6655. .Get("/issue1772",
  6656. [&](const Request & /*req*/, Response &res) {
  6657. res.status = 401;
  6658. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6659. })
  6660. .Delete("/issue609",
  6661. [](const httplib::Request &, httplib::Response &res,
  6662. const httplib::ContentReader &) {
  6663. res.set_content("ok", "text/plain");
  6664. })
  6665. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6666. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6667. .Get("/compress",
  6668. [&](const Request & /*req*/, Response &res) {
  6669. res.set_content(
  6670. "12345678901234567890123456789012345678901234567890123456789"
  6671. "01234567890123456789012345678901234567890",
  6672. "text/plain");
  6673. })
  6674. .Get("/compress-with-charset",
  6675. [&](const Request & /*req*/, Response &res) {
  6676. res.set_content(
  6677. "12345678901234567890123456789012345678901234567890123456789"
  6678. "01234567890123456789012345678901234567890",
  6679. "application/json; charset=utf-8");
  6680. })
  6681. .Get("/nocompress",
  6682. [&](const Request & /*req*/, Response &res) {
  6683. res.set_content(
  6684. "12345678901234567890123456789012345678901234567890123456789"
  6685. "01234567890123456789012345678901234567890",
  6686. "application/octet-stream");
  6687. })
  6688. .Post("/compress-multipart",
  6689. [&](const Request &req, Response & /*res*/) {
  6690. EXPECT_EQ(2u, req.form.fields.size());
  6691. ASSERT_TRUE(!req.form.has_field("???"));
  6692. {
  6693. const auto &text = req.form.get_field("key1");
  6694. EXPECT_EQ("test", text);
  6695. }
  6696. {
  6697. const auto &text = req.form.get_field("key2");
  6698. EXPECT_EQ("--abcdefg123", text);
  6699. }
  6700. })
  6701. #endif
  6702. ;
  6703. persons_["john"] = "programmer";
  6704. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6705. svr_.wait_until_ready();
  6706. }
  6707. virtual void TearDown() {
  6708. svr_.stop();
  6709. if (!request_threads_.empty()) {
  6710. std::this_thread::sleep_for(std::chrono::seconds(1));
  6711. for (auto &t : request_threads_) {
  6712. t.join();
  6713. }
  6714. }
  6715. t_.join();
  6716. }
  6717. map<string, string> persons_;
  6718. #ifdef CPPHTTPLIB_SSL_ENABLED
  6719. SSLClient cli_;
  6720. SSLServer svr_;
  6721. #else
  6722. Client cli_;
  6723. Server svr_;
  6724. #endif
  6725. thread t_;
  6726. std::vector<thread> request_threads_;
  6727. };
  6728. TEST_F(ServerTest, GetMethod200) {
  6729. auto res = cli_.Get("/hi");
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ("HTTP/1.1", res->version);
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ("OK", res->reason);
  6734. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6735. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6736. EXPECT_EQ("Hello World!", res->body);
  6737. }
  6738. TEST_F(ServerTest, GetEmptyFile) {
  6739. auto res = cli_.Get("/empty_file");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6743. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6744. EXPECT_EQ("", res->body);
  6745. }
  6746. TEST_F(ServerTest, GetFileContent) {
  6747. auto res = cli_.Get("/file_content");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6751. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6752. EXPECT_EQ("test.html", res->body);
  6753. }
  6754. TEST_F(ServerTest, GetFileContentWithRange) {
  6755. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6758. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6759. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6760. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6761. EXPECT_EQ("est", res->body);
  6762. }
  6763. TEST_F(ServerTest, GetFileContentWithContentType) {
  6764. auto res = cli_.Get("/file_content_with_content_type");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6769. EXPECT_EQ("file\n", res->body);
  6770. }
  6771. TEST_F(ServerTest, GetInvalidFileContent) {
  6772. auto res = cli_.Get("/invalid_file_content");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6775. }
  6776. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6777. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6779. EXPECT_EQ("HTTP/1.1", res->version);
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6782. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6783. EXPECT_EQ("Hello World!", res->body);
  6784. }
  6785. TEST_F(ServerTest, GetMethod302) {
  6786. auto res = cli_.Get("/");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. EXPECT_EQ(StatusCode::Found_302, res->status);
  6789. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6790. }
  6791. TEST_F(ServerTest, GetMethod302Redirect) {
  6792. cli_.set_follow_location(true);
  6793. auto res = cli_.Get("/");
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. EXPECT_EQ("Hello World!", res->body);
  6797. EXPECT_EQ("/hi", res->location);
  6798. }
  6799. TEST_F(ServerTest, GetMethod404) {
  6800. auto res = cli_.Get("/invalid");
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6803. }
  6804. TEST_F(ServerTest, HeadMethod200) {
  6805. auto res = cli_.Head("/hi");
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6809. EXPECT_TRUE(res->body.empty());
  6810. }
  6811. TEST_F(ServerTest, HeadMethod200Static) {
  6812. auto res = cli_.Head("/mount/dir/index.html");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6816. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6817. EXPECT_TRUE(res->body.empty());
  6818. }
  6819. TEST_F(ServerTest, HeadMethod404) {
  6820. auto res = cli_.Head("/invalid");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6823. EXPECT_TRUE(res->body.empty());
  6824. }
  6825. TEST_F(ServerTest, GetMethodPersonJohn) {
  6826. auto res = cli_.Get("/person/john");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6830. EXPECT_EQ("programmer", res->body);
  6831. }
  6832. TEST_F(ServerTest, PostMethod1) {
  6833. auto res = cli_.Get("/person/john1");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6836. res = cli_.Post("/person", "name=john1&note=coder",
  6837. "application/x-www-form-urlencoded");
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. ASSERT_EQ(StatusCode::OK_200, res->status);
  6840. res = cli_.Get("/person/john1");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. ASSERT_EQ(StatusCode::OK_200, res->status);
  6843. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6844. ASSERT_EQ("coder", res->body);
  6845. }
  6846. TEST_F(ServerTest, PostMethod2) {
  6847. auto res = cli_.Get("/person/john2");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6850. Params params;
  6851. params.emplace("name", "john2");
  6852. params.emplace("note", "coder");
  6853. res = cli_.Post("/person", params);
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. ASSERT_EQ(StatusCode::OK_200, res->status);
  6856. res = cli_.Get("/person/john2");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. ASSERT_EQ(StatusCode::OK_200, res->status);
  6859. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6860. ASSERT_EQ("coder", res->body);
  6861. }
  6862. TEST_F(ServerTest, PutMethod3) {
  6863. auto res = cli_.Get("/person/john3");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6866. Params params;
  6867. params.emplace("name", "john3");
  6868. params.emplace("note", "coder");
  6869. res = cli_.Put("/person", params);
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. ASSERT_EQ(StatusCode::OK_200, res->status);
  6872. res = cli_.Get("/person/john3");
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. ASSERT_EQ(StatusCode::OK_200, res->status);
  6875. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6876. ASSERT_EQ("coder", res->body);
  6877. }
  6878. TEST_F(ServerTest, DeleteMethod1) {
  6879. auto res = cli_.Get("/person/john4");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6882. Params params;
  6883. params.emplace("name", "john4");
  6884. params.emplace("note", "coder");
  6885. res = cli_.Post("/person", params);
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. ASSERT_EQ(StatusCode::OK_200, res->status);
  6888. res = cli_.Get("/person/john4");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. ASSERT_EQ(StatusCode::OK_200, res->status);
  6891. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6892. ASSERT_EQ("coder", res->body);
  6893. Params delete_params;
  6894. delete_params.emplace("name", "john4");
  6895. res = cli_.Delete("/person", delete_params);
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. ASSERT_EQ(StatusCode::OK_200, res->status);
  6898. ASSERT_EQ("DELETED", res->body);
  6899. res = cli_.Get("/person/john4");
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6902. }
  6903. TEST_F(ServerTest, DeleteMethod2) {
  6904. auto res = cli_.Get("/person/john5");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6907. Params params;
  6908. params.emplace("name", "john5");
  6909. params.emplace("note", "developer");
  6910. res = cli_.Post("/person", params);
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. res = cli_.Get("/person/john5");
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. ASSERT_EQ(StatusCode::OK_200, res->status);
  6916. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6917. ASSERT_EQ("developer", res->body);
  6918. Params delete_params;
  6919. delete_params.emplace("name", "john5");
  6920. Headers headers;
  6921. headers.emplace("Custom-Header", "test-value");
  6922. res = cli_.Delete("/person", headers, delete_params);
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. ASSERT_EQ(StatusCode::OK_200, res->status);
  6925. ASSERT_EQ("DELETED", res->body);
  6926. res = cli_.Get("/person/john5");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6929. }
  6930. TEST_F(ServerTest, DeleteMethod3) {
  6931. auto res = cli_.Get("/person/john6");
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6934. Params params;
  6935. params.emplace("name", "john6");
  6936. params.emplace("note", "tester");
  6937. res = cli_.Post("/person", params);
  6938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6939. ASSERT_EQ(StatusCode::OK_200, res->status);
  6940. res = cli_.Get("/person/john6");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. ASSERT_EQ(StatusCode::OK_200, res->status);
  6943. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6944. ASSERT_EQ("tester", res->body);
  6945. Params delete_params;
  6946. delete_params.emplace("name", "john6");
  6947. Headers headers;
  6948. headers.emplace("Custom-Header", "test-value");
  6949. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. ASSERT_EQ(StatusCode::OK_200, res->status);
  6952. ASSERT_EQ("DELETED", res->body);
  6953. res = cli_.Get("/person/john6");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6956. }
  6957. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6958. Params params;
  6959. params.emplace("json", JSON_DATA);
  6960. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. ASSERT_EQ(StatusCode::OK_200, res->status);
  6963. ASSERT_EQ(JSON_DATA, res->body);
  6964. }
  6965. TEST_F(ServerTest, PostEmptyContent) {
  6966. auto res = cli_.Post("/empty", "", "text/plain");
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. ASSERT_EQ(StatusCode::OK_200, res->status);
  6969. ASSERT_EQ("empty", res->body);
  6970. }
  6971. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6972. auto res = cli_.Post("/empty-no-content-type");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. ASSERT_EQ(StatusCode::OK_200, res->status);
  6975. ASSERT_EQ("empty-no-content-type", res->body);
  6976. }
  6977. TEST_F(ServerTest, PostPathOnly) {
  6978. auto res = cli_.Post("/path-only");
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. ASSERT_EQ(StatusCode::OK_200, res->status);
  6981. ASSERT_EQ("path-only", res->body);
  6982. }
  6983. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6984. auto res = cli_.Post("/path-headers-only",
  6985. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. ASSERT_EQ(StatusCode::OK_200, res->status);
  6988. ASSERT_EQ("path-headers-only", res->body);
  6989. }
  6990. TEST_F(ServerTest, PostLarge) {
  6991. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. ASSERT_EQ(StatusCode::OK_200, res->status);
  6994. EXPECT_EQ(LARGE_DATA, res->body);
  6995. }
  6996. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6997. auto res = cli_.Put("/empty-no-content-type");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. ASSERT_EQ(StatusCode::OK_200, res->status);
  7000. ASSERT_EQ("empty-no-content-type", res->body);
  7001. }
  7002. TEST_F(ServerTest, GetMethodDir) {
  7003. auto res = cli_.Get("/dir/");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7007. auto body = R"(<html>
  7008. <head>
  7009. </head>
  7010. <body>
  7011. <a href="/dir/test.html">Test</a>
  7012. <a href="/hi">hi</a>
  7013. </body>
  7014. </html>
  7015. )";
  7016. EXPECT_EQ(body, res->body);
  7017. }
  7018. TEST_F(ServerTest, GetMethodDirTest) {
  7019. auto res = cli_.Get("/dir/test.html");
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. EXPECT_EQ(StatusCode::OK_200, res->status);
  7022. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7023. EXPECT_EQ("test.html", res->body);
  7024. }
  7025. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7026. auto res = cli_.Get("/dir/../dir/test.html");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7029. }
  7030. TEST_F(ServerTest, GetMethodInvalidPath) {
  7031. auto res = cli_.Get("/dir/../test.html");
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7034. }
  7035. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7036. auto res = cli_.Get("/../www/dir/test.html");
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7039. }
  7040. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7041. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7044. }
  7045. TEST_F(ServerTest, GetMethodDirMountTest) {
  7046. auto res = cli_.Get("/mount/dir/test.html");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7050. EXPECT_EQ("test.html", res->body);
  7051. }
  7052. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7053. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7056. }
  7057. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7058. auto res = cli_.Get("/mount/dir/../test.html");
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7061. }
  7062. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7063. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7066. }
  7067. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7068. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7070. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7071. }
  7072. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7073. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7076. }
  7077. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7078. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7081. }
  7082. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7083. auto res = cli_.Get("/mount/dir");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7086. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7087. }
  7088. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7089. auto res = cli_.Get("//dir");
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7092. EXPECT_FALSE(res->has_header("Location"));
  7093. }
  7094. TEST_F(ServerTest, PostMethod303) {
  7095. auto res = cli_.Post("/1", "body", "text/plain");
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7098. EXPECT_EQ("/2", res->get_header_value("Location"));
  7099. }
  7100. TEST_F(ServerTest, PostMethod303Redirect) {
  7101. cli_.set_follow_location(true);
  7102. auto res = cli_.Post("/1", "body", "text/plain");
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::OK_200, res->status);
  7105. EXPECT_EQ("redirected.", res->body);
  7106. EXPECT_EQ("/2", res->location);
  7107. }
  7108. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7109. auto res = cli_.Get("/dir/test.abcde");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::OK_200, res->status);
  7112. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7113. EXPECT_EQ("abcde", res->body);
  7114. }
  7115. TEST_F(ServerTest, StaticFileRange) {
  7116. auto res =
  7117. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7120. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7121. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7122. EXPECT_EQ(true, res->has_header("Content-Range"));
  7123. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7124. EXPECT_EQ(std::string("cd"), res->body);
  7125. }
  7126. TEST_F(ServerTest, StaticFileRanges) {
  7127. auto res = cli_.Get("/dir/test.abcde",
  7128. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7131. EXPECT_TRUE(
  7132. res->get_header_value("Content-Type")
  7133. .find(
  7134. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7135. 0);
  7136. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7137. }
  7138. TEST_F(ServerTest, StaticFileRangeHead) {
  7139. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7142. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7143. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7144. EXPECT_EQ(true, res->has_header("Content-Range"));
  7145. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7146. }
  7147. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7148. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7152. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7153. EXPECT_EQ(true, res->has_header("Content-Range"));
  7154. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7155. res->get_header_value("Content-Range"));
  7156. EXPECT_EQ("LAST\n", res->body);
  7157. }
  7158. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7159. auto res =
  7160. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7164. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7165. EXPECT_EQ(true, res->has_header("Content-Range"));
  7166. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7167. }
  7168. TEST_F(ServerTest, StaticFileBigFile) {
  7169. auto res = cli_.Get("/dir/1MB.txt");
  7170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7173. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7174. }
  7175. TEST_F(ServerTest, InvalidBaseDirMount) {
  7176. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7177. }
  7178. TEST_F(ServerTest, Binary) {
  7179. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7180. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7181. "application/octet-stream");
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. ASSERT_EQ(StatusCode::OK_200, res->status);
  7184. ASSERT_EQ(4U, res->body.size());
  7185. res = cli_.Put("/binary", binary.data(), binary.size(),
  7186. "application/octet-stream");
  7187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7188. ASSERT_EQ(StatusCode::OK_200, res->status);
  7189. ASSERT_EQ(4U, res->body.size());
  7190. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7191. "application/octet-stream");
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. ASSERT_EQ(StatusCode::OK_200, res->status);
  7194. ASSERT_EQ(4U, res->body.size());
  7195. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7196. "application/octet-stream");
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. ASSERT_EQ(StatusCode::OK_200, res->status);
  7199. ASSERT_EQ(4U, res->body.size());
  7200. }
  7201. TEST_F(ServerTest, BinaryString) {
  7202. auto binary = std::string("\x00\x01\x02\x03", 4);
  7203. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. ASSERT_EQ(StatusCode::OK_200, res->status);
  7206. ASSERT_EQ(4U, res->body.size());
  7207. res = cli_.Put("/binary", binary, "application/octet-stream");
  7208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7209. ASSERT_EQ(StatusCode::OK_200, res->status);
  7210. ASSERT_EQ(4U, res->body.size());
  7211. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. ASSERT_EQ(StatusCode::OK_200, res->status);
  7214. ASSERT_EQ(4U, res->body.size());
  7215. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. ASSERT_EQ(StatusCode::OK_200, res->status);
  7218. ASSERT_EQ(4U, res->body.size());
  7219. }
  7220. TEST_F(ServerTest, EmptyRequest) {
  7221. auto res = cli_.Get("");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::Connection, res.error());
  7224. }
  7225. TEST_F(ServerTest, LongRequest) {
  7226. std::string request;
  7227. for (size_t i = 0; i < 545; i++) {
  7228. request += "/TooLongRequest";
  7229. }
  7230. request += "OK";
  7231. auto res = cli_.Get(request.c_str());
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7234. }
  7235. TEST_F(ServerTest, TooLongRequest) {
  7236. std::string request;
  7237. for (size_t i = 0; i < 546; i++) {
  7238. request += "/TooLongRequest";
  7239. }
  7240. request += "_NG";
  7241. auto start = std::chrono::high_resolution_clock::now();
  7242. cli_.set_keep_alive(true);
  7243. auto res = cli_.Get(request.c_str());
  7244. auto end = std::chrono::high_resolution_clock::now();
  7245. auto elapsed =
  7246. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7247. .count();
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7250. EXPECT_LE(elapsed, 1000);
  7251. EXPECT_EQ("close", res->get_header_value("Connection"));
  7252. EXPECT_FALSE(cli_.is_socket_open());
  7253. }
  7254. TEST_F(ServerTest, AlmostTooLongRequest) {
  7255. // test for #2046 - URI length check shouldn't include other content on req
  7256. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7257. // leading /, space, HTTP/1.1)
  7258. std::string request =
  7259. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7260. auto res = cli_.Get(request.c_str());
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7263. }
  7264. TEST_F(ServerTest, LongHeader) {
  7265. Request req;
  7266. req.method = "GET";
  7267. req.path = "/hi";
  7268. std::string host_and_port;
  7269. host_and_port += HOST;
  7270. host_and_port += ":";
  7271. host_and_port += std::to_string(PORT);
  7272. req.headers.emplace("Host", host_and_port.c_str());
  7273. req.headers.emplace("Accept", "*/*");
  7274. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7275. req.headers.emplace(
  7276. "Header-Name",
  7277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7305. "@@@@@@@@@@@@@@@@");
  7306. auto res = std::make_shared<Response>();
  7307. auto error = Error::Success;
  7308. auto ret = cli_.send(req, *res, error);
  7309. ASSERT_TRUE(ret);
  7310. EXPECT_EQ(StatusCode::OK_200, res->status);
  7311. }
  7312. TEST_F(ServerTest, LongQueryValue) {
  7313. auto start = std::chrono::high_resolution_clock::now();
  7314. cli_.set_keep_alive(true);
  7315. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7316. auto end = std::chrono::high_resolution_clock::now();
  7317. auto elapsed =
  7318. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7319. .count();
  7320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7321. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7322. EXPECT_LE(elapsed, 1000);
  7323. EXPECT_EQ("close", res->get_header_value("Connection"));
  7324. EXPECT_FALSE(cli_.is_socket_open());
  7325. }
  7326. TEST_F(ServerTest, TooLongQueryValue) {
  7327. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7328. ASSERT_FALSE(res);
  7329. EXPECT_EQ(Error::Read, res.error());
  7330. }
  7331. TEST_F(ServerTest, TooLongHeader) {
  7332. Request req;
  7333. req.method = "GET";
  7334. req.path = "/hi";
  7335. std::string host_and_port;
  7336. host_and_port += HOST;
  7337. host_and_port += ":";
  7338. host_and_port += std::to_string(PORT);
  7339. req.headers.emplace("Host", host_and_port.c_str());
  7340. req.headers.emplace("Accept", "*/*");
  7341. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7342. req.headers.emplace(
  7343. "Header-Name",
  7344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7372. "@@@@@@@@@@@@@@@@@");
  7373. auto res = std::make_shared<Response>();
  7374. auto error = Error::Success;
  7375. auto ret = cli_.send(req, *res, error);
  7376. ASSERT_TRUE(ret);
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. }
  7379. TEST_F(ServerTest, HeaderCountAtLimit) {
  7380. // Test with headers just under the 100 limit
  7381. httplib::Headers headers;
  7382. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7383. // This should keep us just under the 100 header limit
  7384. for (int i = 0; i < 95; i++) {
  7385. std::string name = "X-Test-Header-" + std::to_string(i);
  7386. std::string value = "value" + std::to_string(i);
  7387. headers.emplace(name, value);
  7388. }
  7389. // This should work fine as we're under the limit
  7390. auto res = cli_.Get("/hi", headers);
  7391. EXPECT_TRUE(res);
  7392. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7393. }
  7394. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7395. // Test with many headers to exceed the 100 limit
  7396. httplib::Headers headers;
  7397. // Add 150 headers to definitely exceed the 100 limit
  7398. for (int i = 0; i < 150; i++) {
  7399. std::string name = "X-Test-Header-" + std::to_string(i);
  7400. std::string value = "value" + std::to_string(i);
  7401. headers.emplace(name, value);
  7402. }
  7403. // This should fail due to exceeding header count limit
  7404. cli_.set_keep_alive(true);
  7405. auto res = cli_.Get("/hi", headers);
  7406. // The server should respond with 400 Bad Request
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7409. EXPECT_EQ("close", res->get_header_value("Connection"));
  7410. EXPECT_FALSE(cli_.is_socket_open());
  7411. }
  7412. TEST_F(ServerTest, PercentEncoding) {
  7413. auto res = cli_.Get("/e%6edwith%");
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::OK_200, res->status);
  7416. }
  7417. TEST_F(ServerTest, PercentEncodingUnicode) {
  7418. auto res = cli_.Get("/e%u006edwith%");
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. }
  7422. TEST_F(ServerTest, InvalidPercentEncoding) {
  7423. auto res = cli_.Get("/%endwith%");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7426. }
  7427. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7428. auto res = cli_.Get("/%uendwith%");
  7429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7431. }
  7432. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7433. auto res = cli_.Get("/hello?aaa=bbb%");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7436. }
  7437. TEST_F(ServerTest, PlusSignEncoding) {
  7438. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("a +b", res->body);
  7442. }
  7443. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7444. // This test simulates a potential DoS attack using many headers
  7445. // to verify our security fix prevents memory exhaustion
  7446. httplib::Headers attack_headers;
  7447. // Attempt to add many headers like an attacker would (200 headers to far
  7448. // exceed limit)
  7449. for (int i = 0; i < 200; i++) {
  7450. std::string name = "X-Attack-Header-" + std::to_string(i);
  7451. std::string value = "attack_payload_" + std::to_string(i);
  7452. attack_headers.emplace(name, value);
  7453. }
  7454. // Try to POST with excessive headers
  7455. cli_.set_keep_alive(true);
  7456. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7457. // Should either fail or return 400 Bad Request due to security limit
  7458. if (res) {
  7459. // If we get a response, it should be 400 Bad Request
  7460. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7461. EXPECT_EQ("close", res->get_header_value("Connection"));
  7462. }
  7463. EXPECT_FALSE(cli_.is_socket_open());
  7464. }
  7465. TEST_F(ServerTest, MultipartFormData) {
  7466. UploadFormDataItems items = {
  7467. {"text1", "text default", "", ""},
  7468. {"text2", "aωb", "", ""},
  7469. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7470. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7471. {"file3", "", "", "application/octet-stream"},
  7472. {"file4", "", "", " application/json tmp-string "}};
  7473. auto res = cli_.Post("/multipart", items);
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::OK_200, res->status);
  7476. }
  7477. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7478. UploadFormDataItems items = {
  7479. {"text", "default text", "", ""},
  7480. {"multi_text1", "aaaaa", "", ""},
  7481. {"multi_text1", "bbbbb", "", ""},
  7482. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7483. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7484. "application/json"},
  7485. };
  7486. auto res = cli_.Post("/multipart/multi_file_values", items);
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7491. auto res = cli_.Get("/hi");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7495. EXPECT_EQ("Hello World!", res->body);
  7496. }
  7497. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7498. Request req;
  7499. req.method = "POST";
  7500. req.path = "/chunked";
  7501. std::string host_and_port;
  7502. host_and_port += HOST;
  7503. host_and_port += ":";
  7504. host_and_port += std::to_string(PORT);
  7505. req.headers.emplace("Host", host_and_port.c_str());
  7506. req.headers.emplace("Accept", "*/*");
  7507. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7508. req.headers.emplace("Content-Type", "text/plain");
  7509. req.headers.emplace("Content-Length", "0");
  7510. req.headers.emplace(
  7511. "Transfer-Encoding",
  7512. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7513. // Client does not chunk, so make a chunked body manually.
  7514. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7515. auto res = std::make_shared<Response>();
  7516. auto error = Error::Success;
  7517. auto ret = cli_.send(req, *res, error);
  7518. ASSERT_TRUE(ret);
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. }
  7521. template <typename ClientT>
  7522. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7523. int expected_status) {
  7524. Request req;
  7525. req.method = "POST";
  7526. req.path = "/chunked";
  7527. std::string host_and_port;
  7528. host_and_port += HOST;
  7529. host_and_port += ":";
  7530. host_and_port += std::to_string(PORT);
  7531. req.headers.emplace("Host", host_and_port.c_str());
  7532. req.headers.emplace("Content-Length", "0");
  7533. req.headers.emplace("Transfer-Encoding", "chunked");
  7534. req.body = body;
  7535. auto res = std::make_shared<Response>();
  7536. auto error = Error::Success;
  7537. ASSERT_TRUE(cli.send(req, *res, error));
  7538. EXPECT_EQ(expected_status, res->status);
  7539. }
  7540. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7541. // rather than treat them as valid lengths.
  7542. template <typename ClientT>
  7543. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7544. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7545. }
  7546. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7547. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7548. }
  7549. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7550. expect_chunked_body_rejected(
  7551. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7552. }
  7553. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7554. // chunk-size line carries no CR, LF or other control character ahead of its
  7555. // terminator. Such a line must be refused rather than read as extension text.
  7556. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7557. expect_chunked_body_rejected(
  7558. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7559. }
  7560. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7561. expect_chunked_body_rejected(
  7562. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7563. }
  7564. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7565. expect_chunked_body_rejected(
  7566. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7567. }
  7568. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7569. // The literal stays split: a hex escape consumes every hex digit that
  7570. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7571. expect_chunked_body_rejected(
  7572. cli_, "4;a\x01"
  7573. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7574. }
  7575. // The bytes around chunk data are no payload, so they cannot ride on the
  7576. // payload limit
  7577. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7578. // Small enough that the whole request is sent before the server turns it
  7579. // down, yet past the limit by the last chunks
  7580. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7581. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7582. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7583. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7584. SCOPED_TRACE(size_line.substr(0, 2));
  7585. std::string body;
  7586. for (auto c : std::string("dechunked post body")) {
  7587. body += size_line + "\r\n" + c + "\r\n";
  7588. }
  7589. body += "0\r\n\r\n";
  7590. expect_chunked_body_rejected(cli_, body.c_str());
  7591. }
  7592. }
  7593. TEST_F(ServerTest, AcceptsChunkExtension) {
  7594. expect_chunked_body_status(cli_,
  7595. "4;name=value\r\ndech\r\n"
  7596. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7597. "0;last\r\n\r\n",
  7598. StatusCode::OK_200);
  7599. }
  7600. TEST_F(ServerTest, GetStreamed2) {
  7601. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7604. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7605. EXPECT_EQ(true, res->has_header("Content-Range"));
  7606. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7607. EXPECT_EQ(std::string("ab"), res->body);
  7608. }
  7609. TEST_F(ServerTest, GetStreamed) {
  7610. auto res = cli_.Get("/streamed");
  7611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7612. EXPECT_EQ(StatusCode::OK_200, res->status);
  7613. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7614. EXPECT_EQ(std::string("aaabbb"), res->body);
  7615. }
  7616. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7617. auto res = cli_.Get("/streamed-without-length",
  7618. Headers{make_range_header({{0, -1}})});
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(StatusCode::OK_200, res->status);
  7621. EXPECT_EQ(false, res->has_header("Content-Length"));
  7622. EXPECT_EQ(false, res->has_header("Content-Range"));
  7623. EXPECT_EQ(std::string("abcdefg"), res->body);
  7624. }
  7625. TEST_F(ServerTest, GetStreamedWithRange1) {
  7626. auto res =
  7627. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7630. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7631. EXPECT_EQ(true, res->has_header("Content-Range"));
  7632. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7633. EXPECT_EQ(std::string("def"), res->body);
  7634. }
  7635. TEST_F(ServerTest, GetStreamedWithRange2) {
  7636. auto res =
  7637. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7640. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ(true, res->has_header("Content-Range"));
  7642. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7643. EXPECT_EQ(std::string("bcdefg"), res->body);
  7644. }
  7645. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7646. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7648. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7649. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7650. EXPECT_EQ(true, res->has_header("Content-Range"));
  7651. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7652. EXPECT_EQ(std::string("efg"), res->body);
  7653. }
  7654. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7655. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7656. // the entire representation.
  7657. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7658. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7660. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7661. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7662. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7663. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7664. }
  7665. }
  7666. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7667. auto res =
  7668. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7671. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7672. EXPECT_EQ(false, res->has_header("Content-Range"));
  7673. EXPECT_EQ(0U, res->body.size());
  7674. }
  7675. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7676. // Only a 206 is served as a partial representation. Under any other status
  7677. // `apply_ranges()` reported the full content length, so the body must match
  7678. // that header, and the content provider must never be asked for an offset
  7679. // outside the representation.
  7680. auto check = [&](int status, const char *range) {
  7681. auto path =
  7682. std::string("/streamed-with-range?status=") + std::to_string(status);
  7683. auto ctx = path + " Range: " + range;
  7684. auto res = cli_.Get(path, Headers{{"Range", range}});
  7685. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7686. EXPECT_EQ(status, res->status) << ctx;
  7687. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7689. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7690. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7691. };
  7692. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7693. check(403, "bytes=3-5");
  7694. // The offset is far past the representation.
  7695. check(403, "bytes=100000-100200");
  7696. // `first_pos` is still -1 here, and the bounds asserts in
  7697. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7698. check(403, "bytes=-3");
  7699. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7700. // multipart branch would have written one that is empty.
  7701. check(403, "bytes=1-2, 4-5");
  7702. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7703. // covers the whole representation.
  7704. check(200, "bytes=3-5");
  7705. check(200, "bytes=1-2, 4-5");
  7706. }
  7707. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7708. auto res =
  7709. cli_.Get("/streamed-with-range",
  7710. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7711. "92233720368547758079223372036854775807"}});
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7714. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7715. EXPECT_EQ(false, res->has_header("Content-Range"));
  7716. EXPECT_EQ(0U, res->body.size());
  7717. }
  7718. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7719. auto res = cli_.Get(
  7720. "/with-range",
  7721. Headers{{"Range",
  7722. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7723. {"Accept-Encoding", ""}});
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7726. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7727. EXPECT_EQ(true, res->has_header("Content-Range"));
  7728. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7729. EXPECT_EQ(std::string("abcdefg"), res->body);
  7730. }
  7731. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7732. auto res = cli_.Get("/with-range", Headers{
  7733. {"Range", "bytes=0-"},
  7734. {"Accept-Encoding", ""},
  7735. });
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7738. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7739. EXPECT_EQ(true, res->has_header("Content-Range"));
  7740. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7741. EXPECT_EQ(std::string("abcdefg"), res->body);
  7742. }
  7743. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7744. auto res = cli_.Get("/streamed-with-range",
  7745. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7748. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7749. EXPECT_EQ(false, res->has_header("Content-Range"));
  7750. EXPECT_EQ(267U, res->body.size());
  7751. // Check that both range contents are present
  7752. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7753. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7754. // Check that Content-Range headers are present for both ranges
  7755. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7756. std::string::npos);
  7757. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7758. std::string::npos);
  7759. }
  7760. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7761. Ranges ranges;
  7762. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7763. ranges.emplace_back(0, -1);
  7764. }
  7765. auto res = cli_.Get("/streamed-with-range?error",
  7766. Headers{{make_range_header(ranges)}});
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7769. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7770. EXPECT_EQ(false, res->has_header("Content-Range"));
  7771. EXPECT_EQ(0U, res->body.size());
  7772. }
  7773. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7774. auto res = cli_.Get("/streamed-with-range",
  7775. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7778. EXPECT_EQ(5U, res->body.size());
  7779. // Check that overlapping ranges are coalesced into a single range
  7780. EXPECT_EQ("bcdef", res->body);
  7781. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7782. // Should be single range, not multipart
  7783. EXPECT_TRUE(res->has_header("Content-Range"));
  7784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7785. }
  7786. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7787. auto res = cli_.Get("/streamed-with-range",
  7788. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7791. EXPECT_EQ(268U, res->body.size());
  7792. // Check that both range contents are present
  7793. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7794. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7795. // Check that Content-Range headers are present for both ranges
  7796. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7797. std::string::npos);
  7798. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7799. std::string::npos);
  7800. }
  7801. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7802. auto res = cli_.Get("/streamed-with-range",
  7803. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7806. EXPECT_EQ(269U, res->body.size());
  7807. // Check that both duplicate range contents are present
  7808. size_t first_abc = res->body.find("abc\r\n");
  7809. EXPECT_TRUE(first_abc != std::string::npos);
  7810. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7811. EXPECT_TRUE(second_abc != std::string::npos);
  7812. // Check that Content-Range headers are present for both ranges
  7813. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7814. EXPECT_TRUE(first_range != std::string::npos);
  7815. size_t second_range =
  7816. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7817. EXPECT_TRUE(second_range != std::string::npos);
  7818. }
  7819. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7820. auto res =
  7821. cli_.Get("/streamed-with-range?error",
  7822. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7825. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7826. EXPECT_EQ(false, res->has_header("Content-Range"));
  7827. EXPECT_EQ(0U, res->body.size());
  7828. }
  7829. TEST_F(ServerTest, GetStreamedEndless) {
  7830. uint64_t offset = 0;
  7831. auto res = cli_.Get("/streamed-cancel",
  7832. [&](const char * /*data*/, uint64_t data_length) {
  7833. if (offset < 100) {
  7834. offset += data_length;
  7835. return true;
  7836. }
  7837. return false;
  7838. });
  7839. ASSERT_TRUE(!res);
  7840. EXPECT_EQ(Error::Canceled, res.error());
  7841. }
  7842. TEST_F(ServerTest, ClientStop) {
  7843. std::atomic_size_t count{4};
  7844. std::vector<std::thread> threads;
  7845. for (auto i = count.load(); i != 0; --i) {
  7846. threads.emplace_back([&]() {
  7847. auto res = cli_.Get("/streamed-cancel",
  7848. [&](const char *, uint64_t) { return true; });
  7849. --count;
  7850. ASSERT_TRUE(!res);
  7851. EXPECT_TRUE(res.error() == Error::Canceled ||
  7852. res.error() == Error::Read || res.error() == Error::Write);
  7853. });
  7854. }
  7855. std::this_thread::sleep_for(std::chrono::seconds(2));
  7856. while (count != 0) {
  7857. cli_.stop();
  7858. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7859. }
  7860. for (auto &t : threads) {
  7861. t.join();
  7862. }
  7863. }
  7864. TEST_F(ServerTest, GetWithRange1) {
  7865. auto res = cli_.Get("/with-range", Headers{
  7866. make_range_header({{3, 5}}),
  7867. {"Accept-Encoding", ""},
  7868. });
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7871. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7872. EXPECT_EQ(true, res->has_header("Content-Range"));
  7873. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7874. EXPECT_EQ(std::string("def"), res->body);
  7875. }
  7876. TEST_F(ServerTest, GetWithRange2) {
  7877. auto res = cli_.Get("/with-range", Headers{
  7878. make_range_header({{1, -1}}),
  7879. {"Accept-Encoding", ""},
  7880. });
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7883. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7884. EXPECT_EQ(true, res->has_header("Content-Range"));
  7885. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7886. EXPECT_EQ(std::string("bcdefg"), res->body);
  7887. }
  7888. TEST_F(ServerTest, GetWithRange3) {
  7889. auto res = cli_.Get("/with-range", Headers{
  7890. make_range_header({{0, 0}}),
  7891. {"Accept-Encoding", ""},
  7892. });
  7893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7895. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7896. EXPECT_EQ(true, res->has_header("Content-Range"));
  7897. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7898. EXPECT_EQ(std::string("a"), res->body);
  7899. }
  7900. TEST_F(ServerTest, GetWithRange4) {
  7901. auto res = cli_.Get("/with-range", Headers{
  7902. make_range_header({{-1, 2}}),
  7903. {"Accept-Encoding", ""},
  7904. });
  7905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7906. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7907. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7908. EXPECT_EQ(true, res->has_header("Content-Range"));
  7909. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7910. EXPECT_EQ(std::string("fg"), res->body);
  7911. }
  7912. TEST_F(ServerTest, GetWithRange5) {
  7913. auto res = cli_.Get("/with-range", Headers{
  7914. make_range_header({{0, 5}}),
  7915. {"Accept-Encoding", ""},
  7916. });
  7917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7919. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7920. EXPECT_EQ(true, res->has_header("Content-Range"));
  7921. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7922. EXPECT_EQ(std::string("abcdef"), res->body);
  7923. }
  7924. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7925. auto res =
  7926. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7929. }
  7930. TEST_F(ServerTest, GetWithRangeMultipart) {
  7931. auto res =
  7932. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7935. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7936. EXPECT_EQ(false, res->has_header("Content-Range"));
  7937. EXPECT_EQ(267U, res->body.size());
  7938. }
  7939. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7940. auto res = cli_.Get("/with-range",
  7941. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7944. }
  7945. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7946. auto res = cli_.Get("/with-range-customized-response",
  7947. Headers{{make_range_header({{1, 2}})}});
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7950. EXPECT_EQ(true, res->has_header("Content-Length"));
  7951. EXPECT_EQ(false, res->has_header("Content-Range"));
  7952. EXPECT_EQ(JSON_DATA, res->body);
  7953. }
  7954. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7955. auto res = cli_.Get("/with-range-customized-response",
  7956. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7959. EXPECT_EQ(true, res->has_header("Content-Length"));
  7960. EXPECT_EQ(false, res->has_header("Content-Range"));
  7961. EXPECT_EQ(JSON_DATA, res->body);
  7962. }
  7963. TEST_F(ServerTest, Issue1772) {
  7964. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7966. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7967. }
  7968. TEST_F(ServerTest, Issue609) {
  7969. auto res = cli_.Delete("/issue609");
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(StatusCode::OK_200, res->status);
  7972. EXPECT_EQ(std::string("ok"), res->body);
  7973. }
  7974. TEST_F(ServerTest, GetStreamedChunked) {
  7975. auto res = cli_.Get("/streamed-chunked");
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. EXPECT_EQ(std::string("123456789"), res->body);
  7979. }
  7980. TEST_F(ServerTest, GetStreamedChunked2) {
  7981. auto res = cli_.Get("/streamed-chunked2");
  7982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. EXPECT_EQ(std::string("123456789"), res->body);
  7985. }
  7986. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7987. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. EXPECT_EQ(std::string("123456789"), res->body);
  7991. EXPECT_TRUE(res->has_header("Trailer"));
  7992. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7993. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7994. // Trailers are now stored separately from headers (security fix)
  7995. EXPECT_EQ(2U, res->trailers.size());
  7996. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7997. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7998. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7999. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8000. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8001. // Verify trailers are NOT in headers (security verification)
  8002. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8003. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8004. }
  8005. TEST_F(ServerTest, LargeChunkedPost) {
  8006. Request req;
  8007. req.method = "POST";
  8008. req.path = "/large-chunked";
  8009. std::string host_and_port;
  8010. host_and_port += HOST;
  8011. host_and_port += ":";
  8012. host_and_port += std::to_string(PORT);
  8013. req.headers.emplace("Host", host_and_port.c_str());
  8014. req.headers.emplace("Accept", "*/*");
  8015. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8016. req.headers.emplace("Content-Type", "text/plain");
  8017. req.headers.emplace("Content-Length", "0");
  8018. req.headers.emplace("Transfer-Encoding", "chunked");
  8019. std::string long_string(30 * 1024u, 'a');
  8020. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8021. // Attempt to make a large enough post to exceed OS buffers, to test that
  8022. // the server handles short reads if the full chunk data isn't available.
  8023. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8024. auto res = std::make_shared<Response>();
  8025. auto error = Error::Success;
  8026. auto ret = cli_.send(req, *res, error);
  8027. ASSERT_TRUE(ret);
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. }
  8030. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8031. auto res = cli_.Get("/remote_addr");
  8032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8033. EXPECT_EQ(StatusCode::OK_200, res->status);
  8034. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8035. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8036. }
  8037. TEST_F(ServerTest, GetMethodLocalAddr) {
  8038. auto res = cli_.Get("/local_addr");
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8042. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8043. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8044. }
  8045. TEST_F(ServerTest, HTTPResponseSplitting) {
  8046. auto res = cli_.Get("/http_response_splitting");
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. }
  8050. TEST_F(ServerTest, SlowRequest) {
  8051. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8052. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8053. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8054. }
  8055. #if 0
  8056. TEST_F(ServerTest, SlowPost) {
  8057. char buffer[64 * 1024];
  8058. memset(buffer, 0x42, sizeof(buffer));
  8059. auto res = cli_.Post(
  8060. "/slowpost", 64 * 1024 * 1024,
  8061. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8062. auto ret = sink.write(buffer, sizeof(buffer));
  8063. EXPECT_TRUE(ret);
  8064. return true;
  8065. },
  8066. "text/plain");
  8067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8068. EXPECT_EQ(StatusCode::OK_200, res->status);
  8069. }
  8070. TEST_F(ServerTest, SlowPostFail) {
  8071. char buffer[64 * 1024];
  8072. memset(buffer, 0x42, sizeof(buffer));
  8073. cli_.set_write_timeout(std::chrono::seconds(0));
  8074. auto res = cli_.Post(
  8075. "/slowpost", 64 * 1024 * 1024,
  8076. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8077. sink.write(buffer, sizeof(buffer));
  8078. return true;
  8079. },
  8080. "text/plain");
  8081. ASSERT_TRUE(!res);
  8082. EXPECT_EQ(Error::Write, res.error());
  8083. }
  8084. #endif
  8085. TEST_F(ServerTest, Put) {
  8086. auto res = cli_.Put("/put", "PUT", "text/plain");
  8087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8088. EXPECT_EQ(StatusCode::OK_200, res->status);
  8089. EXPECT_EQ("PUT", res->body);
  8090. }
  8091. TEST_F(ServerTest, PutWithContentProvider) {
  8092. auto res = cli_.Put(
  8093. "/put", 3,
  8094. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8095. sink.os << "PUT";
  8096. return true;
  8097. },
  8098. "text/plain");
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ(StatusCode::OK_200, res->status);
  8101. EXPECT_EQ("PUT", res->body);
  8102. }
  8103. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8104. auto res = cli_.Post(
  8105. "/post", 42,
  8106. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8107. return false;
  8108. },
  8109. "text/plain");
  8110. ASSERT_TRUE(!res);
  8111. EXPECT_EQ(Error::Canceled, res.error());
  8112. }
  8113. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8114. auto res = cli_.Put(
  8115. "/put",
  8116. [](size_t /*offset*/, DataSink &sink) {
  8117. sink.os << "PUT";
  8118. sink.done();
  8119. return true;
  8120. },
  8121. "text/plain");
  8122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8123. EXPECT_EQ(StatusCode::OK_200, res->status);
  8124. EXPECT_EQ("PUT", res->body);
  8125. }
  8126. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8127. auto res = cli_.Post(
  8128. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8129. "text/plain");
  8130. ASSERT_TRUE(!res);
  8131. EXPECT_EQ(Error::Canceled, res.error());
  8132. }
  8133. TEST_F(ServerTest, PostLoopBack) {
  8134. std::string body;
  8135. auto res = cli_.Post(
  8136. "/post-loopback", 9,
  8137. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8138. EXPECT_EQ(9u, length);
  8139. sink.write("123", 3);
  8140. sink.write("456", 3);
  8141. sink.write("789", 3);
  8142. return true;
  8143. },
  8144. "text/plain",
  8145. [&body](const char *data, size_t data_length) {
  8146. body.append(data, data_length);
  8147. return true;
  8148. });
  8149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. EXPECT_EQ("123456789", body);
  8152. }
  8153. TEST_F(ServerTest, PutLoopBack) {
  8154. std::string body;
  8155. auto res = cli_.Put(
  8156. "/put-loopback", 9,
  8157. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8158. EXPECT_EQ(9u, length);
  8159. sink.write("123", 3);
  8160. sink.write("456", 3);
  8161. sink.write("789", 3);
  8162. return true;
  8163. },
  8164. "text/plain",
  8165. [&body](const char *data, size_t data_length) {
  8166. body.append(data, data_length);
  8167. return true;
  8168. });
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("123456789", body);
  8172. }
  8173. TEST_F(ServerTest, PatchLoopBack) {
  8174. std::string body;
  8175. auto res = cli_.Patch(
  8176. "/patch-loopback", 9,
  8177. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8178. EXPECT_EQ(9u, length);
  8179. sink.write("123", 3);
  8180. sink.write("456", 3);
  8181. sink.write("789", 3);
  8182. return true;
  8183. },
  8184. "text/plain",
  8185. [&body](const char *data, size_t data_length) {
  8186. body.append(data, data_length);
  8187. return true;
  8188. });
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("123456789", body);
  8192. }
  8193. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8194. std::string body;
  8195. auto res = cli_.Post(
  8196. "/post-loopback",
  8197. [](size_t /*offset*/, DataSink &sink) {
  8198. sink.write("123", 3);
  8199. sink.write("456", 3);
  8200. sink.write("789", 3);
  8201. sink.done();
  8202. return true;
  8203. },
  8204. "text/plain",
  8205. [&body](const char *data, size_t data_length) {
  8206. body.append(data, data_length);
  8207. return true;
  8208. });
  8209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8210. EXPECT_EQ(StatusCode::OK_200, res->status);
  8211. EXPECT_EQ("123456789", body);
  8212. }
  8213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8214. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8215. cli_.set_compress(true);
  8216. auto res = cli_.Put(
  8217. "/put", 3,
  8218. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8219. sink.os << "PUT";
  8220. return true;
  8221. },
  8222. "text/plain");
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("PUT", res->body);
  8226. }
  8227. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8228. cli_.set_compress(true);
  8229. auto res = cli_.Post(
  8230. "/post", 42,
  8231. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8232. return false;
  8233. },
  8234. "text/plain");
  8235. ASSERT_TRUE(!res);
  8236. EXPECT_EQ(Error::Canceled, res.error());
  8237. }
  8238. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8239. cli_.set_compress(true);
  8240. auto res = cli_.Put(
  8241. "/put",
  8242. [](size_t /*offset*/, DataSink &sink) {
  8243. sink.os << "PUT";
  8244. sink.done();
  8245. return true;
  8246. },
  8247. "text/plain");
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ("PUT", res->body);
  8251. }
  8252. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8253. cli_.set_compress(true);
  8254. auto res = cli_.Post(
  8255. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8256. "text/plain");
  8257. ASSERT_TRUE(!res);
  8258. EXPECT_EQ(Error::Canceled, res.error());
  8259. }
  8260. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8261. cli_.set_compress(true);
  8262. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8264. EXPECT_EQ(StatusCode::OK_200, res->status);
  8265. EXPECT_EQ(LARGE_DATA, res->body);
  8266. }
  8267. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8268. #ifdef CPPHTTPLIB_SSL_ENABLED
  8269. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8270. Client cli(s.c_str());
  8271. cli.enable_server_certificate_verification(false);
  8272. #else
  8273. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8274. Client cli(s.c_str());
  8275. #endif
  8276. cli.set_compress(true);
  8277. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::OK_200, res->status);
  8280. EXPECT_EQ(LARGE_DATA, res->body);
  8281. // The compressed size should be less than a 10th of the original. May vary
  8282. // depending on the zlib library.
  8283. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8284. static_cast<uint64_t>(10 * 1024 * 1024));
  8285. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8286. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8287. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8288. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8289. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8290. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8291. #endif
  8292. }
  8293. TEST_F(ServerTest, PutContentWithDeflate) {
  8294. cli_.set_compress(false);
  8295. Headers headers;
  8296. headers.emplace("Content-Encoding", "deflate");
  8297. // PUT in deflate format:
  8298. auto res = cli_.Put("/put", headers,
  8299. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. EXPECT_EQ("PUT", res->body);
  8303. }
  8304. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8305. Headers headers;
  8306. headers.emplace("Accept-Encoding", "gzip, deflate");
  8307. auto res = cli_.Get("/streamed-chunked", headers);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::OK_200, res->status);
  8310. EXPECT_EQ(std::string("123456789"), res->body);
  8311. }
  8312. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8313. Headers headers;
  8314. headers.emplace("Accept-Encoding", "gzip, deflate");
  8315. auto res = cli_.Get("/streamed-chunked2", headers);
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_EQ(std::string("123456789"), res->body);
  8319. }
  8320. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8321. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8323. EXPECT_EQ(StatusCode::OK_200, res->status);
  8324. }
  8325. TEST(GzipDecompressor, ChunkedDecompression) {
  8326. std::string data;
  8327. for (size_t i = 0; i < 32 * 1024; ++i) {
  8328. data.push_back(static_cast<char>('a' + i % 26));
  8329. }
  8330. std::string compressed_data;
  8331. {
  8332. httplib::detail::gzip_compressor compressor;
  8333. bool result = compressor.compress(
  8334. data.data(), data.size(),
  8335. /*last=*/true,
  8336. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8337. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8338. compressed_data_size);
  8339. return true;
  8340. });
  8341. ASSERT_TRUE(result);
  8342. }
  8343. std::string decompressed_data;
  8344. {
  8345. httplib::detail::gzip_decompressor decompressor;
  8346. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8347. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8348. size_t chunk_size = 130;
  8349. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8350. chunk_begin += chunk_size) {
  8351. size_t current_chunk_size =
  8352. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8353. bool result = decompressor.decompress(
  8354. compressed_data.data() + chunk_begin, current_chunk_size,
  8355. [&](const char *decompressed_data_chunk,
  8356. size_t decompressed_data_chunk_size) {
  8357. decompressed_data.insert(decompressed_data.size(),
  8358. decompressed_data_chunk,
  8359. decompressed_data_chunk_size);
  8360. return true;
  8361. });
  8362. ASSERT_TRUE(result);
  8363. }
  8364. }
  8365. ASSERT_EQ(data, decompressed_data);
  8366. }
  8367. TEST(GzipDecompressor, DeflateDecompression) {
  8368. std::string original_text = "Raw deflate without gzip";
  8369. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8370. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8371. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8372. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8373. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8374. std::string decompressed_data;
  8375. {
  8376. httplib::detail::gzip_decompressor decompressor;
  8377. bool result = decompressor.decompress(
  8378. compressed_data.data(), compressed_data.size(),
  8379. [&](const char *decompressed_data_chunk,
  8380. size_t decompressed_data_chunk_size) {
  8381. decompressed_data.insert(decompressed_data.size(),
  8382. decompressed_data_chunk,
  8383. decompressed_data_chunk_size);
  8384. return true;
  8385. });
  8386. ASSERT_TRUE(result);
  8387. }
  8388. ASSERT_EQ(original_text, decompressed_data);
  8389. }
  8390. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8391. std::string original_text = "Raw deflate without gzip";
  8392. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8393. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8394. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8395. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8396. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8397. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8398. std::string decompressed_data;
  8399. {
  8400. httplib::detail::gzip_decompressor decompressor;
  8401. bool result = decompressor.decompress(
  8402. compressed_data.data(), compressed_data.size(),
  8403. [&](const char *decompressed_data_chunk,
  8404. size_t decompressed_data_chunk_size) {
  8405. decompressed_data.insert(decompressed_data.size(),
  8406. decompressed_data_chunk,
  8407. decompressed_data_chunk_size);
  8408. return true;
  8409. });
  8410. ASSERT_TRUE(result);
  8411. }
  8412. ASSERT_EQ(original_text, decompressed_data);
  8413. }
  8414. #endif
  8415. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8416. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "br");
  8419. auto res = cli_.Get("/streamed-chunked", headers);
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. EXPECT_EQ(std::string("123456789"), res->body);
  8423. }
  8424. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "br");
  8427. auto res = cli_.Get("/streamed-chunked2", headers);
  8428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8429. EXPECT_EQ(StatusCode::OK_200, res->status);
  8430. EXPECT_EQ(std::string("123456789"), res->body);
  8431. }
  8432. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8433. cli_.set_compress(true);
  8434. auto res = cli_.Put(
  8435. "/put", 3,
  8436. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8437. sink.os << "PUT";
  8438. return true;
  8439. },
  8440. "text/plain");
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. EXPECT_EQ("PUT", res->body);
  8444. }
  8445. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8446. cli_.set_compress(true);
  8447. auto res = cli_.Put(
  8448. "/put",
  8449. [](size_t /*offset*/, DataSink &sink) {
  8450. sink.os << "PUT";
  8451. sink.done();
  8452. return true;
  8453. },
  8454. "text/plain");
  8455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8456. EXPECT_EQ(StatusCode::OK_200, res->status);
  8457. EXPECT_EQ("PUT", res->body);
  8458. }
  8459. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8460. cli_.set_compress(true);
  8461. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::OK_200, res->status);
  8464. EXPECT_EQ(LARGE_DATA, res->body);
  8465. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8466. }
  8467. #endif
  8468. TEST_F(ServerTest, Patch) {
  8469. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_EQ(StatusCode::OK_200, res->status);
  8472. EXPECT_EQ("PATCH", res->body);
  8473. }
  8474. TEST_F(ServerTest, Delete) {
  8475. auto res = cli_.Delete("/delete");
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. EXPECT_EQ("DELETE", res->body);
  8479. }
  8480. TEST_F(ServerTest, DeleteContentReceiver) {
  8481. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8483. EXPECT_EQ(StatusCode::OK_200, res->status);
  8484. EXPECT_EQ("content", res->body);
  8485. }
  8486. TEST_F(ServerTest, Options) {
  8487. auto res = cli_.Options("*");
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ(StatusCode::OK_200, res->status);
  8490. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8491. EXPECT_TRUE(res->body.empty());
  8492. }
  8493. TEST_F(ServerTest, URL) {
  8494. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8496. EXPECT_EQ(StatusCode::OK_200, res->status);
  8497. }
  8498. TEST_F(ServerTest, ArrayParam) {
  8499. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8501. EXPECT_EQ(StatusCode::OK_200, res->status);
  8502. }
  8503. TEST_F(ServerTest, ArrayParamValues) {
  8504. auto res =
  8505. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::OK_200, res->status);
  8508. }
  8509. TEST_F(ServerTest, NoMultipleHeaders) {
  8510. Headers headers = {{"Content-Length", "5"}};
  8511. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8512. "text/plain");
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(ServerTest, PostContentReceiver) {
  8517. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. ASSERT_EQ(StatusCode::OK_200, res->status);
  8520. ASSERT_EQ("content", res->body);
  8521. }
  8522. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8523. UploadFormDataItems items = {
  8524. {"text1", "text default", "", ""},
  8525. {"text2", "aωb", "", ""},
  8526. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8527. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8528. {"file3", "", "", "application/octet-stream"},
  8529. };
  8530. auto res = cli_.Post("/content_receiver", items);
  8531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8532. EXPECT_EQ(StatusCode::OK_200, res->status);
  8533. }
  8534. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8535. UploadFormDataItems items = {
  8536. {"text1", "text default", "", ""},
  8537. {"text2", "aωb", "", ""},
  8538. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8539. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8540. {"file3", "", "", "application/octet-stream"},
  8541. };
  8542. auto boundary = std::string("+++++");
  8543. std::string body;
  8544. for (const auto &item : items) {
  8545. body += "--" + boundary + "\r\n";
  8546. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8547. if (!item.filename.empty()) {
  8548. body += "; filename=\"" + item.filename + "\"";
  8549. }
  8550. body += "\r\n";
  8551. if (!item.content_type.empty()) {
  8552. body += "Content-Type: " + item.content_type + "\r\n";
  8553. }
  8554. body += "\r\n";
  8555. body += item.content + "\r\n";
  8556. }
  8557. body += "--" + boundary + "--\r\n";
  8558. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8559. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8561. EXPECT_EQ(StatusCode::OK_200, res->status);
  8562. }
  8563. TEST(MultipartFormDataTest, FieldEscaping) {
  8564. Server svr;
  8565. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8566. const ContentReader &content_reader) {
  8567. ASSERT_TRUE(req.is_multipart_form_data());
  8568. std::vector<FormData> received;
  8569. content_reader(
  8570. [&](const FormData &file) {
  8571. received.push_back(file);
  8572. return true;
  8573. },
  8574. [&](const char *data, size_t data_length) {
  8575. received.back().content.append(data, data_length);
  8576. return true;
  8577. });
  8578. // '"', CR and LF in names and filenames are escaped following the
  8579. // WHATWG HTML standard, so each part still parses as a single part
  8580. // with no injected headers. Content types get CR/LF escaped too,
  8581. // while '"' (legal there, e.g. quoted charset) is preserved.
  8582. ASSERT_EQ(4U, received.size());
  8583. EXPECT_EQ("na%22me", received[0].name);
  8584. EXPECT_EQ("quoted name", received[0].content);
  8585. EXPECT_EQ("file", received[1].name);
  8586. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8587. received[1].filename);
  8588. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8589. EXPECT_EQ("injected", received[1].content);
  8590. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8591. EXPECT_EQ("my%22file.txt", received[2].filename);
  8592. EXPECT_EQ("cr lf name", received[2].content);
  8593. EXPECT_EQ("typed", received[3].name);
  8594. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8595. received[3].content_type);
  8596. EXPECT_EQ("typed content", received[3].content);
  8597. });
  8598. auto port = svr.bind_to_any_port("localhost");
  8599. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8600. auto se = detail::scope_exit([&] {
  8601. svr.stop();
  8602. t.join();
  8603. ASSERT_FALSE(svr.is_running());
  8604. });
  8605. svr.wait_until_ready();
  8606. Client cli("localhost", port);
  8607. UploadFormDataItems items = {
  8608. {"na\"me", "quoted name", "", ""},
  8609. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8610. "application/octet-stream"},
  8611. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8612. {"typed", "typed content", "",
  8613. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8614. };
  8615. auto res = cli.Post("/post", items);
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::OK_200, res->status);
  8618. }
  8619. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8620. const UploadFormDataItems items = {
  8621. {"name1", "Content 1", "", ""},
  8622. {"name2", "Content 2", "file2.txt", "text/plain"},
  8623. };
  8624. Server svr;
  8625. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8626. const ContentReader &content_reader) {
  8627. ASSERT_TRUE(req.is_multipart_form_data());
  8628. std::vector<FormData> received;
  8629. content_reader(
  8630. [&](const FormData &file) {
  8631. received.push_back(file);
  8632. return true;
  8633. },
  8634. [&](const char *data, size_t data_length) {
  8635. received.back().content.append(data, data_length);
  8636. return true;
  8637. });
  8638. ASSERT_EQ(2U, received.size());
  8639. EXPECT_EQ("name1", received[0].name);
  8640. EXPECT_EQ("Content 1", received[0].content);
  8641. EXPECT_EQ("name2", received[1].name);
  8642. EXPECT_EQ("Content 2", received[1].content);
  8643. EXPECT_EQ("file2.txt", received[1].filename);
  8644. EXPECT_EQ("text/plain", received[1].content_type);
  8645. });
  8646. auto port = svr.bind_to_any_port("localhost");
  8647. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8648. auto se = detail::scope_exit([&] {
  8649. svr.stop();
  8650. t.join();
  8651. ASSERT_FALSE(svr.is_running());
  8652. });
  8653. svr.wait_until_ready();
  8654. Client cli("localhost", port);
  8655. // Whole-body serialization with a generated boundary
  8656. {
  8657. MultipartFormDataWriter writer;
  8658. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8659. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8660. writer.content_type());
  8661. auto body = writer.serialize(items);
  8662. EXPECT_EQ(body.size(), writer.content_length(items));
  8663. auto res = cli.Post("/post", body, writer.content_type());
  8664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8665. EXPECT_EQ(StatusCode::OK_200, res->status);
  8666. }
  8667. // Per-part framing with a custom boundary via a content provider
  8668. {
  8669. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8670. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8671. MultipartFormDataWriter writer("custom-boundary_123");
  8672. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8673. std::string body;
  8674. for (const auto &item : items) {
  8675. body += writer.item_begin(item);
  8676. body += item.content;
  8677. body += MultipartFormDataWriter::item_end();
  8678. }
  8679. body += writer.finish();
  8680. EXPECT_EQ(body.size(), writer.content_length(items));
  8681. auto res = cli.Post(
  8682. "/post", body.size(),
  8683. [&](size_t offset, size_t length, DataSink &sink) {
  8684. sink.write(body.data() + offset, length);
  8685. return true;
  8686. },
  8687. writer.content_type());
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. }
  8691. }
  8692. TEST_F(ServerTest, PostContentReceiverGzip) {
  8693. cli_.set_compress(true);
  8694. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8696. ASSERT_EQ(StatusCode::OK_200, res->status);
  8697. ASSERT_EQ("content", res->body);
  8698. }
  8699. TEST_F(ServerTest, PutContentReceiver) {
  8700. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8702. ASSERT_EQ(StatusCode::OK_200, res->status);
  8703. ASSERT_EQ("content", res->body);
  8704. }
  8705. TEST_F(ServerTest, PatchContentReceiver) {
  8706. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8708. ASSERT_EQ(StatusCode::OK_200, res->status);
  8709. ASSERT_EQ("content", res->body);
  8710. }
  8711. template <typename ClientType>
  8712. void TestWithHeadersAndContentReceiver(
  8713. ClientType &cli,
  8714. std::function<Result(ClientType &, const std::string &, const Headers &,
  8715. const std::string &, const std::string &,
  8716. ContentReceiver, DownloadProgress)>
  8717. request_func) {
  8718. Headers headers;
  8719. headers.emplace("X-Custom-Header", "test-value");
  8720. std::string received_body;
  8721. auto res = request_func(
  8722. cli, "/content_receiver", headers, "content", "application/json",
  8723. [&](const char *data, size_t data_length) {
  8724. received_body.append(data, data_length);
  8725. return true;
  8726. },
  8727. nullptr);
  8728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8729. EXPECT_EQ(StatusCode::OK_200, res->status);
  8730. EXPECT_EQ("content", received_body);
  8731. }
  8732. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8733. #ifdef CPPHTTPLIB_SSL_ENABLED
  8734. using ClientT = SSLClient;
  8735. #else
  8736. using ClientT = Client;
  8737. #endif
  8738. TestWithHeadersAndContentReceiver<ClientT>(
  8739. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8740. const std::string &body, const std::string &content_type,
  8741. ContentReceiver receiver, DownloadProgress progress) {
  8742. return cli.Post(path, headers, body, content_type, receiver, progress);
  8743. });
  8744. }
  8745. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8746. #ifdef CPPHTTPLIB_SSL_ENABLED
  8747. using ClientT = SSLClient;
  8748. #else
  8749. using ClientT = Client;
  8750. #endif
  8751. TestWithHeadersAndContentReceiver<ClientT>(
  8752. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8753. const std::string &body, const std::string &content_type,
  8754. ContentReceiver receiver, DownloadProgress progress) {
  8755. return cli.Put(path, headers, body, content_type, receiver, progress);
  8756. });
  8757. }
  8758. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8759. #ifdef CPPHTTPLIB_SSL_ENABLED
  8760. using ClientT = SSLClient;
  8761. #else
  8762. using ClientT = Client;
  8763. #endif
  8764. TestWithHeadersAndContentReceiver<ClientT>(
  8765. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8766. const std::string &body, const std::string &content_type,
  8767. ContentReceiver receiver, DownloadProgress progress) {
  8768. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8769. });
  8770. }
  8771. template <typename ClientType>
  8772. void TestWithHeadersAndContentReceiverWithProgress(
  8773. ClientType &cli,
  8774. std::function<Result(ClientType &, const std::string &, const Headers &,
  8775. const std::string &, const std::string &,
  8776. ContentReceiver, DownloadProgress)>
  8777. request_func) {
  8778. Headers headers;
  8779. headers.emplace("X-Test-Header", "progress-test");
  8780. std::string received_body;
  8781. auto progress_called = false;
  8782. auto res = request_func(
  8783. cli, "/content_receiver", headers, "content", "text/plain",
  8784. [&](const char *data, size_t data_length) {
  8785. received_body.append(data, data_length);
  8786. return true;
  8787. },
  8788. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8789. progress_called = true;
  8790. return true;
  8791. });
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. EXPECT_EQ("content", received_body);
  8795. EXPECT_TRUE(progress_called);
  8796. }
  8797. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8798. #ifdef CPPHTTPLIB_SSL_ENABLED
  8799. using ClientT = SSLClient;
  8800. #else
  8801. using ClientT = Client;
  8802. #endif
  8803. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8804. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8805. const std::string &body, const std::string &content_type,
  8806. ContentReceiver receiver, DownloadProgress progress) {
  8807. return cli.Post(path, headers, body, content_type, receiver, progress);
  8808. });
  8809. }
  8810. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8811. #ifdef CPPHTTPLIB_SSL_ENABLED
  8812. using ClientT = SSLClient;
  8813. #else
  8814. using ClientT = Client;
  8815. #endif
  8816. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8817. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8818. const std::string &body, const std::string &content_type,
  8819. ContentReceiver receiver, DownloadProgress progress) {
  8820. return cli.Put(path, headers, body, content_type, receiver, progress);
  8821. });
  8822. }
  8823. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8824. #ifdef CPPHTTPLIB_SSL_ENABLED
  8825. using ClientT = SSLClient;
  8826. #else
  8827. using ClientT = Client;
  8828. #endif
  8829. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8830. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8831. const std::string &body, const std::string &content_type,
  8832. ContentReceiver receiver, DownloadProgress progress) {
  8833. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8834. });
  8835. }
  8836. template <typename ClientType>
  8837. void TestWithHeadersAndContentReceiverError(
  8838. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8839. const Headers &, const std::string &,
  8840. const std::string &, ContentReceiver)>
  8841. request_func) {
  8842. Headers headers;
  8843. headers.emplace("X-Error-Test", "true");
  8844. std::string received_body;
  8845. auto receiver_failed = false;
  8846. auto res =
  8847. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8848. [&](const char *data, size_t data_length) {
  8849. received_body.append(data, data_length);
  8850. receiver_failed = true;
  8851. return false;
  8852. });
  8853. ASSERT_FALSE(res);
  8854. EXPECT_TRUE(receiver_failed);
  8855. }
  8856. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8857. #ifdef CPPHTTPLIB_SSL_ENABLED
  8858. using ClientT = SSLClient;
  8859. #else
  8860. using ClientT = Client;
  8861. #endif
  8862. TestWithHeadersAndContentReceiverError<ClientT>(
  8863. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8864. const std::string &body, const std::string &content_type,
  8865. ContentReceiver receiver) {
  8866. return cli.Post(path, headers, body, content_type, receiver);
  8867. });
  8868. }
  8869. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8870. #ifdef CPPHTTPLIB_SSL_ENABLED
  8871. using ClientT = SSLClient;
  8872. #else
  8873. using ClientT = Client;
  8874. #endif
  8875. TestWithHeadersAndContentReceiverError<ClientT>(
  8876. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8877. const std::string &body, const std::string &content_type,
  8878. ContentReceiver receiver) {
  8879. return cli.Put(path, headers, body, content_type, receiver);
  8880. });
  8881. }
  8882. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8883. #ifdef CPPHTTPLIB_SSL_ENABLED
  8884. using ClientT = SSLClient;
  8885. #else
  8886. using ClientT = Client;
  8887. #endif
  8888. TestWithHeadersAndContentReceiverError<ClientT>(
  8889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8890. const std::string &body, const std::string &content_type,
  8891. ContentReceiver receiver) {
  8892. return cli.Patch(path, headers, body, content_type, receiver);
  8893. });
  8894. }
  8895. TEST_F(ServerTest, PostQueryStringAndBody) {
  8896. auto res =
  8897. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. ASSERT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, HTTP2Magic) {
  8902. Request req;
  8903. req.method = "PRI";
  8904. req.path = "*";
  8905. req.body = "SM";
  8906. auto res = std::make_shared<Response>();
  8907. auto error = Error::Success;
  8908. auto ret = cli_.send(req, *res, error);
  8909. ASSERT_TRUE(ret);
  8910. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8911. }
  8912. TEST_F(ServerTest, KeepAlive) {
  8913. auto res = cli_.Get("/hi");
  8914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8917. EXPECT_EQ("Hello World!", res->body);
  8918. res = cli_.Get("/hi");
  8919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8920. EXPECT_EQ(StatusCode::OK_200, res->status);
  8921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8922. EXPECT_EQ("Hello World!", res->body);
  8923. res = cli_.Get("/hi");
  8924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8925. EXPECT_EQ(StatusCode::OK_200, res->status);
  8926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8927. EXPECT_EQ("Hello World!", res->body);
  8928. res = cli_.Get("/not-exist");
  8929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8931. res = cli_.Post("/empty", "", "text/plain");
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8935. EXPECT_EQ("empty", res->body);
  8936. EXPECT_EQ("close", res->get_header_value("Connection"));
  8937. res = cli_.Post(
  8938. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8939. "text/plain");
  8940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8941. EXPECT_EQ(StatusCode::OK_200, res->status);
  8942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8943. EXPECT_EQ("empty", res->body);
  8944. cli_.set_keep_alive(false);
  8945. res = cli_.Get("/last-request");
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::OK_200, res->status);
  8948. EXPECT_EQ("close", res->get_header_value("Connection"));
  8949. }
  8950. TEST_F(ServerTest, TooManyRedirect) {
  8951. cli_.set_follow_location(true);
  8952. auto res = cli_.Get("/redirect/0");
  8953. ASSERT_TRUE(!res);
  8954. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8955. }
  8956. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8957. Request req;
  8958. req.method = "FOOBAR";
  8959. req.path = "/hi";
  8960. cli_.set_keep_alive(true);
  8961. auto res = cli_.send(req);
  8962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8963. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8964. EXPECT_EQ("close", res->get_header_value("Connection"));
  8965. EXPECT_FALSE(cli_.is_socket_open());
  8966. }
  8967. TEST_F(ServerTest, CustomRouteReadsBody) {
  8968. const std::string xml =
  8969. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8970. Request req;
  8971. req.method = "PROPFIND";
  8972. req.path = "/dav/dir";
  8973. req.set_header("Depth", "1");
  8974. req.body = xml;
  8975. auto res = cli_.send(req);
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8978. EXPECT_EQ(xml, res->body);
  8979. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8980. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8981. }
  8982. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8983. Request req;
  8984. req.method = "PROPFIND";
  8985. req.path = "/dav/42";
  8986. auto res = cli_.send(req);
  8987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8988. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8989. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8990. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8991. }
  8992. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8993. Request req;
  8994. req.method = "PROPFIND";
  8995. req.path = "/dav-re/123";
  8996. auto res = cli_.send(req);
  8997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8998. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8999. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9000. }
  9001. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9002. Request req;
  9003. req.method = "MKCOL";
  9004. req.path = "/dav-mkcol";
  9005. auto res = cli_.send(req);
  9006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9007. EXPECT_EQ(StatusCode::Created_201, res->status);
  9008. }
  9009. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9010. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9011. Request req;
  9012. req.method = "REPORT";
  9013. req.path = "/dav-report";
  9014. req.body = xml;
  9015. auto res = cli_.send(req);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9018. EXPECT_EQ(xml, res->body);
  9019. }
  9020. // A content reader route must fire even when the request carries no body,
  9021. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9022. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9023. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9024. Request req;
  9025. req.method = "REPORT";
  9026. req.path = "/dav-report";
  9027. auto res = cli_.send(req);
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9030. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9031. }
  9032. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9033. Request req;
  9034. req.method = "PROPFIND";
  9035. req.path = "/not-dav";
  9036. auto res = cli_.send(req);
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9039. }
  9040. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9041. Request req;
  9042. req.method = "UNLOCK";
  9043. req.path = "/dav/dir";
  9044. cli_.set_keep_alive(true);
  9045. auto res = cli_.send(req);
  9046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9047. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9048. EXPECT_EQ("close", res->get_header_value("Connection"));
  9049. EXPECT_FALSE(cli_.is_socket_open());
  9050. }
  9051. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9052. // The mount point serves this path, but only for GET and HEAD.
  9053. auto get_res = cli_.Get("/dir/index.html");
  9054. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9055. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9056. Request req;
  9057. req.method = "PROPFIND";
  9058. req.path = "/dir/index.html";
  9059. auto res = cli_.send(req);
  9060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9061. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9062. }
  9063. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9064. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9065. cli_.set_keep_alive(true);
  9066. for (auto i = 0; i < 2; i++) {
  9067. Request req;
  9068. req.method = "PROPFIND";
  9069. req.path = "/dav/dir";
  9070. req.body = xml;
  9071. auto res = cli_.send(req);
  9072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9073. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9074. EXPECT_EQ(xml, res->body);
  9075. EXPECT_TRUE(cli_.is_socket_open());
  9076. }
  9077. // A built-in method must still be served on the same connection.
  9078. cli_.set_keep_alive(false);
  9079. auto res = cli_.Get("/hi");
  9080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9081. EXPECT_EQ(StatusCode::OK_200, res->status);
  9082. EXPECT_EQ("close", res->get_header_value("Connection"));
  9083. }
  9084. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9085. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9086. Request req;
  9087. req.method = "PROPFIND";
  9088. req.path = "/dav/dir";
  9089. req.set_header("Expect", "100-continue");
  9090. req.body = xml;
  9091. auto res = cli_.send(req);
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9094. EXPECT_EQ(xml, res->body);
  9095. }
  9096. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9097. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9098. TEST_F(ServerTest, Gzip) {
  9099. Headers headers;
  9100. headers.emplace("Accept-Encoding", "gzip, deflate");
  9101. auto res = cli_.Get("/compress", headers);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9105. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9107. "7890123456789012345678901234567890",
  9108. res->body);
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. }
  9111. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9112. Headers headers;
  9113. headers.emplace("Accept-Encoding", "gzip, deflate");
  9114. auto res = cli_.Get("/compress-with-charset", headers);
  9115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9116. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9117. EXPECT_EQ("application/json; charset=utf-8",
  9118. res->get_header_value("Content-Type"));
  9119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9120. "7890123456789012345678901234567890",
  9121. res->body);
  9122. EXPECT_EQ(StatusCode::OK_200, res->status);
  9123. }
  9124. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9125. Headers headers;
  9126. headers.emplace("Accept-Encoding", "");
  9127. auto res = cli_.Get("/compress", headers);
  9128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9129. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9130. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9133. "7890123456789012345678901234567890",
  9134. res->body);
  9135. EXPECT_EQ(StatusCode::OK_200, res->status);
  9136. }
  9137. TEST_F(ServerTest, GzipWithContentReceiver) {
  9138. Headers headers;
  9139. headers.emplace("Accept-Encoding", "gzip, deflate");
  9140. std::string body;
  9141. auto res =
  9142. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9143. EXPECT_EQ(100U, data_length);
  9144. body.append(data, data_length);
  9145. return true;
  9146. });
  9147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9148. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9150. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9152. "7890123456789012345678901234567890",
  9153. body);
  9154. EXPECT_EQ(StatusCode::OK_200, res->status);
  9155. }
  9156. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9157. Headers headers;
  9158. headers.emplace("Accept-Encoding", "gzip, deflate");
  9159. cli_.set_decompress(false);
  9160. auto res = cli_.Get("/compress", headers);
  9161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9162. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9163. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9164. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9165. EXPECT_EQ(33U, res->body.size());
  9166. EXPECT_EQ(StatusCode::OK_200, res->status);
  9167. }
  9168. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9169. Headers headers;
  9170. headers.emplace("Accept-Encoding", "");
  9171. std::string body;
  9172. auto res =
  9173. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9174. EXPECT_EQ(100U, data_length);
  9175. body.append(data, data_length);
  9176. return true;
  9177. });
  9178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9179. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9180. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9181. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9182. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9183. "7890123456789012345678901234567890",
  9184. body);
  9185. EXPECT_EQ(StatusCode::OK_200, res->status);
  9186. }
  9187. TEST_F(ServerTest, NoGzip) {
  9188. Headers headers;
  9189. headers.emplace("Accept-Encoding", "gzip, deflate");
  9190. auto res = cli_.Get("/nocompress", headers);
  9191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9192. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9193. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9194. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9196. "7890123456789012345678901234567890",
  9197. res->body);
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9201. Headers headers;
  9202. headers.emplace("Accept-Encoding", "gzip, deflate");
  9203. std::string body;
  9204. auto res = cli_.Get("/nocompress", headers,
  9205. [&](const char *data, size_t data_length) {
  9206. EXPECT_EQ(100U, data_length);
  9207. body.append(data, data_length);
  9208. return true;
  9209. });
  9210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9211. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9212. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9213. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9214. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9215. "7890123456789012345678901234567890",
  9216. body);
  9217. EXPECT_EQ(StatusCode::OK_200, res->status);
  9218. }
  9219. TEST_F(ServerTest, MultipartFormDataGzip) {
  9220. UploadFormDataItems items = {
  9221. {"key1", "test", "", ""},
  9222. {"key2", "--abcdefg123", "", ""},
  9223. };
  9224. cli_.set_compress(true);
  9225. auto res = cli_.Post("/compress-multipart", items);
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. EXPECT_EQ(StatusCode::OK_200, res->status);
  9228. }
  9229. #endif
  9230. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9231. // Static file compression is opt-in, so these run their own server rather than
  9232. // flipping it on for the shared ServerTest fixture, which would silently
  9233. // rewrite what every other static file test is asserting.
  9234. class StaticFileCompressionTest : public ::testing::Test {
  9235. protected:
  9236. void TearDown() override {
  9237. if (t_.joinable()) {
  9238. svr_.stop();
  9239. t_.join();
  9240. }
  9241. }
  9242. int start(const std::function<void(Server &)> &configure = nullptr) {
  9243. // Serves the same tree as a directory of build-time compressed assets
  9244. // would be served: the mount point names the coding the files are already
  9245. // stored in. Registered before "/" so it is the one that matches.
  9246. svr_.set_mount_point("/pre-encoded", "./www",
  9247. {{"Content-Encoding", "gzip"}});
  9248. svr_.set_mount_point("/", "./www");
  9249. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9250. res.set_file_content("./www/dir/index.html", "text/html");
  9251. });
  9252. svr_.Get("/pre-encoded-file-content",
  9253. [](const Request & /*req*/, Response &res) {
  9254. res.set_header("Content-Encoding", "gzip");
  9255. res.set_file_content("./www/dir/index.html", "text/html");
  9256. });
  9257. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9258. res.set_content_provider(
  9259. 6, "text/plain",
  9260. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9261. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9262. return true;
  9263. });
  9264. });
  9265. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9266. res.set_content_provider(
  9267. 1000, "text/plain",
  9268. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9269. if (offset < 100) {
  9270. std::string data(100, 'A');
  9271. sink.write(data.data(), data.size());
  9272. return true;
  9273. }
  9274. std::this_thread::sleep_for(std::chrono::seconds(2));
  9275. std::string data(900, 'B');
  9276. sink.write(data.data(), data.size());
  9277. return true;
  9278. });
  9279. });
  9280. if (configure) { configure(svr_); }
  9281. auto port = svr_.bind_to_any_port(HOST);
  9282. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9283. svr_.wait_until_ready();
  9284. return port;
  9285. }
  9286. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9287. // Every file under ./www except 1MB.txt is smaller than the default
  9288. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9289. // it out of the way.
  9290. static void enable_without_floor(Server &svr) {
  9291. svr.set_static_file_compression(true);
  9292. svr.set_static_file_compression_min_length(0);
  9293. }
  9294. Server svr_;
  9295. std::thread t_;
  9296. };
  9297. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9298. auto port = start();
  9299. Client cli(HOST, port);
  9300. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9302. EXPECT_EQ(StatusCode::OK_200, res->status);
  9303. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9304. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9305. EXPECT_EQ(1048576U, res->body.size());
  9306. }
  9307. TEST_F(StaticFileCompressionTest, MountPoint) {
  9308. auto port = start(enable);
  9309. Client cli(HOST, port);
  9310. cli.set_decompress(false);
  9311. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9313. EXPECT_EQ(StatusCode::OK_200, res->status);
  9314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9315. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9316. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9317. // The response stays self-delimiting: a length, not a chunked body.
  9318. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9319. EXPECT_EQ(std::to_string(res->body.size()),
  9320. res->get_header_value("Content-Length"));
  9321. EXPECT_LT(res->body.size(), 1048576U);
  9322. EXPECT_FALSE(res->body.empty());
  9323. }
  9324. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9325. auto port = start(enable);
  9326. Client cli(HOST, port);
  9327. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9331. EXPECT_EQ(1048576U, res->body.size());
  9332. }
  9333. TEST_F(StaticFileCompressionTest, FileContent) {
  9334. auto port = start(enable_without_floor);
  9335. Client cli(HOST, port);
  9336. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9338. EXPECT_EQ(StatusCode::OK_200, res->status);
  9339. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9341. EXPECT_EQ(104U, res->body.size());
  9342. }
  9343. // A handler that serves an already-encoded file names the coding itself. The
  9344. // file-backed path decided its coding from Accept-Encoding and the content
  9345. // type alone, so it compressed the stored bytes a second time and appended a
  9346. // second Content-Encoding field line.
  9347. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9348. auto port = start(enable_without_floor);
  9349. Client cli(HOST, port);
  9350. cli.set_decompress(false);
  9351. auto res = cli.Get("/pre-encoded-file-content",
  9352. Headers{{"Accept-Encoding", "gzip"}});
  9353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9354. EXPECT_EQ(StatusCode::OK_200, res->status);
  9355. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9356. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9357. // Vary belongs to a coding the server chose, and it chose none here.
  9358. EXPECT_FALSE(res->has_header("Vary"));
  9359. // The file travels exactly as it is stored on disk.
  9360. EXPECT_EQ(104U, res->body.size());
  9361. }
  9362. // The 1MB file clears the default floor, so this one runs the configuration a
  9363. // deployment would actually have.
  9364. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9365. auto port = start(enable);
  9366. Client cli(HOST, port);
  9367. cli.set_decompress(false);
  9368. auto res =
  9369. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9371. EXPECT_EQ(StatusCode::OK_200, res->status);
  9372. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9373. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9374. EXPECT_FALSE(res->has_header("Vary"));
  9375. EXPECT_EQ(1048576U, res->body.size());
  9376. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9377. }
  9378. TEST_F(StaticFileCompressionTest, Head) {
  9379. auto port = start(enable);
  9380. Client cli(HOST, port);
  9381. cli.set_decompress(false);
  9382. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9383. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9384. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9386. EXPECT_EQ(StatusCode::OK_200, res->status);
  9387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9388. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9389. // HEAD still reports the size a GET would return.
  9390. EXPECT_EQ(get->get_header_value("Content-Length"),
  9391. res->get_header_value("Content-Length"));
  9392. EXPECT_TRUE(res->body.empty());
  9393. }
  9394. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9395. auto port = start(enable);
  9396. Client cli(HOST, port);
  9397. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9398. {"Accept-Encoding", "gzip"}});
  9399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9401. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9402. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9403. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9404. EXPECT_EQ("cd", res->body);
  9405. }
  9406. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9407. auto port = start(enable);
  9408. Client cli(HOST, port);
  9409. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9411. EXPECT_EQ(StatusCode::OK_200, res->status);
  9412. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9413. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9414. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9415. }
  9416. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9417. auto port = start(enable);
  9418. Client cli(HOST, port);
  9419. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9421. EXPECT_EQ(StatusCode::OK_200, res->status);
  9422. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9423. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9424. EXPECT_TRUE(res->body.empty());
  9425. }
  9426. TEST_F(StaticFileCompressionTest, MinLength) {
  9427. auto port = start(enable);
  9428. Client cli(HOST, port);
  9429. // 104 bytes, well under the default floor. Compressing it would add the
  9430. // gzip header and trailer to a body that already fits in one packet.
  9431. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9433. EXPECT_EQ(StatusCode::OK_200, res->status);
  9434. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9435. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9436. }
  9437. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9438. auto port = start([](Server &svr) {
  9439. svr.set_static_file_compression(true);
  9440. svr.set_static_file_compression_min_length(1);
  9441. });
  9442. Client cli(HOST, port);
  9443. cli.set_decompress(false);
  9444. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9446. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9447. // A 9-byte file comes back larger than it went in, because gzip's header and
  9448. // trailer outweigh anything deflate can save. That is the end of the range
  9449. // the floor exists to keep out.
  9450. EXPECT_GT(res->body.size(), 9U);
  9451. }
  9452. TEST_F(StaticFileCompressionTest, MaxLength) {
  9453. auto port = start([](Server &svr) {
  9454. svr.set_static_file_compression(true);
  9455. svr.set_static_file_compression_min_length(0);
  9456. svr.set_static_file_compression_max_length(1024);
  9457. });
  9458. Client cli(HOST, port);
  9459. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9460. // defines `small` as a macro on Windows.
  9461. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9462. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9463. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9464. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9465. // Under it: compressed.
  9466. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9467. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9468. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9469. }
  9470. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9471. auto port = start(enable_without_floor);
  9472. Client cli(HOST, port);
  9473. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9474. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9475. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9476. auto identity_etag = identity->get_header_value("ETag");
  9477. ASSERT_FALSE(identity_etag.empty());
  9478. auto gzipped =
  9479. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9480. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9481. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9482. auto gzip_etag = gzipped->get_header_value("ETag");
  9483. ASSERT_FALSE(gzip_etag.empty());
  9484. // Two representations, two validators.
  9485. EXPECT_NE(identity_etag, gzip_etag);
  9486. // Each one revalidates against the request that would produce it...
  9487. auto fresh =
  9488. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9489. {"If-None-Match", gzip_etag}});
  9490. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9491. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9492. auto fresh_identity =
  9493. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9494. {"If-None-Match", identity_etag}});
  9495. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9496. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9497. // ...and not against the other representation.
  9498. auto crossed =
  9499. cli.Get("/dir/index.html",
  9500. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9501. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9502. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9503. }
  9504. // The opt-in covers responses the server reads off disk itself. A caller's own
  9505. // known-length provider keeps its Content-Length and, more importantly, keeps
  9506. // delivering incrementally: routing it through a compressor would hold every
  9507. // write back until zlib's window filled.
  9508. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9509. auto port = start(enable);
  9510. Client cli(HOST, port);
  9511. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9513. EXPECT_EQ(StatusCode::OK_200, res->status);
  9514. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9515. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9516. EXPECT_EQ("aaabbb", res->body);
  9517. }
  9518. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9519. auto port = start(enable);
  9520. Client cli(HOST, port);
  9521. cli.set_read_timeout(1, 0);
  9522. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9523. Headers{{"Accept-Encoding", "gzip"}});
  9524. ASSERT_TRUE(handle.is_valid());
  9525. // The provider writes 100 bytes and then stalls for longer than the read
  9526. // timeout. Those first bytes have to arrive anyway: run the response through
  9527. // a compressor and zlib holds them until its window fills, so the read would
  9528. // come back empty instead.
  9529. char buf[256];
  9530. auto n = handle.read(buf, sizeof(buf));
  9531. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9532. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9533. }
  9534. #endif
  9535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9536. TEST_F(ServerTest, Brotli) {
  9537. Headers headers;
  9538. headers.emplace("Accept-Encoding", "br");
  9539. auto res = cli_.Get("/compress", headers);
  9540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9541. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9543. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9545. "7890123456789012345678901234567890",
  9546. res->body);
  9547. EXPECT_EQ(StatusCode::OK_200, res->status);
  9548. }
  9549. #endif
  9550. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9551. TEST_F(ServerTest, Zstd) {
  9552. Headers headers;
  9553. headers.emplace("Accept-Encoding", "zstd");
  9554. auto res = cli_.Get("/compress", headers);
  9555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9556. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9558. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9559. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9560. "7890123456789012345678901234567890",
  9561. res->body);
  9562. EXPECT_EQ(StatusCode::OK_200, res->status);
  9563. }
  9564. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9565. Headers headers;
  9566. headers.emplace("Accept-Encoding", "");
  9567. auto res = cli_.Get("/compress", headers);
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9573. "7890123456789012345678901234567890",
  9574. res->body);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. }
  9577. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9578. Headers headers;
  9579. headers.emplace("Accept-Encoding", "zstd");
  9580. std::string body;
  9581. auto res =
  9582. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9583. EXPECT_EQ(100U, data_length);
  9584. body.append(data, data_length);
  9585. return true;
  9586. });
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9590. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9591. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9592. "7890123456789012345678901234567890",
  9593. body);
  9594. EXPECT_EQ(StatusCode::OK_200, res->status);
  9595. }
  9596. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9597. Headers headers;
  9598. headers.emplace("Accept-Encoding", "zstd");
  9599. cli_.set_decompress(false);
  9600. auto res = cli_.Get("/compress", headers);
  9601. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9602. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9603. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9604. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9606. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9608. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. ASSERT_EQ(26U, res->body.size());
  9611. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9612. 0);
  9613. }
  9614. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9615. Headers headers;
  9616. headers.emplace("Accept-Encoding", "");
  9617. std::string body;
  9618. auto res =
  9619. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9620. EXPECT_EQ(100U, data_length);
  9621. body.append(data, data_length);
  9622. return true;
  9623. });
  9624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9625. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9626. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9627. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9628. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9629. "7890123456789012345678901234567890",
  9630. body);
  9631. EXPECT_EQ(StatusCode::OK_200, res->status);
  9632. }
  9633. TEST_F(ServerTest, NoZstd) {
  9634. Headers headers;
  9635. headers.emplace("Accept-Encoding", "zstd");
  9636. auto res = cli_.Get("/nocompress", headers);
  9637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9638. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9639. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9640. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9641. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9642. "7890123456789012345678901234567890",
  9643. res->body);
  9644. EXPECT_EQ(StatusCode::OK_200, res->status);
  9645. }
  9646. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9647. Headers headers;
  9648. headers.emplace("Accept-Encoding", "zstd");
  9649. std::string body;
  9650. auto res = cli_.Get("/nocompress", headers,
  9651. [&](const char *data, size_t data_length) {
  9652. EXPECT_EQ(100U, data_length);
  9653. body.append(data, data_length);
  9654. return true;
  9655. });
  9656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9657. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9658. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9659. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9660. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9661. "7890123456789012345678901234567890",
  9662. body);
  9663. EXPECT_EQ(StatusCode::OK_200, res->status);
  9664. }
  9665. // TODO: How to enable zstd ??
  9666. TEST_F(ServerTest, MultipartFormDataZstd) {
  9667. UploadFormDataItems items = {
  9668. {"key1", "test", "", ""},
  9669. {"key2", "--abcdefg123", "", ""},
  9670. };
  9671. Headers headers;
  9672. headers.emplace("Accept-Encoding", "zstd");
  9673. cli_.set_compress(true);
  9674. auto res = cli_.Post("/compress-multipart", headers, items);
  9675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9676. EXPECT_EQ(StatusCode::OK_200, res->status);
  9677. }
  9678. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9679. Headers headers;
  9680. headers.emplace("Accept-Encoding", "zstd");
  9681. cli_.set_compress(true);
  9682. auto res = cli_.Put(
  9683. "/put", headers, 3,
  9684. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9685. sink.os << "PUT";
  9686. return true;
  9687. },
  9688. "text/plain");
  9689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9690. EXPECT_EQ(StatusCode::OK_200, res->status);
  9691. EXPECT_EQ("PUT", res->body);
  9692. }
  9693. // Pre-compression logging tests
  9694. TEST_F(ServerTest, PreCompressionLogging) {
  9695. // Test data for compression (matches the actual /compress endpoint content)
  9696. const std::string test_content =
  9697. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9698. "3456789012345678901234567890";
  9699. // Variables to capture logging data
  9700. std::string pre_compression_body;
  9701. std::string pre_compression_content_type;
  9702. std::string pre_compression_content_encoding;
  9703. std::string post_compression_body;
  9704. std::string post_compression_content_type;
  9705. std::string post_compression_content_encoding;
  9706. // Set up pre-compression logger
  9707. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9708. const Response &res) {
  9709. pre_compression_body = res.body;
  9710. pre_compression_content_type = res.get_header_value("Content-Type");
  9711. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9712. });
  9713. // Set up post-compression logger
  9714. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9715. post_compression_body = res.body;
  9716. post_compression_content_type = res.get_header_value("Content-Type");
  9717. post_compression_content_encoding =
  9718. res.get_header_value("Content-Encoding");
  9719. });
  9720. // Test with gzip compression
  9721. Headers headers;
  9722. headers.emplace("Accept-Encoding", "gzip");
  9723. auto res = cli_.Get("/compress", headers);
  9724. // Verify response was compressed
  9725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9726. EXPECT_EQ(StatusCode::OK_200, res->status);
  9727. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9728. // Verify pre-compression logger captured uncompressed content
  9729. EXPECT_EQ(test_content, pre_compression_body);
  9730. EXPECT_EQ("text/plain", pre_compression_content_type);
  9731. EXPECT_TRUE(pre_compression_content_encoding
  9732. .empty()); // No encoding header before compression
  9733. // Verify post-compression logger captured compressed content
  9734. EXPECT_NE(test_content,
  9735. post_compression_body); // Should be different after compression
  9736. EXPECT_EQ("text/plain", post_compression_content_type);
  9737. EXPECT_EQ("gzip", post_compression_content_encoding);
  9738. // Verify compressed content is smaller
  9739. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9740. }
  9741. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9742. const std::string test_content =
  9743. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9744. "3456789012345678901234567890";
  9745. std::string pre_compression_body;
  9746. std::string post_compression_body;
  9747. svr_.set_pre_compression_logger(
  9748. [&](const Request & /*req*/, const Response &res) {
  9749. pre_compression_body = res.body;
  9750. });
  9751. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9752. post_compression_body = res.body;
  9753. });
  9754. Headers headers;
  9755. headers.emplace("Accept-Encoding", "br");
  9756. auto res = cli_.Get("/compress", headers);
  9757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9758. EXPECT_EQ(StatusCode::OK_200, res->status);
  9759. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9760. // Verify pre-compression content is uncompressed
  9761. EXPECT_EQ(test_content, pre_compression_body);
  9762. // Verify post-compression content is compressed
  9763. EXPECT_NE(test_content, post_compression_body);
  9764. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9765. }
  9766. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9767. const std::string test_content =
  9768. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9769. "3456789012345678901234567890";
  9770. std::string pre_compression_body;
  9771. std::string post_compression_body;
  9772. svr_.set_pre_compression_logger(
  9773. [&](const Request & /*req*/, const Response &res) {
  9774. pre_compression_body = res.body;
  9775. });
  9776. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9777. post_compression_body = res.body;
  9778. });
  9779. // Request without compression (use /nocompress endpoint)
  9780. Headers headers;
  9781. auto res = cli_.Get("/nocompress", headers);
  9782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9783. EXPECT_EQ(StatusCode::OK_200, res->status);
  9784. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9785. // Pre-compression logger should not be called when no compression is applied
  9786. EXPECT_TRUE(
  9787. pre_compression_body.empty()); // Pre-compression logger not called
  9788. EXPECT_EQ(
  9789. test_content,
  9790. post_compression_body); // Post-compression logger captures final content
  9791. }
  9792. TEST_F(ServerTest, LoggerSeesContentLength) {
  9793. size_t logged_content_length = 0;
  9794. std::string logged_content_length_header;
  9795. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9796. logged_content_length = res.content_length_;
  9797. logged_content_length_header = res.get_header_value("Content-Length");
  9798. });
  9799. auto res = cli_.Get("/nocompress");
  9800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9801. EXPECT_EQ(StatusCode::OK_200, res->status);
  9802. EXPECT_EQ(res->body.size(), logged_content_length);
  9803. EXPECT_EQ(std::to_string(logged_content_length),
  9804. logged_content_length_header);
  9805. }
  9806. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9807. const std::string test_content =
  9808. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9809. "3456789012345678901234567890";
  9810. std::string pre_compression_body;
  9811. bool pre_logger_called = false;
  9812. // Set only pre-compression logger
  9813. svr_.set_pre_compression_logger(
  9814. [&](const Request & /*req*/, const Response &res) {
  9815. pre_compression_body = res.body;
  9816. pre_logger_called = true;
  9817. });
  9818. Headers headers;
  9819. headers.emplace("Accept-Encoding", "gzip");
  9820. auto res = cli_.Get("/compress", headers);
  9821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9822. EXPECT_EQ(StatusCode::OK_200, res->status);
  9823. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9824. // Verify pre-compression logger was called
  9825. EXPECT_TRUE(pre_logger_called);
  9826. EXPECT_EQ(test_content, pre_compression_body);
  9827. }
  9828. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9829. {
  9830. // Test with Expect: 100-continue header - success case
  9831. // Server returns 100 Continue, client sends body, server returns 200 OK
  9832. Request req;
  9833. req.method = "POST";
  9834. req.path = "/post-large";
  9835. req.set_header("Expect", "100-continue");
  9836. req.body = LARGE_DATA;
  9837. Response res;
  9838. auto error = Error::Success;
  9839. cli_.set_keep_alive(true);
  9840. auto ret = cli_.send(req, res, error);
  9841. EXPECT_TRUE(ret);
  9842. EXPECT_EQ(StatusCode::OK_200, res.status);
  9843. EXPECT_EQ(LARGE_DATA, res.body);
  9844. }
  9845. {
  9846. // Test with Expect: 100-continue header - error case
  9847. // Client should not send the body when server returns an error
  9848. Request req;
  9849. req.method = "POST";
  9850. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9851. req.set_header("Expect", "100-continue");
  9852. req.body = LARGE_DATA;
  9853. Response res;
  9854. auto error = Error::Success;
  9855. auto start = std::chrono::high_resolution_clock::now();
  9856. cli_.set_keep_alive(true);
  9857. auto ret = cli_.send(req, res, error);
  9858. auto end = std::chrono::high_resolution_clock::now();
  9859. auto elapsed =
  9860. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9861. .count();
  9862. // With Expect: 100-continue, request completes successfully but with error
  9863. EXPECT_TRUE(ret);
  9864. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9865. EXPECT_EQ("close", res.get_header_value("Connection"));
  9866. EXPECT_FALSE(cli_.is_socket_open());
  9867. EXPECT_LE(elapsed, 2000);
  9868. }
  9869. {
  9870. // Send an extra GET request to ensure error recovery without hanging
  9871. Request req;
  9872. req.method = "GET";
  9873. req.path = "/hi";
  9874. auto start = std::chrono::high_resolution_clock::now();
  9875. auto res = cli_.send(req);
  9876. auto end = std::chrono::high_resolution_clock::now();
  9877. auto elapsed =
  9878. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9879. .count();
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. EXPECT_EQ("Hello World!", res->body);
  9883. EXPECT_LE(elapsed, 500);
  9884. }
  9885. }
  9886. TEST(ZstdDecompressor, ChunkedDecompression) {
  9887. std::string data;
  9888. for (size_t i = 0; i < 32 * 1024; ++i) {
  9889. data.push_back(static_cast<char>('a' + i % 26));
  9890. }
  9891. std::string compressed_data;
  9892. {
  9893. httplib::detail::zstd_compressor compressor;
  9894. bool result = compressor.compress(
  9895. data.data(), data.size(),
  9896. /*last=*/true,
  9897. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9898. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9899. compressed_data_size);
  9900. return true;
  9901. });
  9902. ASSERT_TRUE(result);
  9903. }
  9904. std::string decompressed_data;
  9905. {
  9906. httplib::detail::zstd_decompressor decompressor;
  9907. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9908. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9909. size_t chunk_size = 130;
  9910. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9911. chunk_begin += chunk_size) {
  9912. size_t current_chunk_size =
  9913. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9914. bool result = decompressor.decompress(
  9915. compressed_data.data() + chunk_begin, current_chunk_size,
  9916. [&](const char *decompressed_data_chunk,
  9917. size_t decompressed_data_chunk_size) {
  9918. decompressed_data.insert(decompressed_data.size(),
  9919. decompressed_data_chunk,
  9920. decompressed_data_chunk_size);
  9921. return true;
  9922. });
  9923. ASSERT_TRUE(result);
  9924. }
  9925. }
  9926. ASSERT_EQ(data, decompressed_data);
  9927. }
  9928. TEST(ZstdDecompressor, Decompress) {
  9929. std::string original_text = "Compressed with ZSTD";
  9930. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9931. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9932. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9933. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9934. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9935. std::string decompressed_data;
  9936. {
  9937. httplib::detail::zstd_decompressor decompressor;
  9938. bool result = decompressor.decompress(
  9939. compressed_data.data(), compressed_data.size(),
  9940. [&](const char *decompressed_data_chunk,
  9941. size_t decompressed_data_chunk_size) {
  9942. decompressed_data.insert(decompressed_data.size(),
  9943. decompressed_data_chunk,
  9944. decompressed_data_chunk_size);
  9945. return true;
  9946. });
  9947. ASSERT_TRUE(result);
  9948. }
  9949. ASSERT_EQ(original_text, decompressed_data);
  9950. }
  9951. #endif
  9952. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9953. // separate chunks so that the server sees each part in its own read(). Used to
  9954. // place a read boundary at a specific offset of a request body.
  9955. static bool send_request_in_parts(time_t read_timeout_sec,
  9956. const std::vector<std::string> &parts,
  9957. std::string *resp = nullptr,
  9958. int port = PORT) {
  9959. auto error = Error::Success;
  9960. auto client_sock = detail::create_client_socket(
  9961. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9962. /*connection_timeout_sec=*/5, 0,
  9963. /*read_timeout_sec=*/5, 0,
  9964. /*write_timeout_sec=*/5, 0, std::string(), error);
  9965. if (client_sock == INVALID_SOCKET) { return false; }
  9966. auto ret = detail::process_client_socket(
  9967. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9968. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9969. for (size_t i = 0; i < parts.size(); i++) {
  9970. const auto &part = parts[i];
  9971. if (part.size() !=
  9972. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9973. return false;
  9974. }
  9975. if (i + 1 < parts.size()) {
  9976. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9977. }
  9978. }
  9979. char buf[512];
  9980. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9981. while (line_reader.getline()) {
  9982. if (resp) { *resp += line_reader.ptr(); }
  9983. }
  9984. return true;
  9985. });
  9986. detail::close_socket(client_sock);
  9987. return ret;
  9988. }
  9989. // Sends a raw request to a server listening at HOST:PORT.
  9990. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9991. std::string *resp = nullptr, int port = PORT) {
  9992. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9993. }
  9994. #ifdef CPPHTTPLIB_SSL_ENABLED
  9995. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9997. ASSERT_TRUE(svr.is_valid());
  9998. svr.set_read_timeout(1, 0);
  9999. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10000. auto se = detail::scope_exit([&] {
  10001. svr.stop();
  10002. t.join();
  10003. ASSERT_FALSE(svr.is_running());
  10004. });
  10005. svr.wait_until_ready();
  10006. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10007. // keeps each wait well within the read timeout. The server gives up a
  10008. // second in, so the bytes sent after that fail.
  10009. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10010. parts.resize(26, std::string(1, '\0'));
  10011. EXPECT_FALSE(send_request_in_parts(5, parts));
  10012. }
  10013. #endif
  10014. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10015. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10016. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10017. const std::vector<std::string> &parts,
  10018. std::string *resp = nullptr,
  10019. int port = PORT) {
  10020. auto error = Error::Success;
  10021. auto sock = detail::create_client_socket(
  10022. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10023. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10024. /*write_timeout_sec=*/5, 0, std::string(), error);
  10025. if (sock == INVALID_SOCKET) { return false; }
  10026. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10027. auto ctx = SSL_CTX_new(TLS_client_method());
  10028. auto ssl = SSL_new(ctx);
  10029. auto ssl_se = detail::scope_exit([&] {
  10030. SSL_free(ssl);
  10031. SSL_CTX_free(ctx);
  10032. });
  10033. SSL_set_fd(ssl, static_cast<int>(sock));
  10034. if (SSL_connect(ssl) != 1) { return false; }
  10035. for (size_t i = 0; i < parts.size(); i++) {
  10036. const auto &part = parts[i];
  10037. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10038. static_cast<int>(part.size())) {
  10039. return false;
  10040. }
  10041. if (i + 1 < parts.size()) {
  10042. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10043. }
  10044. }
  10045. char buf[512];
  10046. int n;
  10047. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10048. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10049. }
  10050. return true;
  10051. }
  10052. #endif
  10053. // The request line, then a header value a byte at a time.
  10054. static std::vector<std::string> slow_request_head_parts() {
  10055. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10056. parts.resize(26, "a");
  10057. parts.emplace_back("\r\n\r\n");
  10058. return parts;
  10059. }
  10060. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10061. // within the one-second read timeout. The server gives up a second in, before
  10062. // the head is complete.
  10063. static void
  10064. expect_slow_request_head_dropped(Server &svr,
  10065. const std::function<std::string()> &send) {
  10066. std::atomic<bool> handled(false);
  10067. svr.Get("/", [&](const Request &, Response &res) {
  10068. handled = true;
  10069. res.set_content("ok", "text/plain");
  10070. });
  10071. svr.set_read_timeout(1, 0);
  10072. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. t.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. auto resp = send();
  10080. EXPECT_FALSE(handled);
  10081. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10082. }
  10083. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10084. Server svr;
  10085. expect_slow_request_head_dropped(svr, [] {
  10086. std::string resp;
  10087. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10088. return resp;
  10089. });
  10090. }
  10091. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10092. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10094. ASSERT_TRUE(svr.is_valid());
  10095. expect_slow_request_head_dropped(svr, [] {
  10096. std::string resp;
  10097. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10098. return resp;
  10099. });
  10100. }
  10101. #endif
  10102. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10103. Server svr;
  10104. std::string header_value;
  10105. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10106. header_value = req.get_header_value("foo");
  10107. res.set_content("ok", "text/plain");
  10108. });
  10109. thread t = thread([&] { svr.listen(HOST, PORT); });
  10110. auto se = detail::scope_exit([&] {
  10111. svr.stop();
  10112. t.join();
  10113. ASSERT_FALSE(svr.is_running());
  10114. });
  10115. svr.wait_until_ready();
  10116. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10117. // like characters are not treated the same - use vertical tab and escape.
  10118. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10119. "foo: \t \v bar \x1B\t \r\n"
  10120. "Connection: close\r\n"
  10121. "\r\n";
  10122. std::string res;
  10123. ASSERT_TRUE(send_request(5, req, &res));
  10124. EXPECT_EQ(header_value, "");
  10125. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10126. }
  10127. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10128. Server svr;
  10129. std::string received;
  10130. svr.Get("/order", [&](const Request &req, Response &res) {
  10131. received = entries_to_string(req.headers);
  10132. res.set_content("ok", "text/plain");
  10133. });
  10134. auto port = svr.bind_to_any_port(HOST);
  10135. thread t = thread([&] { svr.listen_after_bind(); });
  10136. auto se = detail::scope_exit([&] {
  10137. svr.stop();
  10138. t.join();
  10139. ASSERT_FALSE(svr.is_running());
  10140. });
  10141. svr.wait_until_ready();
  10142. const std::string req = "GET /order HTTP/1.1\r\n"
  10143. "Host: localhost\r\n"
  10144. "X-First: 1\r\n"
  10145. "X-Dup: a\r\n"
  10146. "X-Second: 2\r\n"
  10147. "X-Dup: b\r\n"
  10148. "Connection: close\r\n"
  10149. "\r\n";
  10150. std::string res;
  10151. ASSERT_TRUE(send_request(5, req, &res, port));
  10152. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10153. EXPECT_EQ(
  10154. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10155. received);
  10156. }
  10157. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10158. Server svr;
  10159. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10160. res.set_header("Set-Cookie", "first=1");
  10161. res.set_header("X-Between", "y");
  10162. res.set_header("Set-Cookie", "second=2");
  10163. res.set_content("ok", "text/plain");
  10164. });
  10165. auto port = svr.bind_to_any_port(HOST);
  10166. thread t = thread([&] { svr.listen_after_bind(); });
  10167. auto se = detail::scope_exit([&] {
  10168. svr.stop();
  10169. t.join();
  10170. ASSERT_FALSE(svr.is_running());
  10171. });
  10172. svr.wait_until_ready();
  10173. Client cli(HOST, port);
  10174. auto res = cli.Get("/cookies");
  10175. ASSERT_TRUE(res);
  10176. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10177. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10178. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10179. }
  10180. // A stream may send a byte at a time with a small extension on each chunk,
  10181. // however long it runs
  10182. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10183. Server svr;
  10184. svr.Post("/count", [](const Request &req, Response &res) {
  10185. res.set_content(std::to_string(req.body.size()), "text/plain");
  10186. });
  10187. auto port = svr.bind_to_any_port(HOST);
  10188. ASSERT_LT(0, port);
  10189. thread t = thread([&] { svr.listen_after_bind(); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10197. "\r\nTransfer-Encoding: chunked\r\n"
  10198. "Connection: close\r\n\r\n";
  10199. for (auto i = 0; i < 4096; i++) {
  10200. req += "1;a=b\r\nx\r\n";
  10201. }
  10202. req += "0\r\n\r\n";
  10203. std::string res;
  10204. ASSERT_TRUE(send_request(5, req, &res, port));
  10205. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10206. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10207. }
  10208. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10209. Server svr;
  10210. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10211. auto i = new int(0);
  10212. res.set_header("Trailer", "X-Safe, X-Reflected");
  10213. res.set_chunked_content_provider(
  10214. "text/plain",
  10215. [i](size_t /*offset*/, DataSink &sink) {
  10216. if (*i == 0) {
  10217. sink.os << "body";
  10218. } else {
  10219. Headers trailer;
  10220. // A valid trailer that must survive.
  10221. trailer.emplace("X-Safe", "safe");
  10222. // Attacker-controlled value carrying CR/LF (response splitting).
  10223. trailer.emplace("X-Reflected",
  10224. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10225. // Attacker-controlled name carrying CR/LF.
  10226. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10227. sink.done_with_trailer(trailer);
  10228. }
  10229. (*i)++;
  10230. return true;
  10231. },
  10232. [i](bool /*success*/) { delete i; });
  10233. });
  10234. thread t = thread([&] { svr.listen(HOST, PORT); });
  10235. auto se = detail::scope_exit([&] {
  10236. svr.stop();
  10237. t.join();
  10238. ASSERT_FALSE(svr.is_running());
  10239. });
  10240. svr.wait_until_ready();
  10241. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10242. "Host: " + HOST +
  10243. "\r\n"
  10244. "Connection: close\r\n"
  10245. "\r\n";
  10246. std::string res;
  10247. ASSERT_TRUE(send_request(5, req, &res));
  10248. // The injected fields must not appear anywhere in the raw response.
  10249. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10250. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10251. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10252. // Invalid trailers are dropped entirely, matching set_header().
  10253. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10254. // The valid trailer still passes through.
  10255. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10256. }
  10257. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10258. // A custom header writer gets only the fields the default one writes
  10259. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10260. std::string s;
  10261. for (const auto &h : hdrs) {
  10262. s += h.first + ": " + h.second + "\r\n";
  10263. }
  10264. s += "\r\n";
  10265. return strm.write(s.data(), s.size());
  10266. };
  10267. for (auto custom_writer : {false, true}) {
  10268. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10269. Server svr;
  10270. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10271. svr.set_post_routing_handler([](const Request &, Response &res) {
  10272. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10273. });
  10274. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10275. // res.headers is a public field an application can populate directly,
  10276. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10277. // A valid header that must survive.
  10278. res.headers.emplace("X-Safe", "safe");
  10279. // Attacker-controlled value carrying CR/LF (response splitting).
  10280. res.headers.emplace("X-Reflected",
  10281. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10282. // Attacker-controlled name carrying CR/LF.
  10283. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10284. res.set_content("body", "text/plain");
  10285. });
  10286. thread t = thread([&] { svr.listen(HOST, PORT); });
  10287. auto se = detail::scope_exit([&] {
  10288. svr.stop();
  10289. t.join();
  10290. ASSERT_FALSE(svr.is_running());
  10291. });
  10292. svr.wait_until_ready();
  10293. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10294. "Host: " + HOST +
  10295. "\r\n"
  10296. "Connection: close\r\n"
  10297. "\r\n";
  10298. std::string res;
  10299. ASSERT_TRUE(send_request(5, req, &res));
  10300. // The injected fields must not appear anywhere in the raw response.
  10301. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10302. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10303. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10304. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10305. // Invalid headers are dropped entirely, matching set_header().
  10306. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10307. // The valid header still passes through.
  10308. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10309. }
  10310. }
  10311. // Forward declaration: in split builds split.py strips `inline` and moves the
  10312. // definition into httplib.cc, so detail::write_request_line is not visible from
  10313. // the public httplib.h. Re-declaring it here lets the tests link against the
  10314. // symbol in both header-only and split builds.
  10315. namespace httplib {
  10316. namespace detail {
  10317. ssize_t write_request_line(Stream &strm, const std::string &method,
  10318. const std::string &path);
  10319. } // namespace detail
  10320. } // namespace httplib
  10321. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10322. // A well-formed target is written verbatim.
  10323. {
  10324. detail::BufferStream strm;
  10325. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10326. EXPECT_GT(n, 0);
  10327. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10328. }
  10329. // A target carrying CR/LF, SP or other control octets must be rejected
  10330. // before anything reaches the wire, otherwise it splits the request line and
  10331. // injects a header or a whole request.
  10332. const std::string evil_targets[] = {
  10333. "/a\r\nInjected: pwned",
  10334. "/a\rInjected",
  10335. "/a\nInjected",
  10336. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10337. "/a b",
  10338. "/a\tb",
  10339. "/a\x7f",
  10340. };
  10341. for (const auto &evil : evil_targets) {
  10342. detail::BufferStream strm;
  10343. auto n = detail::write_request_line(strm, "GET", evil);
  10344. EXPECT_LT(n, 0);
  10345. EXPECT_TRUE(strm.get_buffer().empty());
  10346. }
  10347. }
  10348. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10349. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10350. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10351. // target reaches write_request. The client must fail cleanly with
  10352. // Error::Write instead of putting a request-line-less, header-injecting
  10353. // request on the wire.
  10354. Server svr;
  10355. svr.Get("/a", [](const Request &, Response &res) {
  10356. res.set_content("ok", "text/plain");
  10357. });
  10358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10359. auto se = detail::scope_exit([&] {
  10360. svr.stop();
  10361. thread.join();
  10362. ASSERT_FALSE(svr.is_running());
  10363. });
  10364. svr.wait_until_ready();
  10365. {
  10366. Client cli(HOST, PORT);
  10367. cli.set_path_encode(false);
  10368. // The request is rejected before anything is written, so the connection
  10369. // stays silent and the subsequent response read would otherwise block for
  10370. // the full default read timeout. Shorten it -- the assertion is on the
  10371. // error, not the timeout.
  10372. cli.set_read_timeout(1, 0);
  10373. auto res = cli.Get("/a\r\nInjected: pwned");
  10374. EXPECT_FALSE(res);
  10375. EXPECT_EQ(Error::Write, res.error());
  10376. }
  10377. }
  10378. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10379. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10380. // including extension methods.
  10381. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10382. for (const auto &method : good_methods) {
  10383. detail::BufferStream strm;
  10384. auto n = detail::write_request_line(strm, method, "/");
  10385. EXPECT_GT(n, 0);
  10386. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10387. }
  10388. // A method carrying CR/LF would split the request line and smuggle a whole
  10389. // request ahead of the real one. A space or an empty method corrupts the
  10390. // request line. All must be rejected before anything reaches the wire.
  10391. const std::string evil_methods[] = {
  10392. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10393. "GET\r\nInjected: pwned",
  10394. "GET\r",
  10395. "GET\n",
  10396. "GE T",
  10397. "",
  10398. };
  10399. for (const auto &evil : evil_methods) {
  10400. detail::BufferStream strm;
  10401. auto n = detail::write_request_line(strm, evil, "/");
  10402. EXPECT_LT(n, 0);
  10403. EXPECT_TRUE(strm.get_buffer().empty());
  10404. }
  10405. }
  10406. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10407. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10408. // through Client::send must fail with Error::Write and no request, neither
  10409. // the smuggled one nor the real one, may reach the server.
  10410. Server svr;
  10411. std::atomic<int> request_count(0);
  10412. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10413. request_count++;
  10414. res.status = StatusCode::OK_200;
  10415. return Server::HandlerResponse::Handled;
  10416. });
  10417. auto port = svr.bind_to_any_port(HOST);
  10418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. thread.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. {
  10426. Client cli(HOST, port);
  10427. const std::string evil_methods[] = {
  10428. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10429. "GE T",
  10430. "",
  10431. };
  10432. for (const auto &evil : evil_methods) {
  10433. Request req;
  10434. req.method = evil;
  10435. req.path = "/";
  10436. auto res = cli.send(req);
  10437. EXPECT_FALSE(res);
  10438. EXPECT_EQ(Error::Write, res.error());
  10439. }
  10440. auto handle =
  10441. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10442. EXPECT_FALSE(handle.is_valid());
  10443. EXPECT_EQ(Error::Write, handle.error);
  10444. // A valid request on the same client still goes through.
  10445. auto res = cli.Get("/");
  10446. ASSERT_TRUE(res);
  10447. EXPECT_EQ(StatusCode::OK_200, res->status);
  10448. }
  10449. EXPECT_EQ(1, request_count.load());
  10450. }
  10451. // Sends a raw request and verifies that there isn't a crash or exception.
  10452. static void test_raw_request(const std::string &req,
  10453. std::string *out = nullptr) {
  10454. Server svr;
  10455. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10456. res.set_content("ok", "text/plain");
  10457. });
  10458. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10459. res.set_content("ok", "text/plain");
  10460. });
  10461. svr.Get("/header_field_value_check",
  10462. [&](const Request & /*req*/, Response &res) {
  10463. res.set_content("ok", "text/plain");
  10464. });
  10465. svr.CustomRoute("PROPFIND", "/dav",
  10466. [&](const Request & /*req*/, Response &res) {
  10467. res.status = StatusCode::MultiStatus_207;
  10468. });
  10469. // Server read timeout must be longer than the client read timeout for the
  10470. // bug to reproduce, probably to force the server to process a request
  10471. // without a trailing blank line.
  10472. const time_t client_read_timeout_sec = 1;
  10473. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10474. bool listen_thread_ok = false;
  10475. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. ASSERT_FALSE(svr.is_running());
  10480. EXPECT_TRUE(listen_thread_ok);
  10481. });
  10482. svr.wait_until_ready();
  10483. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10484. }
  10485. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10486. // A certain header line causes an exception if the header property is parsed
  10487. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10488. test_raw_request(
  10489. "GET /hi HTTP/1.1\r\n"
  10490. " : "
  10491. " "
  10492. " ");
  10493. }
  10494. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10495. // A certain header line causes an exception if the header property *name* is
  10496. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10497. // greedy matcher and requires backtracking when there are a lot of ":"
  10498. // characters.
  10499. // This occurs with libc++ but not libstdc++.
  10500. test_raw_request(
  10501. "GET /hi HTTP/1.1\r\n"
  10502. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10503. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10504. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10505. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10506. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10507. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10508. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10509. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10510. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10511. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10512. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10513. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10514. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10515. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10516. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10517. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10518. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10519. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10520. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10521. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10522. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10523. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10524. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10525. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10526. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10527. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10528. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10529. "&&&%%%");
  10530. }
  10531. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10532. // Make sure this doesn't crash the server.
  10533. // In a previous version of the header line regex, the "\r" rendered the line
  10534. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10535. // a new position where the leading white space ended and the field value
  10536. // began.
  10537. // The crash occurs with libc++ but not libstdc++.
  10538. test_raw_request("GET /hi HTTP/1.1\r\n"
  10539. "a:" +
  10540. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10541. "\r\n"
  10542. "\r\n");
  10543. }
  10544. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10545. const char *rejected[] = {
  10546. // RFC 9112 §3: one SP between the parts, and nothing else
  10547. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10548. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10549. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10550. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10551. // A request-target has no fragment
  10552. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10553. // An HTTP/1.1 request needs a Host
  10554. "GET /hi HTTP/1.1\r\n\r\n",
  10555. };
  10556. for (auto request : rejected) {
  10557. std::string out;
  10558. test_raw_request(request, &out);
  10559. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10560. }
  10561. std::string out;
  10562. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10563. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10564. }
  10565. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10566. // RFC 9112 §6.1
  10567. const char *requests[] = {
  10568. "PUT /put_hi HTTP/1.1\r\n"
  10569. "Host: localhost\r\n"
  10570. "Content-Length: 0\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "\r\n"
  10573. "0\r\n\r\n",
  10574. "PUT /put_hi HTTP/1.0\r\n"
  10575. "Connection: keep-alive\r\n"
  10576. "Transfer-Encoding: chunked\r\n"
  10577. "\r\n"
  10578. "0\r\n\r\n",
  10579. };
  10580. for (auto request : requests) {
  10581. std::string out;
  10582. test_raw_request(request, &out);
  10583. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10584. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10585. }
  10586. }
  10587. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10588. std::string out;
  10589. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10590. "Content-Type: text/plain\r\n"
  10591. "Transfer-Encoding: chunked\r\n"
  10592. "\r\n"
  10593. "nothex\r\n",
  10594. &out);
  10595. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10596. }
  10597. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10598. std::string out;
  10599. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10600. "Content-Type: text/plain\r\n"
  10601. "Transfer-Encoding: chunked\r\n"
  10602. "\r\n"
  10603. "3\r\n"
  10604. "xyz\r\n"
  10605. "NaN\r\n",
  10606. &out);
  10607. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10608. }
  10609. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10610. std::string out;
  10611. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10612. "Content-Type: text/plain\r\n"
  10613. "Transfer-Encoding: chunked\r\n"
  10614. "\r\n"
  10615. // Length is too large for 64 bits.
  10616. "1ffffffffffffffff\r\n"
  10617. "xyz\r\n",
  10618. &out);
  10619. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10620. }
  10621. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10622. test_raw_request("GET /hi HTTP/1.1\r\n"
  10623. "Content-Type: text/plain\r\n\r");
  10624. }
  10625. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10626. std::string out;
  10627. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10628. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10629. }
  10630. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10631. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10632. std::string out;
  10633. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10634. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10635. }
  10636. }
  10637. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10638. std::string out;
  10639. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10640. "Host: localhost\r\n"
  10641. "Connection: close\r\n\r\n",
  10642. &out);
  10643. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10644. }
  10645. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10646. Server svr;
  10647. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10648. EXPECT_TRUE(!req.remote_addr.empty());
  10649. });
  10650. thread t = thread([&] { svr.listen(HOST, PORT); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. t.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. // Send an invalid request line to trigger Bad Request
  10658. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10659. std::string out;
  10660. ASSERT_TRUE(send_request(5, bad_req, &out));
  10661. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10662. }
  10663. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10664. // answered right away rather than blocking on a read that waits for EOF.
  10665. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10666. std::string out;
  10667. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10668. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10669. }
  10670. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10671. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10672. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10673. for (const auto *method : methods) {
  10674. Server svr;
  10675. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10676. EXPECT_FALSE(svr.is_valid()) << method;
  10677. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10678. }
  10679. }
  10680. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10681. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10682. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10683. for (const auto *method : methods) {
  10684. Server svr;
  10685. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10686. EXPECT_FALSE(svr.is_valid()) << method;
  10687. }
  10688. }
  10689. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10690. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10691. "COPY", "MOVE", "LOCK",
  10692. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10693. Server svr;
  10694. for (const auto *method : methods) {
  10695. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10696. }
  10697. EXPECT_TRUE(svr.is_valid());
  10698. }
  10699. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10700. Server svr;
  10701. svr.CustomRoute("POST", "/x",
  10702. [](const Request &, Response &, const ContentReader &) {});
  10703. EXPECT_FALSE(svr.is_valid());
  10704. }
  10705. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10706. Server svr;
  10707. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10708. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10709. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10710. EXPECT_FALSE(svr.is_valid());
  10711. }
  10712. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10713. Server svr;
  10714. auto captured = Error::Success;
  10715. svr.set_error_logger(
  10716. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10717. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10718. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10719. }
  10720. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10721. std::string out;
  10722. std::string request(
  10723. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10724. test_raw_request(request, &out);
  10725. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10726. }
  10727. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10728. std::string out;
  10729. std::string request(
  10730. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10731. test_raw_request(request, &out);
  10732. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10733. }
  10734. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10735. std::string out;
  10736. std::string request(
  10737. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10738. test_raw_request(request, &out);
  10739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10740. }
  10741. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10742. std::string out;
  10743. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10744. "Host: localhost\r\n"
  10745. "Test: \r\n\r\n",
  10746. &out);
  10747. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10748. }
  10749. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10750. Server svr;
  10751. std::string x_custom;
  10752. std::string cookie;
  10753. std::string xff;
  10754. std::string x_unicode;
  10755. std::string x_iis;
  10756. svr.Get("/check", [&](const Request &req, Response &res) {
  10757. x_custom = req.get_header_value("X-Custom");
  10758. cookie = req.get_header_value("Cookie");
  10759. xff = req.get_header_value("X-Forwarded-For");
  10760. x_unicode = req.get_header_value("X-Unicode");
  10761. x_iis = req.get_header_value("X-IIS");
  10762. res.set_content("ok", "text/plain");
  10763. });
  10764. thread t = thread([&] { svr.listen(HOST, PORT); });
  10765. auto se = detail::scope_exit([&] {
  10766. svr.stop();
  10767. t.join();
  10768. ASSERT_FALSE(svr.is_running());
  10769. });
  10770. svr.wait_until_ready();
  10771. const std::string req = "GET /check HTTP/1.1\r\n"
  10772. "Host: localhost\r\n"
  10773. "X-Custom: a%0D%0AInjected: b\r\n"
  10774. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10775. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10776. "X-Unicode: %E3%81%82\r\n"
  10777. "X-IIS: %u00E9\r\n"
  10778. "Connection: close\r\n"
  10779. "\r\n";
  10780. std::string res;
  10781. ASSERT_TRUE(send_request(5, req, &res));
  10782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10783. // Every value must be returned verbatim (wire form), with no decoding.
  10784. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10785. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10786. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10787. EXPECT_EQ("%E3%81%82", x_unicode);
  10788. EXPECT_EQ("%u00E9", x_iis);
  10789. }
  10790. // Applications that previously relied on automatic percent-decoding can
  10791. // reproduce the old behavior by explicitly calling decode_path_component()
  10792. // or, for RFC 3986 conformance, decode_uri_component().
  10793. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10794. Server svr;
  10795. std::string decoded;
  10796. svr.Get("/check", [&](const Request &req, Response &res) {
  10797. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10798. res.set_content("ok", "text/plain");
  10799. });
  10800. thread t = thread([&] { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. t.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. const std::string req = "GET /check HTTP/1.1\r\n"
  10808. "Host: localhost\r\n"
  10809. "X-Custom: hello%20world\r\n"
  10810. "Connection: close\r\n"
  10811. "\r\n";
  10812. std::string res;
  10813. ASSERT_TRUE(send_request(5, req, &res));
  10814. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10815. EXPECT_EQ("hello world", decoded);
  10816. }
  10817. // Regression test for #2033. Browsers send Referer values that include
  10818. // percent-encoded characters such as %0A inside the URL. Decoding the
  10819. // header value would either trip the post-decode CR/LF/NUL guard (the
  10820. // original bug, returning 400) or, after that guard was relaxed, silently
  10821. // store a literal LF — both unacceptable. The wire form must round-trip.
  10822. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10823. Server svr;
  10824. std::string referer;
  10825. svr.Get("/check", [&](const Request &req, Response &res) {
  10826. referer = req.get_header_value("Referer");
  10827. res.set_content("ok", "text/plain");
  10828. });
  10829. thread t = thread([&] { svr.listen(HOST, PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. t.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. const std::string req = "GET /check HTTP/1.1\r\n"
  10837. "Host: localhost\r\n"
  10838. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10839. "Connection: close\r\n"
  10840. "\r\n";
  10841. std::string res;
  10842. ASSERT_TRUE(send_request(5, req, &res));
  10843. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10844. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10845. }
  10846. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10847. Server svr;
  10848. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10849. res.set_header("Cache-Control", "no-cache");
  10850. res.set_chunked_content_provider(
  10851. "text/event-stream", [](size_t offset, DataSink &sink) {
  10852. std::string s = "data:";
  10853. s += std::to_string(offset);
  10854. s += "\n\n";
  10855. auto ret = sink.write(s.data(), s.size());
  10856. EXPECT_TRUE(ret);
  10857. std::this_thread::sleep_for(std::chrono::seconds(1));
  10858. return true;
  10859. });
  10860. });
  10861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10862. svr.wait_until_ready();
  10863. Client client(HOST, PORT);
  10864. const Headers headers = {{"Accept", "text/event-stream"}};
  10865. auto get_thread = std::thread([&client, &headers]() {
  10866. auto res = client.Get(
  10867. "/events", headers,
  10868. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10869. });
  10870. auto se = detail::scope_exit([&] {
  10871. svr.stop();
  10872. get_thread.join();
  10873. listen_thread.join();
  10874. ASSERT_FALSE(svr.is_running());
  10875. });
  10876. // Give GET time to get a few messages.
  10877. std::this_thread::sleep_for(std::chrono::seconds(2));
  10878. }
  10879. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10880. httplib::Server svr;
  10881. svr.Post("/hi",
  10882. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10883. res.status = StatusCode::OK_200;
  10884. });
  10885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10886. svr.wait_until_ready();
  10887. Client cli(HOST, PORT);
  10888. auto res = cli.Post("/hi", "data", "text/plain");
  10889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10890. EXPECT_EQ(StatusCode::OK_200, res->status);
  10891. svr.stop();
  10892. thread.join();
  10893. ASSERT_FALSE(svr.is_running());
  10894. res = cli.Post("/hi", "data", "text/plain");
  10895. ASSERT_FALSE(res);
  10896. }
  10897. TEST(ServerStopTest, ListenFailure) {
  10898. Server svr;
  10899. auto t = thread([&]() {
  10900. auto ret = svr.listen("????", PORT);
  10901. EXPECT_FALSE(ret);
  10902. });
  10903. svr.wait_until_ready();
  10904. svr.stop();
  10905. t.join();
  10906. }
  10907. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10908. TEST(ServerStopTest, Decommision) {
  10909. Server svr;
  10910. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10911. for (int i = 0; i < 4; i++) {
  10912. auto is_even = !(i % 2);
  10913. std::thread t{[&] {
  10914. try {
  10915. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10916. if (is_even) {
  10917. throw std::runtime_error("Some thing that happens to go wrong.");
  10918. }
  10919. svr.listen(HOST, PORT);
  10920. } catch (...) { svr.decommission(); }
  10921. }};
  10922. svr.wait_until_ready();
  10923. // Server is up
  10924. {
  10925. Client cli(HOST, PORT);
  10926. auto res = cli.Get("/hi");
  10927. if (is_even) {
  10928. EXPECT_FALSE(res);
  10929. } else {
  10930. EXPECT_TRUE(res);
  10931. EXPECT_EQ("hi...", res->body);
  10932. }
  10933. }
  10934. svr.stop();
  10935. t.join();
  10936. // Server is down...
  10937. {
  10938. Client cli(HOST, PORT);
  10939. auto res = cli.Get("/hi");
  10940. EXPECT_FALSE(res);
  10941. }
  10942. }
  10943. }
  10944. #endif
  10945. // Helper function for string body upload progress tests
  10946. template <typename SetupHandler, typename ClientCall>
  10947. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10948. ClientCall &&client_call,
  10949. const string &body) {
  10950. Server svr;
  10951. setup_handler(svr);
  10952. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10953. auto se = detail::scope_exit([&] {
  10954. svr.stop();
  10955. t.join();
  10956. });
  10957. svr.wait_until_ready();
  10958. Client cli(HOST, PORT);
  10959. vector<uint64_t> progress_values;
  10960. bool progress_called = false;
  10961. auto res =
  10962. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10963. progress_values.push_back(current);
  10964. progress_called = true;
  10965. return true;
  10966. });
  10967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10968. EXPECT_EQ(200, res->status);
  10969. EXPECT_TRUE(progress_called);
  10970. }
  10971. TEST(UploadProgressTest, PostStringBodyBasic) {
  10972. TestStringBodyUploadProgress(
  10973. [](Server &svr) {
  10974. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10975. res.set_content("received", "text/plain");
  10976. });
  10977. },
  10978. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10979. return cli.Post("/test", body, "text/plain", progress_callback);
  10980. },
  10981. "test data for upload progress");
  10982. }
  10983. TEST(UploadProgressTest, PutStringBodyBasic) {
  10984. TestStringBodyUploadProgress(
  10985. [](Server &svr) {
  10986. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10987. res.set_content("put received", "text/plain");
  10988. });
  10989. },
  10990. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10991. return cli.Put("/test", body, "text/plain", progress_callback);
  10992. },
  10993. "put test data for upload progress");
  10994. }
  10995. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10996. TestStringBodyUploadProgress(
  10997. [](Server &svr) {
  10998. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10999. res.set_content("patch received", "text/plain");
  11000. });
  11001. },
  11002. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11003. return cli.Patch("/test", body, "text/plain", progress_callback);
  11004. },
  11005. "patch test data for upload progress");
  11006. }
  11007. // Helper function for content provider upload progress tests
  11008. template <typename SetupHandler, typename ClientCall>
  11009. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11010. ClientCall &&client_call) {
  11011. Server svr;
  11012. setup_handler(svr);
  11013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11014. auto se = detail::scope_exit([&] {
  11015. svr.stop();
  11016. t.join();
  11017. });
  11018. svr.wait_until_ready();
  11019. Client cli(HOST, PORT);
  11020. vector<uint64_t> progress_values;
  11021. auto res =
  11022. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11023. progress_values.push_back(current);
  11024. return true;
  11025. });
  11026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11027. EXPECT_EQ(200, res->status);
  11028. EXPECT_FALSE(progress_values.empty());
  11029. }
  11030. TEST(UploadProgressTest, PostContentProviderProgress) {
  11031. TestContentProviderUploadProgress(
  11032. [](Server &svr) {
  11033. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("provider received", "text/plain");
  11035. });
  11036. },
  11037. [](Client &cli, UploadProgress progress_callback) {
  11038. return cli.Post(
  11039. "/test", 9,
  11040. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11041. sink.os << "test data";
  11042. return true;
  11043. },
  11044. "text/plain", progress_callback);
  11045. });
  11046. }
  11047. // Helper function for multipart upload progress tests
  11048. template <typename SetupHandler, typename ClientCall>
  11049. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11050. ClientCall &&client_call,
  11051. const string &endpoint) {
  11052. Server svr;
  11053. setup_handler(svr);
  11054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11055. auto se = detail::scope_exit([&] {
  11056. svr.stop();
  11057. t.join();
  11058. });
  11059. svr.wait_until_ready();
  11060. Client cli(HOST, PORT);
  11061. vector<uint64_t> progress_values;
  11062. UploadFormDataItems items = {
  11063. {"field1", "value1", "", ""},
  11064. {"field2", "longer value for progress tracking test", "", ""},
  11065. {"file1", "file content data for upload progress", "test.txt",
  11066. "text/plain"}};
  11067. auto res = client_call(cli, endpoint, items,
  11068. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11069. progress_values.push_back(current);
  11070. return true;
  11071. });
  11072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11073. EXPECT_EQ(200, res->status);
  11074. EXPECT_FALSE(progress_values.empty());
  11075. }
  11076. TEST(UploadProgressTest, PostMultipartProgress) {
  11077. TestMultipartUploadProgress(
  11078. [](Server &svr) {
  11079. svr.Post("/multipart", [](const Request &req, Response &res) {
  11080. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11081. res.set_content("multipart received", "text/plain");
  11082. });
  11083. },
  11084. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11085. UploadProgress progress_callback) {
  11086. return cli.Post(endpoint, items, progress_callback);
  11087. },
  11088. "/multipart");
  11089. }
  11090. // Helper function for basic download progress tests
  11091. template <typename SetupHandler, typename ClientCall>
  11092. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11093. ClientCall &&client_call, const string &endpoint,
  11094. size_t expected_content_size) {
  11095. Server svr;
  11096. setup_handler(svr);
  11097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11098. auto se = detail::scope_exit([&] {
  11099. svr.stop();
  11100. t.join();
  11101. });
  11102. svr.wait_until_ready();
  11103. Client cli(HOST, PORT);
  11104. vector<uint64_t> progress_values;
  11105. auto res = client_call(cli, endpoint,
  11106. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11107. progress_values.push_back(current);
  11108. return true;
  11109. });
  11110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11111. EXPECT_EQ(200, res->status);
  11112. EXPECT_FALSE(progress_values.empty());
  11113. EXPECT_EQ(expected_content_size, res->body.size());
  11114. }
  11115. TEST(DownloadProgressTest, GetBasic) {
  11116. TestBasicDownloadProgress(
  11117. [](Server &svr) {
  11118. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11119. string content(1000, 'D');
  11120. res.set_content(content, "text/plain");
  11121. });
  11122. },
  11123. [](Client &cli, const string &endpoint,
  11124. DownloadProgress progress_callback) {
  11125. return cli.Get(endpoint, progress_callback);
  11126. },
  11127. "/download", 1000u);
  11128. }
  11129. // Helper function for content receiver download progress tests
  11130. template <typename SetupHandler, typename ClientCall>
  11131. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11132. ClientCall &&client_call,
  11133. const string &endpoint,
  11134. size_t expected_content_size) {
  11135. Server svr;
  11136. setup_handler(svr);
  11137. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11138. auto se = detail::scope_exit([&] {
  11139. svr.stop();
  11140. t.join();
  11141. });
  11142. svr.wait_until_ready();
  11143. Client cli(HOST, PORT);
  11144. vector<uint64_t> progress_values;
  11145. string received_body;
  11146. auto res = client_call(
  11147. cli, endpoint,
  11148. [&](const char *data, size_t data_length) -> bool {
  11149. received_body.append(data, data_length);
  11150. return true;
  11151. },
  11152. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11153. progress_values.push_back(current);
  11154. return true;
  11155. });
  11156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11157. EXPECT_EQ(200, res->status);
  11158. EXPECT_FALSE(progress_values.empty());
  11159. EXPECT_EQ(expected_content_size, received_body.size());
  11160. EXPECT_TRUE(res->body.empty());
  11161. }
  11162. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11163. TestContentReceiverDownloadProgress(
  11164. [](Server &svr) {
  11165. svr.Get("/download-receiver",
  11166. [](const Request & /*req*/, Response &res) {
  11167. string content(2000, 'R');
  11168. res.set_content(content, "text/plain");
  11169. });
  11170. },
  11171. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11172. DownloadProgress progress_callback) {
  11173. return cli.Get(endpoint, content_receiver, progress_callback);
  11174. },
  11175. "/download-receiver", 2000u);
  11176. }
  11177. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11178. // A provider reaching a pass with nothing to hand over - an empty buffer
  11179. // popped off a queue, say - must not be taken to mean the body is finished.
  11180. // It used to end the loop with the terminating chunk unwritten while the
  11181. // server still considered the response complete, so the peer waited for an
  11182. // end that never arrived.
  11183. Server svr;
  11184. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11185. auto step = std::make_shared<int>(0);
  11186. res.set_chunked_content_provider("text/plain",
  11187. [step](size_t /*offset*/, DataSink &sink) {
  11188. switch ((*step)++) {
  11189. case 0: sink.write("", 0); break;
  11190. case 1: sink.write("hello", 5); break;
  11191. default: sink.done(); break;
  11192. }
  11193. return true;
  11194. });
  11195. });
  11196. auto port = svr.bind_to_any_port(HOST);
  11197. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11198. auto listen_se = detail::scope_exit([&] {
  11199. svr.stop();
  11200. listen_thread.join();
  11201. ASSERT_FALSE(svr.is_running());
  11202. });
  11203. svr.wait_until_ready();
  11204. Client cli(HOST, port);
  11205. // Without the fix the body is never terminated, so bound the wait rather
  11206. // than letting the test hang on the default read timeout.
  11207. cli.set_read_timeout(5, 0);
  11208. auto res = cli.Get("/stream");
  11209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11210. EXPECT_EQ(StatusCode::OK_200, res->status);
  11211. EXPECT_EQ("hello", res->body);
  11212. }
  11213. TEST(StreamingTest, NoContentLengthStreaming) {
  11214. Server svr;
  11215. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11216. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11217. if (offset < 6) {
  11218. sink.os << (offset < 3 ? "a" : "b");
  11219. } else {
  11220. sink.done();
  11221. }
  11222. return true;
  11223. });
  11224. });
  11225. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11226. auto listen_se = detail::scope_exit([&] {
  11227. svr.stop();
  11228. listen_thread.join();
  11229. ASSERT_FALSE(svr.is_running());
  11230. });
  11231. svr.wait_until_ready();
  11232. Client client(HOST, PORT);
  11233. auto get_thread = std::thread([&client]() {
  11234. std::string s;
  11235. auto res =
  11236. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11237. s += std::string(data, len);
  11238. return true;
  11239. });
  11240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11241. EXPECT_EQ(StatusCode::OK_200, res->status);
  11242. EXPECT_EQ("aaabbb", s);
  11243. });
  11244. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11245. // Give GET time to get a few messages.
  11246. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11247. }
  11248. TEST(MountTest, Unmount) {
  11249. Server svr;
  11250. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11251. auto se = detail::scope_exit([&] {
  11252. svr.stop();
  11253. listen_thread.join();
  11254. ASSERT_FALSE(svr.is_running());
  11255. });
  11256. svr.wait_until_ready();
  11257. Client cli("localhost", PORT);
  11258. svr.set_mount_point("/mount2", "./www2");
  11259. auto res = cli.Get("/");
  11260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11262. res = cli.Get("/mount2/dir/test.html");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::OK_200, res->status);
  11265. svr.set_mount_point("/", "./www");
  11266. res = cli.Get("/dir/");
  11267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. svr.remove_mount_point("/");
  11270. res = cli.Get("/dir/");
  11271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11273. svr.remove_mount_point("/mount2");
  11274. res = cli.Get("/mount2/dir/test.html");
  11275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11277. }
  11278. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11279. Server svr;
  11280. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11281. svr.Get("/api/hello", [](const Request &, Response &res) {
  11282. res.set_content("api", "text/plain");
  11283. });
  11284. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11285. auto se = detail::scope_exit([&] {
  11286. svr.stop();
  11287. listen_thread.join();
  11288. ASSERT_FALSE(svr.is_running());
  11289. });
  11290. svr.wait_until_ready();
  11291. Client cli(HOST, PORT);
  11292. auto res = cli.Get("/dir/test.html");
  11293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11294. EXPECT_EQ(StatusCode::OK_200, res->status);
  11295. res = cli.Get("/api/hello");
  11296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11297. EXPECT_EQ(StatusCode::OK_200, res->status);
  11298. EXPECT_EQ("api", res->body);
  11299. }
  11300. TEST(MountTest, PathSegmentBoundary) {
  11301. Server svr;
  11302. svr.set_mount_point("/mount2", "./www2");
  11303. svr.set_mount_point("/", "./www");
  11304. auto port = svr.bind_to_any_port(HOST);
  11305. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11306. auto se = detail::scope_exit([&] {
  11307. svr.stop();
  11308. listen_thread.join();
  11309. ASSERT_FALSE(svr.is_running());
  11310. });
  11311. svr.wait_until_ready();
  11312. Client cli(HOST, port);
  11313. auto res = cli.Get("/mount2/dir/test.html");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::OK_200, res->status);
  11316. // "/mount2" must not match part-way through a path segment.
  11317. res = cli.Get("/mount2dir/test.html");
  11318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11320. // A mount point ending in '/' keeps matching every path below it.
  11321. res = cli.Get("/dir/test.html");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. EXPECT_EQ(StatusCode::OK_200, res->status);
  11324. }
  11325. TEST(MountTest, Redicect) {
  11326. Server svr;
  11327. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. listen_thread.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. });
  11333. svr.set_mount_point("/", "./www");
  11334. svr.wait_until_ready();
  11335. Client cli("localhost", PORT);
  11336. auto res = cli.Get("/dir/");
  11337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11338. EXPECT_EQ(StatusCode::OK_200, res->status);
  11339. res = cli.Get("/dir");
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11342. res = cli.Get("/file");
  11343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11344. EXPECT_EQ(StatusCode::OK_200, res->status);
  11345. res = cli.Get("/file/");
  11346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11348. cli.set_follow_location(true);
  11349. res = cli.Get("/dir");
  11350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11351. EXPECT_EQ(StatusCode::OK_200, res->status);
  11352. }
  11353. TEST(MountTest, MultibytesPathName) {
  11354. Server svr;
  11355. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11356. auto se = detail::scope_exit([&] {
  11357. svr.stop();
  11358. listen_thread.join();
  11359. ASSERT_FALSE(svr.is_running());
  11360. });
  11361. svr.set_mount_point("/", "./www");
  11362. svr.wait_until_ready();
  11363. Client cli("localhost", PORT);
  11364. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. EXPECT_EQ(StatusCode::OK_200, res->status);
  11367. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11368. }
  11369. // A mount point serves no path with an empty segment or one ending in '.' or
  11370. // a space, so a guard in the pre-routing handler sees the path of every file
  11371. // that is served
  11372. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11373. Server svr;
  11374. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11375. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11376. if (req.path == "/dir/test.html") {
  11377. res.status = StatusCode::Unauthorized_401;
  11378. return Server::HandlerResponse::Handled;
  11379. }
  11380. return Server::HandlerResponse::Unhandled;
  11381. });
  11382. auto port = svr.bind_to_any_port(HOST);
  11383. ASSERT_LT(0, port);
  11384. thread t = thread([&] { svr.listen_after_bind(); });
  11385. auto se = detail::scope_exit([&] {
  11386. svr.stop();
  11387. t.join();
  11388. ASSERT_FALSE(svr.is_running());
  11389. });
  11390. svr.wait_until_ready();
  11391. Client cli(HOST, port);
  11392. for (auto path :
  11393. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11394. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11395. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11396. "/dir/test.html%3A%3A$DATA"}) {
  11397. SCOPED_TRACE(path);
  11398. auto res = cli.Get(path);
  11399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11401. }
  11402. }
  11403. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11404. Server svr;
  11405. svr.set_mount_point("/", "./www");
  11406. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11407. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11408. auto port = svr.bind_to_any_port(HOST);
  11409. ASSERT_GT(port, 0);
  11410. thread t = thread([&] { svr.listen_after_bind(); });
  11411. auto se = detail::scope_exit([&] {
  11412. svr.stop();
  11413. t.join();
  11414. ASSERT_FALSE(svr.is_running());
  11415. });
  11416. svr.wait_until_ready();
  11417. Client cli(HOST, port);
  11418. auto res = cli.Get("/dir/test.abcde");
  11419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11420. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11421. res = cli.Get("/dir/test.html");
  11422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11423. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11424. }
  11425. #ifdef _WIN32
  11426. // Issue #2435: mmap::open() must succeed even when another handle holds
  11427. // the file open for writing (e.g. an active log file).
  11428. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11429. const char *path = "mmap_concurrent_writer_test.txt";
  11430. const char *content = "hello";
  11431. {
  11432. std::ofstream f(path, std::ios::binary);
  11433. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11434. }
  11435. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11436. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11437. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11438. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11439. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11440. detail::mmap m(path);
  11441. ASSERT_TRUE(m.is_open());
  11442. EXPECT_EQ(strlen(content), m.size());
  11443. char buf[8];
  11444. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11445. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11446. }
  11447. #endif
  11448. #ifndef _WIN32
  11449. // A directory or a device has no size to serve.
  11450. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11451. const char *path = "./mmap_not_regular_test_dir";
  11452. ASSERT_EQ(0, ::mkdir(path, 0755));
  11453. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11454. for (auto p : {path, "/dev/null"}) {
  11455. detail::mmap m(p);
  11456. EXPECT_FALSE(m.is_open()) << p;
  11457. EXPECT_EQ(0U, m.size()) << p;
  11458. }
  11459. Server svr;
  11460. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11461. res.set_file_content("/dev/null");
  11462. });
  11463. auto port = svr.bind_to_any_port(HOST);
  11464. thread t = thread([&] { svr.listen_after_bind(); });
  11465. auto se = detail::scope_exit([&] {
  11466. svr.stop();
  11467. t.join();
  11468. });
  11469. svr.wait_until_ready();
  11470. auto res = Client(HOST, port).Get("/null");
  11471. ASSERT_TRUE(res);
  11472. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11473. }
  11474. #endif
  11475. #ifdef __linux__
  11476. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11477. TEST(MmapTest, FileIsNotMapped) {
  11478. const char *path = "mmap_not_mapped_test.txt";
  11479. {
  11480. std::ofstream f(path, std::ios::binary);
  11481. f << "hello";
  11482. }
  11483. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11484. detail::mmap m(path);
  11485. ASSERT_TRUE(m.is_open());
  11486. std::ifstream maps("/proc/self/maps");
  11487. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11488. std::istreambuf_iterator<char>());
  11489. EXPECT_EQ(std::string::npos, mappings.find(path));
  11490. }
  11491. #endif
  11492. TEST(KeepAliveTest, ReadTimeout) {
  11493. Server svr;
  11494. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11495. std::this_thread::sleep_for(std::chrono::seconds(2));
  11496. res.set_content("a", "text/plain");
  11497. });
  11498. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11499. res.set_content("b", "text/plain");
  11500. });
  11501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11502. auto se = detail::scope_exit([&] {
  11503. svr.stop();
  11504. listen_thread.join();
  11505. ASSERT_FALSE(svr.is_running());
  11506. });
  11507. svr.wait_until_ready();
  11508. Client cli("localhost", PORT);
  11509. cli.set_keep_alive(true);
  11510. cli.set_read_timeout(std::chrono::seconds(1));
  11511. auto resa = cli.Get("/a");
  11512. ASSERT_FALSE(resa);
  11513. EXPECT_EQ(Error::Read, resa.error());
  11514. auto resb = cli.Get("/b");
  11515. ASSERT_TRUE(resb);
  11516. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11517. EXPECT_EQ("b", resb->body);
  11518. }
  11519. TEST(KeepAliveTest, MaxCount) {
  11520. size_t keep_alive_max_count = 3;
  11521. Server svr;
  11522. svr.set_keep_alive_max_count(keep_alive_max_count);
  11523. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11524. res.set_content("Hello World!", "text/plain");
  11525. });
  11526. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11527. auto se = detail::scope_exit([&] {
  11528. svr.stop();
  11529. listen_thread.join();
  11530. ASSERT_FALSE(svr.is_running());
  11531. });
  11532. svr.wait_until_ready();
  11533. Client cli(HOST, PORT);
  11534. cli.set_keep_alive(true);
  11535. for (size_t i = 0; i < 5; i++) {
  11536. auto result = cli.Get("/hi");
  11537. ASSERT_TRUE(result);
  11538. EXPECT_EQ(StatusCode::OK_200, result->status);
  11539. if (i == keep_alive_max_count - 1) {
  11540. EXPECT_EQ("close", result->get_header_value("Connection"));
  11541. } else {
  11542. EXPECT_FALSE(result->has_header("Connection"));
  11543. }
  11544. }
  11545. }
  11546. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11547. // can pull the next one into the server's buffer. The server must serve it
  11548. // without waiting for the socket to become readable again. The keep-alive
  11549. // timeout outlasts the client's read timeout, so a request left waiting for it
  11550. // shows up as a missing response.
  11551. static void serve_pipelining_routes(Server &svr,
  11552. const std::function<void(int)> &client) {
  11553. svr.set_keep_alive_timeout(5);
  11554. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11555. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11556. });
  11557. svr.Post("/echo", [](const Request &req, Response &res) {
  11558. res.set_content("echo " + req.body, "text/plain");
  11559. });
  11560. auto port = svr.bind_to_any_port(HOST);
  11561. thread t = thread([&] { svr.listen_after_bind(); });
  11562. auto se = detail::scope_exit([&] {
  11563. svr.stop();
  11564. t.join();
  11565. });
  11566. svr.wait_until_ready();
  11567. client(port);
  11568. }
  11569. static std::string
  11570. send_pipelined_requests(const std::vector<std::string> &parts) {
  11571. Server svr;
  11572. std::string res;
  11573. serve_pipelining_routes(svr, [&](int port) {
  11574. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11575. });
  11576. return res;
  11577. }
  11578. static void expect_in_order(const std::string &res,
  11579. const std::vector<std::string> &bodies) {
  11580. size_t pos = 0;
  11581. for (const auto &body : bodies) {
  11582. pos = res.find(body, pos);
  11583. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11584. pos += body.size();
  11585. }
  11586. }
  11587. TEST(KeepAliveTest, PipelinedRequests) {
  11588. auto res = send_pipelined_requests(
  11589. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11590. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11591. "Content-Length: 4\r\n\r\nbody"
  11592. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11593. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11594. }
  11595. // The second request starts in the server's buffer and ends on the socket.
  11596. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11597. auto res =
  11598. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11599. "GET /hi/2 HTTP/1.1\r\nHo",
  11600. "st: localhost\r\nConnection: close\r\n\r\n"});
  11601. expect_in_order(res, {"hi 1", "hi 2"});
  11602. }
  11603. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11604. // CRLF after a body does not turn into a 400 for the next request.
  11605. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11606. auto res = send_pipelined_requests(
  11607. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11608. "Content-Length: 4\r\n\r\nbody\r\n"
  11609. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11610. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11611. expect_in_order(res, {"echo body", "hi 2"});
  11612. }
  11613. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11614. // must not be served as the next request.
  11615. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11616. auto res = send_pipelined_requests(
  11617. {"INVALID REQUEST LINE\r\n\r\n"
  11618. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11619. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11620. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11621. }
  11622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11623. // Over TLS, the next request is held by the TLS library as already decrypted
  11624. // data rather than on the socket.
  11625. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11627. std::string res;
  11628. serve_pipelining_routes(svr, [&](int port) {
  11629. // One part, so all three requests arrive in one TLS record
  11630. EXPECT_TRUE(send_ssl_request_in_parts(
  11631. 2,
  11632. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11633. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11634. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11635. &res, port));
  11636. });
  11637. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11638. }
  11639. #endif
  11640. TEST(KeepAliveTest, Issue1041) {
  11641. Server svr;
  11642. svr.set_keep_alive_timeout(3);
  11643. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11644. res.set_content("Hello World!", "text/plain");
  11645. });
  11646. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11647. auto se = detail::scope_exit([&] {
  11648. svr.stop();
  11649. listen_thread.join();
  11650. ASSERT_FALSE(svr.is_running());
  11651. });
  11652. svr.wait_until_ready();
  11653. Client cli(HOST, PORT);
  11654. cli.set_keep_alive(true);
  11655. auto result = cli.Get("/hi");
  11656. ASSERT_TRUE(result);
  11657. EXPECT_EQ(StatusCode::OK_200, result->status);
  11658. std::this_thread::sleep_for(std::chrono::seconds(5));
  11659. result = cli.Get("/hi");
  11660. ASSERT_TRUE(result);
  11661. EXPECT_EQ(StatusCode::OK_200, result->status);
  11662. }
  11663. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11664. Server svr;
  11665. svr.set_keep_alive_max_count(0);
  11666. std::set<int> remote_ports;
  11667. svr.Get("/hi", [&](const Request &req, Response &res) {
  11668. remote_ports.insert(req.remote_port);
  11669. res.set_content("hi", "text/plain");
  11670. });
  11671. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11672. auto se = detail::scope_exit([&] {
  11673. svr.stop();
  11674. listen_thread.join();
  11675. ASSERT_FALSE(svr.is_running());
  11676. });
  11677. svr.wait_until_ready();
  11678. Client cli(HOST, PORT);
  11679. cli.set_keep_alive(true);
  11680. for (int i = 0; i < 3; i++) {
  11681. auto res = cli.Get("/hi");
  11682. ASSERT_TRUE(res);
  11683. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11684. }
  11685. // All three over one connection
  11686. EXPECT_EQ(1u, remote_ports.size());
  11687. }
  11688. // Forward declaration (see the base64_encode note).
  11689. namespace httplib {
  11690. namespace detail {
  11691. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11692. } // namespace detail
  11693. } // namespace httplib
  11694. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11695. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11696. #ifndef _WIN32
  11697. signal(SIGPIPE, SIG_IGN);
  11698. #endif
  11699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11700. ASSERT_NE(INVALID_SOCKET, srv);
  11701. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11702. default_socket_options(srv);
  11703. sockaddr_in addr{};
  11704. addr.sin_family = AF_INET;
  11705. addr.sin_port = 0;
  11706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11707. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11708. ASSERT_EQ(0, ::listen(srv, 2));
  11709. socklen_t addr_len = sizeof(addr);
  11710. ASSERT_EQ(0,
  11711. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11712. auto port = ntohs(addr.sin_port);
  11713. struct Peer {
  11714. socket_t sock = INVALID_SOCKET;
  11715. #ifdef CPPHTTPLIB_SSL_ENABLED
  11716. tls::session_t session = nullptr;
  11717. #endif
  11718. };
  11719. #ifdef CPPHTTPLIB_SSL_ENABLED
  11720. tls::ctx_t ctx = nullptr;
  11721. if (use_tls) {
  11722. ctx = tls::create_server_context();
  11723. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11724. nullptr);
  11725. }
  11726. auto ctx_se = detail::scope_exit([&] {
  11727. if (ctx) { tls::free_context(ctx); }
  11728. });
  11729. #endif
  11730. auto close_peer = [](Peer &peer) {
  11731. #ifdef CPPHTTPLIB_SSL_ENABLED
  11732. if (peer.session) { tls::free_session(peer.session); }
  11733. #endif
  11734. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11735. };
  11736. auto accept_peer = [&]() {
  11737. Peer peer;
  11738. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11739. peer.sock = ::accept(srv, nullptr, nullptr);
  11740. if (peer.sock == INVALID_SOCKET) { return peer; }
  11741. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11742. #ifdef CPPHTTPLIB_SSL_ENABLED
  11743. if (use_tls) {
  11744. peer.session = tls::create_session(ctx, peer.sock);
  11745. tls::TlsError err;
  11746. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11747. nullptr)) {
  11748. close_peer(peer);
  11749. return Peer();
  11750. }
  11751. }
  11752. #endif
  11753. return peer;
  11754. };
  11755. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11756. #ifdef CPPHTTPLIB_SSL_ENABLED
  11757. tls::TlsError err;
  11758. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11759. #endif
  11760. return detail::read_socket(peer.sock, buf, len, 0);
  11761. };
  11762. auto read_head = [&](const Peer &peer) {
  11763. std::string head;
  11764. char buf[1024];
  11765. while (head.find("\r\n\r\n") == std::string::npos) {
  11766. auto n = read_some(peer, buf, sizeof(buf));
  11767. if (n <= 0) { break; }
  11768. head.append(buf, static_cast<size_t>(n));
  11769. }
  11770. };
  11771. auto send_text = [](const Peer &peer, const std::string &text) {
  11772. #ifdef CPPHTTPLIB_SSL_ENABLED
  11773. tls::TlsError err;
  11774. if (peer.session) {
  11775. tls::write(peer.session, text.data(), text.size(), err);
  11776. return;
  11777. }
  11778. #endif
  11779. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11780. };
  11781. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11782. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11783. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11784. // Sent once the first response is read, so that it lands on an idle socket
  11785. std::promise<void> first_response_read;
  11786. auto first_response_read_future = first_response_read.get_future();
  11787. auto server_thread = std::thread([&] {
  11788. auto peer1 = accept_peer();
  11789. if (peer1.sock == INVALID_SOCKET) { return; }
  11790. read_head(peer1);
  11791. if (same_write) {
  11792. send_text(peer1, first + stray);
  11793. } else {
  11794. send_text(peer1, first);
  11795. first_response_read_future.wait_for(std::chrono::seconds(5));
  11796. send_text(peer1, stray);
  11797. }
  11798. // peer1 stays open, so only the unread data can tell the client
  11799. auto peer2 = accept_peer();
  11800. if (peer2.sock != INVALID_SOCKET) {
  11801. read_head(peer2);
  11802. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11803. "Connection: close\r\n\r\nsecond");
  11804. close_peer(peer2);
  11805. }
  11806. close_peer(peer1);
  11807. });
  11808. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11809. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11810. std::to_string(port));
  11811. #ifdef CPPHTTPLIB_SSL_ENABLED
  11812. cli.enable_server_certificate_verification(false);
  11813. #endif
  11814. cli.set_keep_alive(true);
  11815. cli.set_read_timeout(5, 0);
  11816. auto res = cli.Get("/1");
  11817. first_response_read.set_value();
  11818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11819. EXPECT_EQ("first", res->body);
  11820. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11821. res = cli.Get("/2");
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. EXPECT_EQ(StatusCode::OK_200, res->status);
  11824. EXPECT_EQ("second", res->body);
  11825. }
  11826. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11827. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11828. }
  11829. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11830. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11831. }
  11832. #ifdef CPPHTTPLIB_SSL_ENABLED
  11833. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11834. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11835. }
  11836. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11837. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11838. }
  11839. #endif
  11840. TEST(KeepAliveTest, Issue1959) {
  11841. Server svr;
  11842. svr.set_keep_alive_timeout(5);
  11843. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11844. res.set_content("a", "text/plain");
  11845. });
  11846. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11847. auto se = detail::scope_exit([&] {
  11848. if (!svr.is_running()) return;
  11849. svr.stop();
  11850. listen_thread.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. Client cli("localhost", PORT);
  11855. cli.set_keep_alive(true);
  11856. using namespace std::chrono;
  11857. auto start = steady_clock::now();
  11858. cli.Get("/a");
  11859. svr.stop();
  11860. listen_thread.join();
  11861. auto end = steady_clock::now();
  11862. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11863. EXPECT_LT(elapsed, 5000);
  11864. }
  11865. #ifdef CPPHTTPLIB_SSL_ENABLED
  11866. TEST(KeepAliveTest, SSLClientReconnection) {
  11867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11868. ASSERT_TRUE(svr.is_valid());
  11869. svr.set_keep_alive_timeout(1);
  11870. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11871. res.set_content("Hello World!", "text/plain");
  11872. });
  11873. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11874. auto se = detail::scope_exit([&] {
  11875. svr.stop();
  11876. listen_thread.join();
  11877. ASSERT_FALSE(svr.is_running());
  11878. });
  11879. svr.wait_until_ready();
  11880. SSLClient cli(HOST, PORT);
  11881. cli.enable_server_certificate_verification(false);
  11882. cli.set_keep_alive(true);
  11883. auto result = cli.Get("/hi");
  11884. ASSERT_TRUE(result);
  11885. EXPECT_EQ(StatusCode::OK_200, result->status);
  11886. result = cli.Get("/hi");
  11887. ASSERT_TRUE(result);
  11888. EXPECT_EQ(StatusCode::OK_200, result->status);
  11889. std::this_thread::sleep_for(std::chrono::seconds(2));
  11890. // Recoonect
  11891. result = cli.Get("/hi");
  11892. ASSERT_TRUE(result);
  11893. EXPECT_EQ(StatusCode::OK_200, result->status);
  11894. result = cli.Get("/hi");
  11895. ASSERT_TRUE(result);
  11896. EXPECT_EQ(StatusCode::OK_200, result->status);
  11897. }
  11898. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11900. ASSERT_TRUE(svr.is_valid());
  11901. svr.set_keep_alive_timeout(1);
  11902. std::string content = "reconnect";
  11903. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11904. res.set_content("Hello World!", "text/plain");
  11905. });
  11906. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11907. auto se = detail::scope_exit([&] {
  11908. svr.stop();
  11909. listen_thread.join();
  11910. ASSERT_FALSE(svr.is_running());
  11911. });
  11912. svr.wait_until_ready();
  11913. SSLClient cli(HOST, PORT);
  11914. cli.enable_server_certificate_verification(false);
  11915. cli.set_keep_alive(true);
  11916. auto result = cli.Post(
  11917. "/hi", content.size(),
  11918. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11919. sink.write(content.c_str(), content.size());
  11920. return true;
  11921. },
  11922. "text/plain");
  11923. ASSERT_TRUE(result);
  11924. EXPECT_EQ(200, result->status);
  11925. std::this_thread::sleep_for(std::chrono::seconds(2));
  11926. // Recoonect
  11927. result = cli.Post(
  11928. "/hi", content.size(),
  11929. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11930. sink.write(content.c_str(), content.size());
  11931. return true;
  11932. },
  11933. "text/plain");
  11934. ASSERT_TRUE(result);
  11935. EXPECT_EQ(200, result->status);
  11936. result = cli.Post(
  11937. "/hi", content.size(),
  11938. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11939. sink.write(content.c_str(), content.size());
  11940. return true;
  11941. },
  11942. "text/plain");
  11943. ASSERT_TRUE(result);
  11944. EXPECT_EQ(200, result->status);
  11945. }
  11946. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11947. using namespace httplib::tls;
  11948. {
  11949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11950. ASSERT_TRUE(svr.is_valid());
  11951. svr.Get("/sni", [&](const Request &req, Response &res) {
  11952. std::string expected = req.sni();
  11953. EXPECT_EQ(expected, req.get_param_value("expected"));
  11954. res.set_content("ok", "text/plain");
  11955. });
  11956. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11957. auto se = detail::scope_exit([&] {
  11958. svr.stop();
  11959. listen_thread.join();
  11960. ASSERT_FALSE(svr.is_running());
  11961. });
  11962. svr.wait_until_ready();
  11963. {
  11964. SSLClient cli("localhost", PORT);
  11965. cli.enable_server_certificate_verification(false);
  11966. auto res = cli.Get("/sni?expected=localhost");
  11967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11968. }
  11969. {
  11970. SSLClient cli("::1", PORT);
  11971. cli.enable_server_certificate_verification(false);
  11972. auto res = cli.Get("/sni?expected=");
  11973. // NOTE: This may fail if the server is listening on IPv4 only
  11974. // (e.g., when localhost resolves to 127.0.0.1 only)
  11975. if (res) {
  11976. EXPECT_EQ(StatusCode::OK_200, res->status);
  11977. } else {
  11978. EXPECT_EQ(Error::Connection, res.error());
  11979. }
  11980. }
  11981. }
  11982. }
  11983. // The SNI of a failed handshake does not reach the next connection that the
  11984. // same worker thread serves
  11985. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11987. ASSERT_TRUE(svr.is_valid());
  11988. svr.new_task_queue = [] { return new ThreadPool(1); };
  11989. svr.Get("/sni", [](const Request &req, Response &res) {
  11990. res.set_content(req.sni(), "text/plain");
  11991. });
  11992. auto port = svr.bind_to_any_port("127.0.0.1");
  11993. ASSERT_LT(0, port);
  11994. thread t = thread([&] { svr.listen_after_bind(); });
  11995. auto se = detail::scope_exit([&] {
  11996. svr.stop();
  11997. t.join();
  11998. ASSERT_FALSE(svr.is_running());
  11999. });
  12000. svr.wait_until_ready();
  12001. {
  12002. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12003. SSLClient cli("localhost", port);
  12004. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12005. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12006. auto res = cli.Get("/sni");
  12007. ASSERT_FALSE(res);
  12008. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12009. }
  12010. // An IP host sends no SNI (RFC 6066)
  12011. SSLClient cli("127.0.0.1", port);
  12012. cli.enable_server_certificate_verification(false);
  12013. auto res = cli.Get("/sni");
  12014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12015. EXPECT_EQ("", res->body);
  12016. }
  12017. #endif
  12018. TEST(ClientProblemDetectionTest, ContentProvider) {
  12019. Server svr;
  12020. size_t content_length = 1024 * 1024;
  12021. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12022. res.set_content_provider(
  12023. content_length, "text/plain",
  12024. [&](size_t offset, size_t length, DataSink &sink) {
  12025. auto out_len = std::min(length, static_cast<size_t>(1024));
  12026. std::string out(out_len, '@');
  12027. sink.write(out.data(), out_len);
  12028. return offset < 4096;
  12029. },
  12030. [](bool success) { ASSERT_FALSE(success); });
  12031. });
  12032. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12033. res.set_content_provider(
  12034. 0, "text/plain",
  12035. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12036. EXPECT_TRUE(false);
  12037. return true;
  12038. },
  12039. [](bool success) { ASSERT_FALSE(success); });
  12040. });
  12041. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. listen_thread.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. });
  12047. svr.wait_until_ready();
  12048. Client cli("localhost", PORT);
  12049. {
  12050. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12051. size_t /*data_length*/) { return false; });
  12052. ASSERT_FALSE(res);
  12053. }
  12054. {
  12055. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12056. size_t /*data_length*/) { return false; });
  12057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12058. }
  12059. }
  12060. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12061. // A provider that reports success without writing anything and without
  12062. // calling done() used to be handed the same offset and length again on every
  12063. // pass, so it spun for as long as the peer stayed connected.
  12064. Server svr;
  12065. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12066. res.set_content("ok", "text/plain");
  12067. });
  12068. auto port = svr.bind_to_any_port(HOST);
  12069. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12070. auto se = detail::scope_exit([&] {
  12071. svr.stop();
  12072. listen_thread.join();
  12073. ASSERT_FALSE(svr.is_running());
  12074. });
  12075. svr.wait_until_ready();
  12076. std::atomic<int> call_count{0};
  12077. Client cli(HOST, port);
  12078. auto res = cli.Post(
  12079. "/", 1024,
  12080. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12081. // Give up after enough passes to show the spin, so that losing the
  12082. // check below fails this test instead of hanging it.
  12083. return ++call_count < 100;
  12084. },
  12085. "text/plain");
  12086. ASSERT_FALSE(res);
  12087. EXPECT_EQ(Error::Write, res.error());
  12088. EXPECT_EQ(1, call_count.load());
  12089. }
  12090. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12091. // A writer only has to assign `write`. The other three used to be left as
  12092. // empty std::functions, so a provider calling one threw
  12093. // std::bad_function_call out of the thread running it and took the whole
  12094. // process down.
  12095. DataSink sink;
  12096. std::string written;
  12097. sink.write = [&](const char *data, size_t data_len) {
  12098. written.append(data, data_len);
  12099. return true;
  12100. };
  12101. EXPECT_TRUE(sink.is_writable());
  12102. sink.done();
  12103. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12104. EXPECT_TRUE(written.empty());
  12105. }
  12106. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12107. // A sink that cannot carry trailers still has to finish.
  12108. DataSink sink;
  12109. auto done_count = 0;
  12110. sink.done = [&]() { done_count++; };
  12111. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12112. EXPECT_EQ(1, done_count);
  12113. }
  12114. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12115. Server svr;
  12116. const std::string body(4096, 'x');
  12117. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12118. res.set_content_provider(body.size(), "text/plain",
  12119. [&](size_t offset, size_t length, DataSink &sink) {
  12120. sink.write(body.data() + offset, length);
  12121. sink.done();
  12122. return true;
  12123. });
  12124. });
  12125. auto port = svr.bind_to_any_port(HOST);
  12126. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12127. auto se = detail::scope_exit([&] {
  12128. svr.stop();
  12129. listen_thread.join();
  12130. ASSERT_FALSE(svr.is_running());
  12131. });
  12132. svr.wait_until_ready();
  12133. Client cli(HOST, port);
  12134. auto res = cli.Get("/");
  12135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12136. EXPECT_EQ(StatusCode::OK_200, res->status);
  12137. EXPECT_EQ(body, res->body);
  12138. }
  12139. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12140. Server svr;
  12141. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12142. res.set_content_provider(
  12143. 1024, "text/plain",
  12144. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12145. sink.write("hello", 5);
  12146. sink.done(); // short of the 1024 bytes the response promised
  12147. return true;
  12148. });
  12149. });
  12150. auto port = svr.bind_to_any_port(HOST);
  12151. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12152. auto se = detail::scope_exit([&] {
  12153. svr.stop();
  12154. listen_thread.join();
  12155. ASSERT_FALSE(svr.is_running());
  12156. });
  12157. svr.wait_until_ready();
  12158. Client cli(HOST, port);
  12159. cli.set_read_timeout(5, 0);
  12160. // The response is short of its Content-Length, so the client cannot read a
  12161. // complete body. What matters is that this returns at all: a no-op done()
  12162. // would leave the writer looping over a provider that never makes progress.
  12163. auto res = cli.Get("/");
  12164. EXPECT_FALSE(res);
  12165. }
  12166. // Read as the next response by a peer that sees it after a framed body.
  12167. static const std::string smuggled_response =
  12168. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12169. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12170. Server svr;
  12171. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12172. res.set_content_provider(
  12173. 5, "text/plain",
  12174. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12175. auto data = "AAAAA" + smuggled_response;
  12176. sink.write(data.data(), data.size());
  12177. return true;
  12178. });
  12179. });
  12180. thread t = thread([&] { svr.listen(HOST, PORT); });
  12181. auto se = detail::scope_exit([&] {
  12182. svr.stop();
  12183. t.join();
  12184. ASSERT_FALSE(svr.is_running());
  12185. });
  12186. svr.wait_until_ready();
  12187. std::string resp;
  12188. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12189. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12190. resp.clear();
  12191. ASSERT_TRUE(send_request(
  12192. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12193. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12194. }
  12195. TEST(NoContentTest, BodyIsNotSent) {
  12196. Server svr;
  12197. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12198. res.status = StatusCode::NoContent_204;
  12199. res.set_content(smuggled_response, "text/plain");
  12200. });
  12201. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12202. res.status = StatusCode::NotModified_304;
  12203. res.set_chunked_content_provider(
  12204. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12205. sink.write(smuggled_response.data(), smuggled_response.size());
  12206. sink.done();
  12207. return true;
  12208. });
  12209. });
  12210. thread t = thread([&] { svr.listen(HOST, PORT); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. t.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. });
  12216. svr.wait_until_ready();
  12217. for (auto path : {"/204", "/304"}) {
  12218. std::string resp;
  12219. ASSERT_TRUE(send_request(
  12220. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12221. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12222. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12223. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12224. }
  12225. }
  12226. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12227. Server svr;
  12228. std::atomic<bool> smuggled(false);
  12229. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12230. res.set_content("ok", "text/plain");
  12231. });
  12232. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12233. smuggled = true;
  12234. });
  12235. auto port = svr.bind_to_any_port(HOST);
  12236. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. listen_thread.join();
  12240. ASSERT_FALSE(svr.is_running());
  12241. });
  12242. svr.wait_until_ready();
  12243. // What follows the body would be read as the next request.
  12244. Client cli(HOST, port);
  12245. auto res = cli.Post(
  12246. "/", 5,
  12247. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12248. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12249. sink.write(data.data(), data.size());
  12250. return true;
  12251. },
  12252. "text/plain");
  12253. ASSERT_FALSE(res);
  12254. EXPECT_EQ(Error::Write, res.error());
  12255. EXPECT_FALSE(smuggled);
  12256. }
  12257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12258. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12259. // The compressed path builds the whole body before connecting, so this
  12260. // fails client-side and never reaches a server.
  12261. Client cli(HOST, PORT);
  12262. cli.set_compress(true);
  12263. auto res = cli.Post(
  12264. "/", 1024,
  12265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12266. sink.write("hello", 5);
  12267. sink.done(); // short of the 1024 bytes the request announced
  12268. return true;
  12269. },
  12270. "text/plain");
  12271. ASSERT_FALSE(res);
  12272. EXPECT_EQ(Error::Write, res.error());
  12273. }
  12274. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12275. Server svr;
  12276. std::string received;
  12277. size_t content_length_count = 0;
  12278. bool has_transfer_encoding = true;
  12279. svr.Post("/echo", [&](const Request &req, Response &res) {
  12280. received = req.body;
  12281. content_length_count = req.get_header_value_count("Content-Length");
  12282. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12283. res.set_content("ok", "text/plain");
  12284. });
  12285. svr.Get("/next", [](const Request &, Response &res) {
  12286. res.set_content("next", "text/plain");
  12287. });
  12288. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12289. auto se = detail::scope_exit([&] {
  12290. svr.stop();
  12291. listen_thread.join();
  12292. ASSERT_FALSE(svr.is_running());
  12293. });
  12294. svr.wait_until_ready();
  12295. Client cli(HOST, PORT);
  12296. cli.set_keep_alive(true);
  12297. cli.set_compress(true);
  12298. const std::string body = "hello world";
  12299. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12300. auto res = cli.Post("/echo", headers, body, "text/plain");
  12301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12302. EXPECT_EQ(StatusCode::OK_200, res->status);
  12303. EXPECT_EQ(body, received);
  12304. EXPECT_EQ(1u, content_length_count);
  12305. EXPECT_FALSE(has_transfer_encoding);
  12306. // The rest of a truncated body would be read as this request
  12307. auto res2 = cli.Get("/next");
  12308. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12309. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12310. EXPECT_EQ("next", res2->body);
  12311. }
  12312. #endif
  12313. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12314. Server svr;
  12315. std::string received;
  12316. size_t content_length_count = 1;
  12317. bool has_transfer_encoding = false;
  12318. svr.Post("/echo", [&](const Request &req, Response &res) {
  12319. received = req.body;
  12320. content_length_count = req.get_header_value_count("Content-Length");
  12321. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12322. res.set_content("ok", "text/plain");
  12323. });
  12324. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12325. auto se = detail::scope_exit([&] {
  12326. svr.stop();
  12327. listen_thread.join();
  12328. ASSERT_FALSE(svr.is_running());
  12329. });
  12330. svr.wait_until_ready();
  12331. Client cli(HOST, PORT);
  12332. cli.set_keep_alive(true);
  12333. const std::string body = "hello world";
  12334. Headers headers = {{"Content-Length", "5"}};
  12335. auto res = cli.Post(
  12336. "/echo", headers,
  12337. [&](size_t /*offset*/, DataSink &sink) {
  12338. sink.write(body.data(), body.size());
  12339. sink.done();
  12340. return true;
  12341. },
  12342. "text/plain");
  12343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12344. EXPECT_EQ(StatusCode::OK_200, res->status);
  12345. EXPECT_EQ(body, received);
  12346. EXPECT_EQ(0u, content_length_count);
  12347. EXPECT_TRUE(has_transfer_encoding);
  12348. }
  12349. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12350. Server svr;
  12351. svr.set_error_handler([](Request const &, Response &res) -> void {
  12352. res.set_chunked_content_provider(
  12353. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12354. sink.os << "hello";
  12355. sink.os << "world";
  12356. sink.done();
  12357. return true;
  12358. });
  12359. });
  12360. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12361. auto se = detail::scope_exit([&] {
  12362. svr.stop();
  12363. listen_thread.join();
  12364. ASSERT_FALSE(svr.is_running());
  12365. });
  12366. svr.wait_until_ready();
  12367. Client cli("localhost", PORT);
  12368. auto res = cli.Get("/");
  12369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12371. EXPECT_EQ("helloworld", res->body);
  12372. }
  12373. // A body set after a content provider must replace it, not be sent through it.
  12374. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12375. Server svr;
  12376. svr.set_mount_point("/", "./www");
  12377. svr.set_file_request_handler([](const Request &req, Response &res) {
  12378. if (req.path == "/dir/test.html") {
  12379. res.status = StatusCode::Forbidden_403;
  12380. res.set_content(std::string(5000, 'D'), "text/plain");
  12381. } else if (req.path == "/file") {
  12382. res.status = StatusCode::Forbidden_403;
  12383. res.body = "Denied";
  12384. }
  12385. });
  12386. auto port = svr.bind_to_any_port(HOST);
  12387. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12388. auto se = detail::scope_exit([&] {
  12389. svr.stop();
  12390. t.join();
  12391. ASSERT_FALSE(svr.is_running());
  12392. });
  12393. svr.wait_until_ready();
  12394. Client cli(HOST, port);
  12395. {
  12396. auto res = cli.Get("/dir/test.html");
  12397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12398. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12399. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12400. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12401. }
  12402. {
  12403. auto res = cli.Get("/file");
  12404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12405. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12406. EXPECT_EQ("Denied", res->body);
  12407. }
  12408. {
  12409. auto res = cli.Get("/dir/index.html");
  12410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12411. EXPECT_EQ(StatusCode::OK_200, res->status);
  12412. EXPECT_EQ(0U, res->body.find("<html>"));
  12413. }
  12414. }
  12415. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12416. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12417. Server svr;
  12418. std::vector<bool> released;
  12419. std::mutex released_mutex;
  12420. auto releaser = [&](bool success) {
  12421. std::lock_guard<std::mutex> guard(released_mutex);
  12422. released.push_back(success);
  12423. };
  12424. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12425. return sink.write(&"hello"[offset], length);
  12426. };
  12427. svr.Get("/sized", [&](const Request &, Response &res) {
  12428. res.status = StatusCode::NotFound_404;
  12429. res.set_content_provider(5, "text/plain", provider, releaser);
  12430. });
  12431. svr.Get("/chunked", [&](const Request &, Response &res) {
  12432. res.status = StatusCode::ServiceUnavailable_503;
  12433. res.set_chunked_content_provider(
  12434. "text/plain",
  12435. [](size_t, DataSink &sink) {
  12436. sink.os << "chunk";
  12437. sink.done();
  12438. return true;
  12439. },
  12440. releaser);
  12441. });
  12442. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12443. res.set_content_provider(5, "text/plain", provider, releaser);
  12444. throw std::runtime_error("after the provider");
  12445. });
  12446. svr.set_error_handler([](const Request &req, Response &res) {
  12447. // Leave the exception handler's content to it.
  12448. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12449. res.set_content(std::string(1000, 'E'), "text/html");
  12450. return Server::HandlerResponse::Handled;
  12451. });
  12452. svr.set_exception_handler(
  12453. [](const Request &, Response &res, std::exception_ptr) {
  12454. res.status = StatusCode::InternalServerError_500;
  12455. res.set_content(std::string(1000, 'X'), "text/html");
  12456. });
  12457. auto port = svr.bind_to_any_port(HOST);
  12458. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12459. auto se = detail::scope_exit([&] {
  12460. svr.stop();
  12461. t.join();
  12462. ASSERT_FALSE(svr.is_running());
  12463. });
  12464. svr.wait_until_ready();
  12465. Client cli(HOST, port);
  12466. {
  12467. auto res = cli.Get("/sized");
  12468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12470. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12472. }
  12473. {
  12474. auto res = cli.Get("/chunked");
  12475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12477. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12478. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12479. }
  12480. {
  12481. auto res = cli.Get("/throw");
  12482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12483. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12484. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12485. }
  12486. std::lock_guard<std::mutex> guard(released_mutex);
  12487. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12488. }
  12489. #endif
  12490. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12491. Server svr;
  12492. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12493. return sink.write(&"abc"[offset], length);
  12494. };
  12495. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12496. res.set_file_content("./www/dir/test.html");
  12497. res.set_content("body", "text/plain");
  12498. });
  12499. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12500. res.set_content(std::string(100, 'B'), "text/plain");
  12501. res.set_file_content("./www/dir/test.html");
  12502. });
  12503. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12504. res.set_content(std::string(100, 'B'), "text/plain");
  12505. res.set_content_provider(3, "text/x-provider", abc);
  12506. });
  12507. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12508. res.set_content_provider(3, "text/x-provider", abc);
  12509. res.set_content(std::string(100, 'B'), "text/plain");
  12510. });
  12511. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12512. res.set_content_provider(3, "text/x-provider", abc);
  12513. res.set_file_content("./www/dir/test.html", "text/x-file");
  12514. });
  12515. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12516. res.set_file_content("./www/dir/test.html");
  12517. res.set_header("Content-Type", "text/x-handler");
  12518. });
  12519. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12520. res.set_content_provider(3, "text/plain", abc);
  12521. res.body = "direct";
  12522. });
  12523. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12524. res.set_file_content("./www/dir/test.html");
  12525. res.body = "direct";
  12526. });
  12527. auto port = svr.bind_to_any_port(HOST);
  12528. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12529. auto se = detail::scope_exit([&] {
  12530. svr.stop();
  12531. t.join();
  12532. ASSERT_FALSE(svr.is_running());
  12533. });
  12534. svr.wait_until_ready();
  12535. Client cli(HOST, port);
  12536. auto expect_body = [&](const char *path, const std::string &body,
  12537. const std::string &type) {
  12538. // Uncompressed, so Content-Length can be compared with the body.
  12539. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12540. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12541. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12542. EXPECT_EQ(body, res->body) << path;
  12543. EXPECT_EQ(std::to_string(body.size()),
  12544. res->get_header_value("Content-Length"))
  12545. << path;
  12546. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12547. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12548. };
  12549. expect_body("/file-then-body", "body", "text/plain");
  12550. expect_body("/body-then-file", "test.html", "text/html");
  12551. expect_body("/body-then-provider", "abc", "text/x-provider");
  12552. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12553. expect_body("/provider-then-file", "test.html", "text/x-file");
  12554. expect_body("/file-then-header", "test.html", "text/x-handler");
  12555. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12556. expect_body("/file-then-direct-body", "direct", "text/plain");
  12557. // Ranges are checked against the body, not the dropped provider.
  12558. {
  12559. auto res = cli.Get("/provider-then-direct-body",
  12560. Headers{{make_range_header({{1, 2}})}});
  12561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12562. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12563. EXPECT_EQ("ir", res->body);
  12564. }
  12565. {
  12566. auto res = cli.Get("/file-then-direct-body",
  12567. Headers{{make_range_header({{7, 8}})}});
  12568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12569. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12570. }
  12571. }
  12572. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12573. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12574. const char *path = "./truncated_while_served.txt";
  12575. const size_t size = 32 * 1024 * 1024;
  12576. {
  12577. std::ofstream f(path, std::ios::binary);
  12578. f << std::string(size, 'x');
  12579. }
  12580. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12581. // Over TLS, where the bytes are encrypted in this process rather than
  12582. // copied by send().
  12583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12584. svr.Get("/file", [&](const Request &, Response &res) {
  12585. res.set_file_content(path, "text/plain");
  12586. });
  12587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12588. auto se = detail::scope_exit([&] {
  12589. svr.stop();
  12590. thread.join();
  12591. ASSERT_FALSE(svr.is_running());
  12592. });
  12593. svr.wait_until_ready();
  12594. // The file shrinks once the first bytes are in, as a rewrite in place
  12595. // would, and reading the mapping past its new end used to raise SIGBUS.
  12596. SSLClient cli(HOST, PORT);
  12597. cli.enable_server_certificate_verification(false);
  12598. size_t received = 0;
  12599. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12600. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12601. received += len;
  12602. return true;
  12603. });
  12604. EXPECT_FALSE(res);
  12605. EXPECT_LT(received, size);
  12606. }
  12607. #endif
  12608. // Forward declaration (see the base64_encode note).
  12609. namespace httplib {
  12610. namespace detail {
  12611. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12612. const std::string &content_type,
  12613. EncodingType encoding);
  12614. } // namespace detail
  12615. } // namespace httplib
  12616. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12617. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12618. ASSERT_TRUE(mm->is_open());
  12619. Response res;
  12620. detail::set_file_content_provider(res, mm, "text/html",
  12621. detail::EncodingType::None);
  12622. std::string out;
  12623. DataSink sink;
  12624. sink.write = [&](const char *d, size_t l) {
  12625. out.append(d, l);
  12626. return true;
  12627. };
  12628. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12629. EXPECT_EQ("test.html", out);
  12630. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12631. EXPECT_EQ("test.html", out);
  12632. }
  12633. TEST(LongPollingTest, ClientCloseDetection) {
  12634. Server svr;
  12635. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12636. res.set_chunked_content_provider(
  12637. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12638. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12639. sink.os << "hello";
  12640. auto count = 10;
  12641. while (count > 0 && sink.is_writable()) {
  12642. this_thread::sleep_for(chrono::milliseconds(10));
  12643. count--;
  12644. }
  12645. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12646. return true;
  12647. });
  12648. });
  12649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12650. auto se = detail::scope_exit([&] {
  12651. svr.stop();
  12652. listen_thread.join();
  12653. ASSERT_FALSE(svr.is_running());
  12654. });
  12655. svr.wait_until_ready();
  12656. Client cli("localhost", PORT);
  12657. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12658. EXPECT_EQ("hello", string(data, data_length));
  12659. return false; // close the socket immediately.
  12660. });
  12661. ASSERT_FALSE(res);
  12662. }
  12663. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12664. Server svr;
  12665. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12666. res.set_chunked_content_provider(
  12667. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12668. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12669. sink.os << "hello";
  12670. EXPECT_TRUE(sink.os.good());
  12671. // Wait for the client to close the connection
  12672. auto count = 10;
  12673. while (count > 0 && sink.is_writable()) {
  12674. this_thread::sleep_for(chrono::milliseconds(10));
  12675. count--;
  12676. }
  12677. // After client disconnect, write repeatedly until the socket
  12678. // write actually fails (small writes may be absorbed by the
  12679. // kernel buffer)
  12680. std::string chunk(1024, 'x');
  12681. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12682. sink.os << chunk;
  12683. }
  12684. EXPECT_TRUE(sink.os.fail());
  12685. return true;
  12686. });
  12687. });
  12688. auto port = svr.bind_to_any_port("localhost");
  12689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12690. auto se = detail::scope_exit([&] {
  12691. svr.stop();
  12692. listen_thread.join();
  12693. ASSERT_FALSE(svr.is_running());
  12694. });
  12695. svr.wait_until_ready();
  12696. Client cli("localhost", port);
  12697. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12698. EXPECT_EQ("hello", string(data, data_length));
  12699. return false; // close the socket immediately.
  12700. });
  12701. ASSERT_FALSE(res);
  12702. }
  12703. TEST(GetWithParametersTest, GetWithParameters) {
  12704. Server svr;
  12705. svr.Get("/", [&](const Request &req, Response &) {
  12706. EXPECT_EQ("world", req.get_param_value("hello"));
  12707. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12708. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12709. });
  12710. svr.Get("/params", [&](const Request &req, Response &) {
  12711. EXPECT_EQ("world", req.get_param_value("hello"));
  12712. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12713. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12714. });
  12715. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12716. EXPECT_EQ("resource-id", req.matches[1]);
  12717. EXPECT_EQ("foo", req.get_param_value("param1"));
  12718. EXPECT_EQ("bar", req.get_param_value("param2"));
  12719. });
  12720. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12721. EXPECT_EQ("user-id", req.path_params.at("id"));
  12722. EXPECT_EQ("foo", req.get_param_value("param1"));
  12723. EXPECT_EQ("bar", req.get_param_value("param2"));
  12724. });
  12725. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12726. auto se = detail::scope_exit([&] {
  12727. svr.stop();
  12728. listen_thread.join();
  12729. ASSERT_FALSE(svr.is_running());
  12730. });
  12731. svr.wait_until_ready();
  12732. {
  12733. Client cli(HOST, PORT);
  12734. Params params;
  12735. params.emplace("hello", "world");
  12736. params.emplace("hello2", "world2");
  12737. params.emplace("hello3", "world3");
  12738. auto res = cli.Get("/", params, Headers{});
  12739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12740. EXPECT_EQ(StatusCode::OK_200, res->status);
  12741. }
  12742. {
  12743. Client cli(HOST, PORT);
  12744. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12746. EXPECT_EQ(StatusCode::OK_200, res->status);
  12747. }
  12748. {
  12749. Client cli(HOST, PORT);
  12750. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12752. EXPECT_EQ(StatusCode::OK_200, res->status);
  12753. }
  12754. {
  12755. Client cli(HOST, PORT);
  12756. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12758. EXPECT_EQ(StatusCode::OK_200, res->status);
  12759. }
  12760. }
  12761. TEST(GetWithParametersTest, GetWithParameters2) {
  12762. Server svr;
  12763. svr.Get("/", [&](const Request &req, Response &res) {
  12764. auto text = req.get_param_value("hello");
  12765. res.set_content(text, "text/plain");
  12766. });
  12767. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. listen_thread.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. Client cli("localhost", PORT);
  12775. Params params;
  12776. params.emplace("hello", "world");
  12777. std::string body;
  12778. auto res = cli.Get("/", params, Headers{},
  12779. [&](const char *data, size_t data_length) {
  12780. body.append(data, data_length);
  12781. return true;
  12782. });
  12783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12784. EXPECT_EQ(StatusCode::OK_200, res->status);
  12785. EXPECT_EQ("world", body);
  12786. }
  12787. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12788. Server svr;
  12789. svr.Get("/search", [&](const Request &req, Response &res) {
  12790. auto q = req.get_param_value("q");
  12791. res.set_content(q, "text/plain");
  12792. });
  12793. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12794. auto se = detail::scope_exit([&] {
  12795. svr.stop();
  12796. listen_thread.join();
  12797. ASSERT_FALSE(svr.is_running());
  12798. });
  12799. svr.wait_until_ready();
  12800. Client cli("localhost", PORT);
  12801. // Verify that Get(path, params) works without requiring Headers argument
  12802. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12804. EXPECT_EQ(StatusCode::OK_200, res->status);
  12805. EXPECT_EQ("cpp-httplib", res->body);
  12806. }
  12807. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12808. auto host = "httpbingo.org";
  12809. auto path = std::string{"/range/32"};
  12810. #ifdef CPPHTTPLIB_SSL_ENABLED
  12811. SSLClient cli(host);
  12812. #else
  12813. Client cli(host);
  12814. #endif
  12815. cli.set_default_headers({make_range_header({{1, 10}})});
  12816. cli.set_connection_timeout(5);
  12817. {
  12818. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12819. SKIP_ON_GATEWAY_ERROR(res);
  12820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12821. EXPECT_EQ("bcdefghijk", res->body);
  12822. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12823. }
  12824. {
  12825. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12826. SKIP_ON_GATEWAY_ERROR(res);
  12827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12828. EXPECT_EQ("bcdefghijk", res->body);
  12829. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12830. }
  12831. }
  12832. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12833. Server svr;
  12834. svr.set_default_headers({{"Hello", "World"}});
  12835. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12836. res.set_content("ok", "text/plain");
  12837. });
  12838. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12839. auto se = detail::scope_exit([&] {
  12840. svr.stop();
  12841. listen_thread.join();
  12842. ASSERT_FALSE(svr.is_running());
  12843. });
  12844. svr.wait_until_ready();
  12845. Client cli("localhost", PORT);
  12846. auto res = cli.Get("/");
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. EXPECT_EQ(StatusCode::OK_200, res->status);
  12849. EXPECT_EQ("ok", res->body);
  12850. EXPECT_EQ("World", res->get_header_value("Hello"));
  12851. }
  12852. #ifdef CPPHTTPLIB_SSL_ENABLED
  12853. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12855. ASSERT_TRUE(svr.is_valid());
  12856. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12857. std::this_thread::sleep_for(std::chrono::seconds(2));
  12858. res.set_content("a", "text/plain");
  12859. });
  12860. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12861. res.set_content("b", "text/plain");
  12862. });
  12863. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12864. auto se = detail::scope_exit([&] {
  12865. svr.stop();
  12866. listen_thread.join();
  12867. ASSERT_FALSE(svr.is_running());
  12868. });
  12869. svr.wait_until_ready();
  12870. SSLClient cli("localhost", PORT);
  12871. cli.enable_server_certificate_verification(false);
  12872. cli.set_keep_alive(true);
  12873. cli.set_read_timeout(std::chrono::seconds(1));
  12874. auto resa = cli.Get("/a");
  12875. ASSERT_TRUE(!resa);
  12876. EXPECT_EQ(Error::Read, resa.error());
  12877. auto resb = cli.Get("/b");
  12878. ASSERT_TRUE(resb);
  12879. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12880. EXPECT_EQ("b", resb->body);
  12881. }
  12882. // Closing an idle keep-alive connection sends close_notify and returns. The
  12883. // server must not wait for the client's close_notify: an idle client never
  12884. // sends one, so the worker would be held until the read timeout expires, and
  12885. // stop() would wait for it.
  12886. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12888. ASSERT_TRUE(svr.is_valid());
  12889. svr.set_keep_alive_timeout(1);
  12890. svr.set_read_timeout(10, 0);
  12891. svr.Get("/", [](const Request &, Response &res) {
  12892. res.set_content("ok", "text/plain");
  12893. });
  12894. auto port = svr.bind_to_any_port(HOST);
  12895. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12896. auto se = detail::scope_exit([&] {
  12897. if (listen_thread.joinable()) {
  12898. svr.stop();
  12899. listen_thread.join();
  12900. }
  12901. });
  12902. svr.wait_until_ready();
  12903. SSLClient cli(HOST, port);
  12904. cli.enable_server_certificate_verification(false);
  12905. cli.set_keep_alive(true);
  12906. auto res = cli.Get("/");
  12907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12908. EXPECT_EQ(StatusCode::OK_200, res->status);
  12909. // Stay idle past the keep-alive timeout so the server closes the connection.
  12910. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12911. auto start = std::chrono::steady_clock::now();
  12912. svr.stop();
  12913. listen_thread.join();
  12914. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12915. std::chrono::steady_clock::now() - start)
  12916. .count();
  12917. EXPECT_LT(elapsed, 3000);
  12918. }
  12919. #endif
  12920. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12921. protected:
  12922. ServerTestWithAI_PASSIVE()
  12923. : cli_(HOST, PORT)
  12924. #ifdef CPPHTTPLIB_SSL_ENABLED
  12925. ,
  12926. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12927. #endif
  12928. {
  12929. #ifdef CPPHTTPLIB_SSL_ENABLED
  12930. cli_.enable_server_certificate_verification(false);
  12931. #endif
  12932. }
  12933. virtual void SetUp() {
  12934. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12935. res.set_content("Hello World!", "text/plain");
  12936. });
  12937. t_ = thread(
  12938. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12939. svr_.wait_until_ready();
  12940. }
  12941. virtual void TearDown() {
  12942. svr_.stop();
  12943. t_.join();
  12944. }
  12945. #ifdef CPPHTTPLIB_SSL_ENABLED
  12946. SSLClient cli_;
  12947. SSLServer svr_;
  12948. #else
  12949. Client cli_;
  12950. Server svr_;
  12951. #endif
  12952. thread t_;
  12953. };
  12954. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12955. auto res = cli_.Get("/hi");
  12956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12957. EXPECT_EQ(StatusCode::OK_200, res->status);
  12958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12959. EXPECT_EQ("Hello World!", res->body);
  12960. }
  12961. class ServerUpDownTest : public ::testing::Test {
  12962. protected:
  12963. ServerUpDownTest() : cli_(HOST, PORT) {}
  12964. virtual void SetUp() {
  12965. t_ = thread([&]() {
  12966. svr_.bind_to_any_port(HOST);
  12967. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12968. ASSERT_TRUE(svr_.listen_after_bind());
  12969. });
  12970. svr_.wait_until_ready();
  12971. }
  12972. virtual void TearDown() {
  12973. svr_.stop();
  12974. t_.join();
  12975. }
  12976. Client cli_;
  12977. Server svr_;
  12978. thread t_;
  12979. };
  12980. TEST_F(ServerUpDownTest, QuickStartStop) {
  12981. // Should not crash, especially when run with
  12982. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12983. }
  12984. class PayloadMaxLengthTest : public ::testing::Test {
  12985. protected:
  12986. PayloadMaxLengthTest()
  12987. : cli_(HOST, PORT)
  12988. #ifdef CPPHTTPLIB_SSL_ENABLED
  12989. ,
  12990. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12991. #endif
  12992. {
  12993. #ifdef CPPHTTPLIB_SSL_ENABLED
  12994. cli_.enable_server_certificate_verification(false);
  12995. #endif
  12996. }
  12997. virtual void SetUp() {
  12998. svr_.set_payload_max_length(8);
  12999. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13000. res.set_content("test", "text/plain");
  13001. });
  13002. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13003. svr_.wait_until_ready();
  13004. }
  13005. virtual void TearDown() {
  13006. svr_.stop();
  13007. t_.join();
  13008. }
  13009. #ifdef CPPHTTPLIB_SSL_ENABLED
  13010. SSLClient cli_;
  13011. SSLServer svr_;
  13012. #else
  13013. Client cli_;
  13014. Server svr_;
  13015. #endif
  13016. thread t_;
  13017. };
  13018. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13019. auto res = cli_.Post("/test", "123456789", "text/plain");
  13020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13021. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13022. res = cli_.Post("/test", "12345678", "text/plain");
  13023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13024. EXPECT_EQ(StatusCode::OK_200, res->status);
  13025. }
  13026. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13027. // Test chunked encoding with payload exceeding the 8-byte limit
  13028. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13029. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13031. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13032. }
  13033. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13034. // Test chunked encoding with payload within the 8-byte limit
  13035. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13036. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13038. EXPECT_EQ(StatusCode::OK_200, res->status);
  13039. }
  13040. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13041. // Test using send_request to send chunked data exceeding payload limit
  13042. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13043. "Host: " +
  13044. std::string(HOST) + ":" + std::to_string(PORT) +
  13045. "\r\n"
  13046. "Transfer-Encoding: chunked\r\n"
  13047. "Connection: close\r\n"
  13048. "\r\n"
  13049. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13050. "0123456789\r\n"
  13051. "0\r\n" // End chunk
  13052. "\r\n";
  13053. std::string response;
  13054. bool result = send_request(1, chunked_request, &response);
  13055. if (!result) {
  13056. // If send_request fails, it might be because the server closed the
  13057. // connection due to payload limit enforcement, which is acceptable
  13058. SUCCEED()
  13059. << "Server rejected oversized chunked request (connection closed)";
  13060. } else {
  13061. // If we got a response, check if it's an error response or connection was
  13062. // closed early Short response length indicates connection was closed due to
  13063. // payload limit
  13064. if (response.length() <= 10) {
  13065. SUCCEED() << "Server closed connection for oversized chunked request";
  13066. } else {
  13067. // Check for error status codes
  13068. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13069. response.find("Payload Too Large") != std::string::npos ||
  13070. response.find("400") != std::string::npos);
  13071. }
  13072. }
  13073. }
  13074. class LargePayloadMaxLengthTest : public ::testing::Test {
  13075. protected:
  13076. LargePayloadMaxLengthTest()
  13077. : cli_(HOST, PORT)
  13078. #ifdef CPPHTTPLIB_SSL_ENABLED
  13079. ,
  13080. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13081. #endif
  13082. {
  13083. #ifdef CPPHTTPLIB_SSL_ENABLED
  13084. cli_.enable_server_certificate_verification(false);
  13085. #endif
  13086. }
  13087. virtual void SetUp() {
  13088. // Set 10MB payload limit
  13089. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13090. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13091. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13092. res.set_content("Large payload test", "text/plain");
  13093. });
  13094. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13095. svr_.wait_until_ready();
  13096. }
  13097. virtual void TearDown() {
  13098. svr_.stop();
  13099. t_.join();
  13100. }
  13101. #ifdef CPPHTTPLIB_SSL_ENABLED
  13102. SSLClient cli_;
  13103. SSLServer svr_;
  13104. #else
  13105. Client cli_;
  13106. Server svr_;
  13107. #endif
  13108. thread t_;
  13109. };
  13110. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13111. // Test chunked encoding with payload within 10MB limit
  13112. std::string medium_payload(5 * 1024 * 1024,
  13113. 'A'); // 5MB payload, within 10MB limit
  13114. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13116. EXPECT_EQ(StatusCode::OK_200, res->status);
  13117. }
  13118. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13119. // Test chunked encoding with payload exceeding 10MB limit
  13120. std::string large_payload(12 * 1024 * 1024,
  13121. 'B'); // 12MB payload, exceeds 10MB limit
  13122. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13123. // Server may either return 413 or close the connection
  13124. if (res) {
  13125. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13126. } else {
  13127. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13128. }
  13129. }
  13130. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13131. Server svr;
  13132. svr.Get("/", [](const Request &, Response &res) {
  13133. // Claims the most the client accepts, far more than it sends, then drops
  13134. // the connection.
  13135. res.set_content_provider(std::string().max_size(), "text/plain",
  13136. [](size_t, size_t, DataSink &sink) {
  13137. sink.write("abc", 3);
  13138. return false;
  13139. });
  13140. });
  13141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13142. auto se = detail::scope_exit([&] {
  13143. svr.stop();
  13144. thread.join();
  13145. ASSERT_FALSE(svr.is_running());
  13146. });
  13147. svr.wait_until_ready();
  13148. Client cli(HOST, PORT);
  13149. cli.set_payload_max_length(0);
  13150. EXPECT_FALSE(cli.Get("/"));
  13151. }
  13152. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13153. // Stream API does, not as a plain read failure
  13154. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13155. Server svr;
  13156. svr.Get("/big", [](const Request &, Response &res) {
  13157. res.set_content(std::string(100000, 'b'), "text/plain");
  13158. });
  13159. auto port = svr.bind_to_any_port(HOST);
  13160. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13161. auto se = detail::scope_exit([&] {
  13162. svr.stop();
  13163. thread.join();
  13164. });
  13165. svr.wait_until_ready();
  13166. Client cli(HOST, port);
  13167. cli.set_payload_max_length(1000);
  13168. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13169. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13170. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13171. [](const char *, size_t) { return true; });
  13172. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13173. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13174. // Small on the wire, over the limit once decompressed
  13175. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13176. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13177. #endif
  13178. }
  13179. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13180. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13181. // path.
  13182. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13183. Server svr;
  13184. const size_t LIMIT = 64 * 1024; // 64KB
  13185. svr.set_payload_max_length(LIMIT);
  13186. size_t total = 0;
  13187. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13188. const ContentReader &content_reader) {
  13189. content_reader([&](const char * /*data*/, size_t len) {
  13190. total += len;
  13191. return true;
  13192. });
  13193. res.status = 200;
  13194. res.set_content("stream_ok", "text/plain");
  13195. });
  13196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13197. auto se = detail::scope_exit([&] {
  13198. svr.stop();
  13199. thread.join();
  13200. ASSERT_FALSE(svr.is_running());
  13201. });
  13202. svr.wait_until_ready();
  13203. // Prepare 256KB raw data and gzip-compress it
  13204. std::string raw(256 * 1024, 'A');
  13205. std::string gz;
  13206. {
  13207. z_stream zs{};
  13208. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13209. Z_DEFAULT_STRATEGY);
  13210. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13211. zs.avail_in = static_cast<uInt>(raw.size());
  13212. char outbuf[4096];
  13213. int ret;
  13214. do {
  13215. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13216. zs.avail_out = sizeof(outbuf);
  13217. ret = deflate(&zs, Z_FINISH);
  13218. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13219. } while (ret != Z_STREAM_END);
  13220. deflateEnd(&zs);
  13221. }
  13222. Client cli(HOST, PORT);
  13223. cli.set_connection_timeout(std::chrono::seconds(5));
  13224. Headers headers = {{"Content-Encoding", "gzip"}};
  13225. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13226. "application/octet-stream");
  13227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13228. // Server must reject oversized decompressed payloads with 413.
  13229. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13230. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13231. EXPECT_LE(total, LIMIT);
  13232. }
  13233. #endif
  13234. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13235. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13236. // the payload must be passed through untouched instead of being rejected.
  13237. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13238. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13239. Server svr;
  13240. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13241. res.set_content(body, "image/jpeg");
  13242. res.set_header("Content-Encoding", "UTF-8");
  13243. });
  13244. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13245. res.set_content(body, "image/jpeg");
  13246. res.set_header("Content-Encoding", "identity");
  13247. });
  13248. svr.Post("/echo", [](const Request &req, Response &res) {
  13249. res.set_content(req.body, "image/jpeg");
  13250. });
  13251. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13252. auto se = detail::scope_exit([&] {
  13253. svr.stop();
  13254. t.join();
  13255. ASSERT_FALSE(svr.is_running());
  13256. });
  13257. svr.wait_until_ready();
  13258. Client cli(HOST, PORT);
  13259. {
  13260. auto res = cli.Get("/image");
  13261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13262. EXPECT_EQ(StatusCode::OK_200, res->status);
  13263. EXPECT_EQ(body, res->body);
  13264. }
  13265. {
  13266. auto res = cli.Get("/identity");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_EQ(StatusCode::OK_200, res->status);
  13269. EXPECT_EQ(body, res->body);
  13270. }
  13271. {
  13272. // The same applies to a request body reaching the server.
  13273. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13274. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. EXPECT_EQ(StatusCode::OK_200, res->status);
  13277. EXPECT_EQ(body, res->body);
  13278. }
  13279. }
  13280. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13281. // gzip-encoded response even when the build has no zlib support.
  13282. static const char GZIPPED_HELLO_WORLD[] = {
  13283. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13284. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13285. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13286. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13287. // A content coding is a whole token, not something the field value merely
  13288. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13289. // as "fibre" look like Brotli, and turned a multi-coding value like
  13290. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13291. // it was never meant to see.
  13292. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13293. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13294. Server svr;
  13295. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13296. res.set_content(body, "image/jpeg");
  13297. res.set_header("Content-Encoding", "fibre");
  13298. });
  13299. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13300. res.set_content(body, "image/jpeg");
  13301. res.set_header("Content-Encoding", "gzip, br");
  13302. });
  13303. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13304. res.set_content(body, "image/jpeg");
  13305. res.set_header("Content-Encoding", "x-zstd-ish");
  13306. });
  13307. auto port = svr.bind_to_any_port(HOST);
  13308. thread t = thread([&]() { svr.listen_after_bind(); });
  13309. auto se = detail::scope_exit([&] {
  13310. svr.stop();
  13311. t.join();
  13312. ASSERT_FALSE(svr.is_running());
  13313. });
  13314. svr.wait_until_ready();
  13315. Client cli(HOST, port);
  13316. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13317. auto res = cli.Get(path);
  13318. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13319. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13320. // Not a coding we recognize, so the payload comes back untouched
  13321. EXPECT_EQ(body, res->body) << path;
  13322. }
  13323. }
  13324. // A content coding cpp-httplib recognizes but was not built with must be
  13325. // reported as such. Handing the still-compressed payload back to the caller
  13326. // would silently corrupt it.
  13327. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13328. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13329. Server svr;
  13330. // "image/jpeg" keeps the server from applying a content coding of its own,
  13331. // so the hand-crafted Content-Encoding below survives.
  13332. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13333. res.set_content(gzipped, "image/jpeg");
  13334. res.set_header("Content-Encoding", "gzip");
  13335. });
  13336. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13337. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13338. res.set_content(gzipped, "image/jpeg");
  13339. res.set_header("Content-Encoding", "GZIP");
  13340. });
  13341. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. ASSERT_FALSE(svr.is_running());
  13346. });
  13347. svr.wait_until_ready();
  13348. Client cli(HOST, PORT);
  13349. {
  13350. auto res = cli.Get("/gzipped");
  13351. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13353. EXPECT_EQ("Hello World!", res->body);
  13354. #else
  13355. ASSERT_FALSE(res);
  13356. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13357. #endif
  13358. }
  13359. {
  13360. // open_stream() must behave the same way.
  13361. auto handle = cli.open_stream("GET", "/gzipped");
  13362. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13363. ASSERT_TRUE(handle.is_valid());
  13364. std::string received;
  13365. char buf[256];
  13366. ssize_t n;
  13367. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13368. received.append(buf, static_cast<size_t>(n));
  13369. }
  13370. EXPECT_EQ("Hello World!", received);
  13371. #else
  13372. EXPECT_FALSE(handle.is_valid());
  13373. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13374. #endif
  13375. }
  13376. {
  13377. // A differently-cased coding must not be mistaken for an unknown one, or
  13378. // the body would be handed back still compressed.
  13379. auto res = cli.Get("/gzipped-uppercase");
  13380. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13382. EXPECT_EQ("Hello World!", res->body);
  13383. #else
  13384. ASSERT_FALSE(res);
  13385. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13386. #endif
  13387. }
  13388. }
  13389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13390. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13391. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13392. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13393. // body a second time and appending a second Content-Encoding field line, so
  13394. // clients that decode one coding per listed value handed back raw gzip bytes.
  13395. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13396. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13397. Server svr;
  13398. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13399. // keeps the server from applying a coding of its own.
  13400. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13401. res.set_content(gzipped, "text/plain");
  13402. res.set_header("Content-Encoding", "gzip");
  13403. });
  13404. auto port = svr.bind_to_any_port(HOST);
  13405. thread t = thread([&]() { svr.listen_after_bind(); });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. Client cli(HOST, port);
  13413. Headers headers = {{"Accept-Encoding", "gzip"}};
  13414. auto res = cli.Get("/pre-gzipped", headers);
  13415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13416. EXPECT_EQ(StatusCode::OK_200, res->status);
  13417. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13418. EXPECT_EQ("Hello World!", res->body);
  13419. }
  13420. // set_compress(false) sends every handler response as it is, buffered or
  13421. // streamed
  13422. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13423. const std::string text(1000, 'a');
  13424. Server svr;
  13425. svr.set_compress(false);
  13426. svr.Get("/buffered", [&](const Request &, Response &res) {
  13427. res.set_content(text, "text/plain");
  13428. });
  13429. svr.Get("/streamed", [&](const Request &, Response &res) {
  13430. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13431. sink.write(text.data(), text.size());
  13432. sink.done();
  13433. return true;
  13434. });
  13435. });
  13436. auto port = svr.bind_to_any_port(HOST);
  13437. ASSERT_LT(0, port);
  13438. thread t = thread([&] { svr.listen_after_bind(); });
  13439. auto se = detail::scope_exit([&] {
  13440. svr.stop();
  13441. t.join();
  13442. ASSERT_FALSE(svr.is_running());
  13443. });
  13444. svr.wait_until_ready();
  13445. Client cli(HOST, port);
  13446. cli.set_decompress(false);
  13447. for (auto path : {"/buffered", "/streamed"}) {
  13448. SCOPED_TRACE(path);
  13449. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13451. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13452. EXPECT_EQ(text, res->body);
  13453. }
  13454. }
  13455. // A chunked provider settles its coding where the headers are written and
  13456. // reuses it at write time. Both ends of that have to hold: a handler's own
  13457. // Content-Encoding suppresses the coding, and a response without one is still
  13458. // compressed as it always was.
  13459. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13460. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13461. const std::string plain = "Hello World! Hello World! Hello World!";
  13462. Server svr;
  13463. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13464. res.set_header("Content-Encoding", "gzip");
  13465. res.set_chunked_content_provider(
  13466. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13467. sink.write(gzipped.data(), gzipped.size());
  13468. sink.done();
  13469. return true;
  13470. });
  13471. });
  13472. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13473. res.set_chunked_content_provider(
  13474. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13475. sink.write(plain.data(), plain.size());
  13476. sink.done();
  13477. return true;
  13478. });
  13479. });
  13480. auto port = svr.bind_to_any_port(HOST);
  13481. thread t = thread([&]() { svr.listen_after_bind(); });
  13482. auto se = detail::scope_exit([&] {
  13483. svr.stop();
  13484. t.join();
  13485. ASSERT_FALSE(svr.is_running());
  13486. });
  13487. svr.wait_until_ready();
  13488. Client cli(HOST, port);
  13489. Headers headers = {{"Accept-Encoding", "gzip"}};
  13490. {
  13491. auto res = cli.Get("/pre-gzipped", headers);
  13492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13493. EXPECT_EQ(StatusCode::OK_200, res->status);
  13494. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13495. EXPECT_EQ("Hello World!", res->body);
  13496. }
  13497. {
  13498. auto res = cli.Get("/negotiated", headers);
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13500. EXPECT_EQ(StatusCode::OK_200, res->status);
  13501. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13502. EXPECT_EQ(plain, res->body);
  13503. }
  13504. }
  13505. #endif
  13506. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13507. // the same message as the comma-joined one, so both have to be read the same
  13508. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13509. // single gzip coding, and a body the sender says was encoded twice was handed
  13510. // back after one pass, still compressed but presented as decoded.
  13511. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13512. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13513. Server svr;
  13514. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13515. res.set_content(body, "image/jpeg");
  13516. res.headers.emplace("Content-Encoding", "gzip");
  13517. res.headers.emplace("Content-Encoding", "gzip");
  13518. });
  13519. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13520. res.set_content(body, "image/jpeg");
  13521. res.set_header("Content-Encoding", "gzip, gzip");
  13522. });
  13523. auto port = svr.bind_to_any_port(HOST);
  13524. thread t = thread([&]() { svr.listen_after_bind(); });
  13525. auto se = detail::scope_exit([&] {
  13526. svr.stop();
  13527. t.join();
  13528. ASSERT_FALSE(svr.is_running());
  13529. });
  13530. svr.wait_until_ready();
  13531. Client cli(HOST, port);
  13532. // Two codings is not something cpp-httplib decodes, so both representations
  13533. // take the pass-through path rather than one of them being gunzipped once.
  13534. for (const char *path : {"/split", "/joined"}) {
  13535. auto res = cli.Get(path);
  13536. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13537. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13538. EXPECT_EQ(body, res->body) << path;
  13539. }
  13540. }
  13541. // Regression test for DoS vulnerability: a malicious server sending a response
  13542. // without Content-Length header must not cause unbounded memory consumption on
  13543. // the client side. The client should stop reading after a reasonable limit,
  13544. // similar to the server-side set_payload_max_length protection.
  13545. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13546. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13547. #ifndef _WIN32
  13548. signal(SIGPIPE, SIG_IGN);
  13549. #endif
  13550. auto server_thread = std::thread([] {
  13551. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13552. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13553. default_socket_options(srv);
  13554. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13555. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13556. sockaddr_in addr{};
  13557. addr.sin_family = AF_INET;
  13558. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13559. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13560. int opt = 1;
  13561. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13562. #ifdef _WIN32
  13563. reinterpret_cast<const char *>(&opt),
  13564. #else
  13565. &opt,
  13566. #endif
  13567. sizeof(opt));
  13568. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13569. ::listen(srv, 1);
  13570. sockaddr_in cli_addr{};
  13571. socklen_t cli_len = sizeof(cli_addr);
  13572. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13573. if (cli != INVALID_SOCKET) {
  13574. char buf[4096];
  13575. ::recv(cli, buf, sizeof(buf), 0);
  13576. // Malicious response: no Content-Length, no chunked encoding
  13577. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13578. "Connection: close\r\n"
  13579. "\r\n";
  13580. ::send(cli,
  13581. #ifdef _WIN32
  13582. static_cast<const char *>(response_header.c_str()),
  13583. static_cast<int>(response_header.size()),
  13584. #else
  13585. response_header.c_str(), response_header.size(),
  13586. #endif
  13587. 0);
  13588. // Send 10MB of data
  13589. std::string chunk(64 * 1024, 'A');
  13590. size_t total_sent = 0;
  13591. while (total_sent < MALICIOUS_DATA_SIZE) {
  13592. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13593. auto sent = ::send(cli,
  13594. #ifdef _WIN32
  13595. static_cast<const char *>(chunk.c_str()),
  13596. static_cast<int>(to_send),
  13597. #else
  13598. chunk.c_str(), to_send,
  13599. #endif
  13600. 0);
  13601. if (sent <= 0) break;
  13602. total_sent += static_cast<size_t>(sent);
  13603. }
  13604. detail::close_socket(cli);
  13605. }
  13606. detail::close_socket(srv);
  13607. });
  13608. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13609. size_t total_read = 0;
  13610. {
  13611. Client cli("127.0.0.1", PORT + 2);
  13612. cli.set_read_timeout(5, 0);
  13613. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13614. auto stream = cli.open_stream("GET", "/malicious");
  13615. ASSERT_TRUE(stream.is_valid());
  13616. char buffer[64 * 1024];
  13617. ssize_t n;
  13618. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13619. total_read += static_cast<size_t>(n);
  13620. }
  13621. } // StreamHandle and Client destroyed here, closing the socket
  13622. server_thread.join();
  13623. // With set_payload_max_length, the client must stop reading before consuming
  13624. // all 10MB. The read loop should be cut off at or near the configured limit.
  13625. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13626. << "Client read " << total_read << " bytes, exceeding the configured "
  13627. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13628. }
  13629. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13630. // the entire response body without truncation.
  13631. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13632. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13633. #ifndef _WIN32
  13634. signal(SIGPIPE, SIG_IGN);
  13635. #endif
  13636. auto server_thread = std::thread([] {
  13637. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13638. default_socket_options(srv);
  13639. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13641. sockaddr_in addr{};
  13642. addr.sin_family = AF_INET;
  13643. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13644. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13645. int opt = 1;
  13646. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13647. #ifdef _WIN32
  13648. reinterpret_cast<const char *>(&opt),
  13649. #else
  13650. &opt,
  13651. #endif
  13652. sizeof(opt));
  13653. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13654. ::listen(srv, 1);
  13655. sockaddr_in cli_addr{};
  13656. socklen_t cli_len = sizeof(cli_addr);
  13657. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13658. if (cli != INVALID_SOCKET) {
  13659. char buf[4096];
  13660. ::recv(cli, buf, sizeof(buf), 0);
  13661. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13662. "Connection: close\r\n"
  13663. "\r\n";
  13664. ::send(cli,
  13665. #ifdef _WIN32
  13666. static_cast<const char *>(response_header.c_str()),
  13667. static_cast<int>(response_header.size()),
  13668. #else
  13669. response_header.c_str(), response_header.size(),
  13670. #endif
  13671. 0);
  13672. std::string chunk(64 * 1024, 'A');
  13673. size_t total_sent = 0;
  13674. while (total_sent < DATA_SIZE) {
  13675. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13676. auto sent = ::send(cli,
  13677. #ifdef _WIN32
  13678. static_cast<const char *>(chunk.c_str()),
  13679. static_cast<int>(to_send),
  13680. #else
  13681. chunk.c_str(), to_send,
  13682. #endif
  13683. 0);
  13684. if (sent <= 0) break;
  13685. total_sent += static_cast<size_t>(sent);
  13686. }
  13687. #ifdef _WIN32
  13688. ::shutdown(cli, SD_SEND);
  13689. #else
  13690. ::shutdown(cli, SHUT_WR);
  13691. #endif
  13692. // Drain until the client closes its end, ensuring all data is delivered
  13693. char drain[1024];
  13694. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13695. detail::close_socket(cli);
  13696. }
  13697. detail::close_socket(srv);
  13698. });
  13699. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13700. size_t total_read = 0;
  13701. {
  13702. Client cli("127.0.0.1", PORT + 2);
  13703. cli.set_read_timeout(5, 0);
  13704. cli.set_payload_max_length(0); // 0 means no limit
  13705. auto stream = cli.open_stream("GET", "/data");
  13706. ASSERT_TRUE(stream.is_valid());
  13707. char buffer[64 * 1024];
  13708. ssize_t n;
  13709. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13710. total_read += static_cast<size_t>(n);
  13711. }
  13712. }
  13713. server_thread.join();
  13714. EXPECT_EQ(total_read, DATA_SIZE)
  13715. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13716. << " bytes without truncation, but only read " << total_read << " bytes.";
  13717. }
  13718. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13719. // enormous Content-Length must not cause the client to pre-allocate a huge
  13720. // response body buffer. The reservation is capped at payload_max_length_, and
  13721. // the read itself fails when the body exceeds the limit.
  13722. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13723. #ifndef _WIN32
  13724. signal(SIGPIPE, SIG_IGN);
  13725. #endif
  13726. auto server_thread = std::thread([] {
  13727. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13728. default_socket_options(srv);
  13729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13730. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13731. sockaddr_in addr{};
  13732. addr.sin_family = AF_INET;
  13733. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13734. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13735. int opt = 1;
  13736. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13737. #ifdef _WIN32
  13738. reinterpret_cast<const char *>(&opt),
  13739. #else
  13740. &opt,
  13741. #endif
  13742. sizeof(opt));
  13743. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13744. ::listen(srv, 1);
  13745. sockaddr_in cli_addr{};
  13746. socklen_t cli_len = sizeof(cli_addr);
  13747. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13748. if (cli != INVALID_SOCKET) {
  13749. char buf[4096];
  13750. ::recv(cli, buf, sizeof(buf), 0);
  13751. // Malicious response: claim a 20GB body but send only a tiny payload.
  13752. std::string response = "HTTP/1.1 200 OK\r\n"
  13753. "Content-Length: 20000000000\r\n"
  13754. "\r\n"
  13755. "abc";
  13756. ::send(cli,
  13757. #ifdef _WIN32
  13758. static_cast<const char *>(response.c_str()),
  13759. static_cast<int>(response.size()),
  13760. #else
  13761. response.c_str(), response.size(),
  13762. #endif
  13763. 0);
  13764. detail::close_socket(cli);
  13765. }
  13766. detail::close_socket(srv);
  13767. });
  13768. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13769. {
  13770. Client cli("127.0.0.1", PORT + 2);
  13771. cli.set_read_timeout(5, 0);
  13772. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13773. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13774. // (server claims more bytes than payload_max_length permits), but it must
  13775. // not exhaust memory before getting there.
  13776. auto res = cli.Get("/malicious");
  13777. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13778. }
  13779. server_thread.join();
  13780. }
  13781. // Verify that content_receiver bypasses the default payload_max_length,
  13782. // allowing streaming downloads larger than 100MB without requiring an explicit
  13783. // set_payload_max_length call.
  13784. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13785. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13786. #ifndef _WIN32
  13787. signal(SIGPIPE, SIG_IGN);
  13788. #endif
  13789. auto server_thread = std::thread([] {
  13790. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13791. default_socket_options(srv);
  13792. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13793. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13794. sockaddr_in addr{};
  13795. addr.sin_family = AF_INET;
  13796. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13797. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13798. int opt = 1;
  13799. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13800. #ifdef _WIN32
  13801. reinterpret_cast<const char *>(&opt),
  13802. #else
  13803. &opt,
  13804. #endif
  13805. sizeof(opt));
  13806. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13807. ::listen(srv, 1);
  13808. sockaddr_in cli_addr{};
  13809. socklen_t cli_len = sizeof(cli_addr);
  13810. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13811. if (cli != INVALID_SOCKET) {
  13812. char buf[4096];
  13813. ::recv(cli, buf, sizeof(buf), 0);
  13814. // Response with Content-Length larger than default 100MB limit
  13815. auto content_length = std::to_string(DATA_SIZE);
  13816. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13817. "Content-Length: " +
  13818. content_length +
  13819. "\r\n"
  13820. "Connection: close\r\n"
  13821. "\r\n";
  13822. ::send(cli,
  13823. #ifdef _WIN32
  13824. static_cast<const char *>(response_header.c_str()),
  13825. static_cast<int>(response_header.size()),
  13826. #else
  13827. response_header.c_str(), response_header.size(),
  13828. #endif
  13829. 0);
  13830. std::string chunk(64 * 1024, 'A');
  13831. size_t total_sent = 0;
  13832. while (total_sent < DATA_SIZE) {
  13833. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13834. auto sent = ::send(cli,
  13835. #ifdef _WIN32
  13836. static_cast<const char *>(chunk.c_str()),
  13837. static_cast<int>(to_send),
  13838. #else
  13839. chunk.c_str(), to_send,
  13840. #endif
  13841. 0);
  13842. if (sent <= 0) break;
  13843. total_sent += static_cast<size_t>(sent);
  13844. }
  13845. detail::close_socket(cli);
  13846. }
  13847. detail::close_socket(srv);
  13848. });
  13849. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13850. size_t total_received = 0;
  13851. {
  13852. Client cli("127.0.0.1", PORT + 2);
  13853. cli.set_read_timeout(10, 0);
  13854. // Do NOT call set_payload_max_length — use the default 100MB limit
  13855. auto res =
  13856. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13857. total_received += data_length;
  13858. return true;
  13859. });
  13860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13861. EXPECT_EQ(StatusCode::OK_200, res->status);
  13862. }
  13863. server_thread.join();
  13864. EXPECT_EQ(total_received, DATA_SIZE)
  13865. << "With content_receiver, the client should read all " << DATA_SIZE
  13866. << " bytes despite the default 100MB payload_max_length, but only read "
  13867. << total_received << " bytes.";
  13868. }
  13869. // Verify that an explicit set_payload_max_length smaller than the response is
  13870. // enforced even when a content_receiver is used.
  13871. TEST(ClientVulnerabilityTest,
  13872. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13873. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13874. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13875. #ifndef _WIN32
  13876. signal(SIGPIPE, SIG_IGN);
  13877. #endif
  13878. auto server_thread = std::thread([] {
  13879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13880. default_socket_options(srv);
  13881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13883. sockaddr_in addr{};
  13884. addr.sin_family = AF_INET;
  13885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13887. int opt = 1;
  13888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13889. #ifdef _WIN32
  13890. reinterpret_cast<const char *>(&opt),
  13891. #else
  13892. &opt,
  13893. #endif
  13894. sizeof(opt));
  13895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13896. ::listen(srv, 1);
  13897. sockaddr_in cli_addr{};
  13898. socklen_t cli_len = sizeof(cli_addr);
  13899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13900. if (cli != INVALID_SOCKET) {
  13901. char buf[4096];
  13902. ::recv(cli, buf, sizeof(buf), 0);
  13903. auto content_length = std::to_string(DATA_SIZE);
  13904. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13905. "Content-Length: " +
  13906. content_length +
  13907. "\r\n"
  13908. "Connection: close\r\n"
  13909. "\r\n";
  13910. ::send(cli,
  13911. #ifdef _WIN32
  13912. static_cast<const char *>(response_header.c_str()),
  13913. static_cast<int>(response_header.size()),
  13914. #else
  13915. response_header.c_str(), response_header.size(),
  13916. #endif
  13917. 0);
  13918. std::string chunk(64 * 1024, 'A');
  13919. size_t total_sent = 0;
  13920. while (total_sent < DATA_SIZE) {
  13921. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13922. auto sent = ::send(cli,
  13923. #ifdef _WIN32
  13924. static_cast<const char *>(chunk.c_str()),
  13925. static_cast<int>(to_send),
  13926. #else
  13927. chunk.c_str(), to_send,
  13928. #endif
  13929. 0);
  13930. if (sent <= 0) break;
  13931. total_sent += static_cast<size_t>(sent);
  13932. }
  13933. detail::close_socket(cli);
  13934. }
  13935. detail::close_socket(srv);
  13936. });
  13937. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13938. size_t total_received = 0;
  13939. {
  13940. Client cli("127.0.0.1", PORT + 2);
  13941. cli.set_read_timeout(10, 0);
  13942. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13943. auto res =
  13944. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13945. total_received += data_length;
  13946. return true;
  13947. });
  13948. // Should fail because 200MB exceeds the explicit 150MB limit
  13949. EXPECT_FALSE(res);
  13950. }
  13951. server_thread.join();
  13952. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13953. << "Client with content_receiver should respect the explicit "
  13954. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13955. << total_received << " bytes.";
  13956. }
  13957. // Verify that an explicit set_payload_max_length larger than the response
  13958. // allows the content_receiver to read all data successfully.
  13959. TEST(ClientVulnerabilityTest,
  13960. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13961. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13962. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13963. #ifndef _WIN32
  13964. signal(SIGPIPE, SIG_IGN);
  13965. #endif
  13966. auto server_thread = std::thread([] {
  13967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13968. default_socket_options(srv);
  13969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13971. sockaddr_in addr{};
  13972. addr.sin_family = AF_INET;
  13973. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13975. int opt = 1;
  13976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13977. #ifdef _WIN32
  13978. reinterpret_cast<const char *>(&opt),
  13979. #else
  13980. &opt,
  13981. #endif
  13982. sizeof(opt));
  13983. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13984. ::listen(srv, 1);
  13985. sockaddr_in cli_addr{};
  13986. socklen_t cli_len = sizeof(cli_addr);
  13987. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13988. if (cli != INVALID_SOCKET) {
  13989. char buf[4096];
  13990. ::recv(cli, buf, sizeof(buf), 0);
  13991. auto content_length = std::to_string(DATA_SIZE);
  13992. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13993. "Content-Length: " +
  13994. content_length +
  13995. "\r\n"
  13996. "Connection: close\r\n"
  13997. "\r\n";
  13998. ::send(cli,
  13999. #ifdef _WIN32
  14000. static_cast<const char *>(response_header.c_str()),
  14001. static_cast<int>(response_header.size()),
  14002. #else
  14003. response_header.c_str(), response_header.size(),
  14004. #endif
  14005. 0);
  14006. std::string chunk(64 * 1024, 'A');
  14007. size_t total_sent = 0;
  14008. while (total_sent < DATA_SIZE) {
  14009. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14010. auto sent = ::send(cli,
  14011. #ifdef _WIN32
  14012. static_cast<const char *>(chunk.c_str()),
  14013. static_cast<int>(to_send),
  14014. #else
  14015. chunk.c_str(), to_send,
  14016. #endif
  14017. 0);
  14018. if (sent <= 0) break;
  14019. total_sent += static_cast<size_t>(sent);
  14020. }
  14021. #ifdef _WIN32
  14022. ::shutdown(cli, SD_SEND);
  14023. #else
  14024. ::shutdown(cli, SHUT_WR);
  14025. #endif
  14026. char drain[1024];
  14027. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14028. detail::close_socket(cli);
  14029. }
  14030. detail::close_socket(srv);
  14031. });
  14032. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14033. size_t total_received = 0;
  14034. {
  14035. Client cli("127.0.0.1", PORT + 2);
  14036. cli.set_read_timeout(10, 0);
  14037. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14038. auto res =
  14039. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14040. total_received += data_length;
  14041. return true;
  14042. });
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. EXPECT_EQ(StatusCode::OK_200, res->status);
  14045. }
  14046. server_thread.join();
  14047. EXPECT_EQ(total_received, DATA_SIZE)
  14048. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14049. << " bytes (larger than " << DATA_SIZE
  14050. << " bytes response), content_receiver should read all data, but only "
  14051. "read "
  14052. << total_received << " bytes.";
  14053. }
  14054. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14055. // Regression test for "zip bomb" attack on the client side: a malicious server
  14056. // sends a small gzip-compressed response that decompresses to a huge payload.
  14057. // The client must enforce payload_max_length on the decompressed size.
  14058. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14059. constexpr size_t DECOMPRESSED_SIZE =
  14060. 10 * 1024 * 1024; // 10MB after decompression
  14061. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14062. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14063. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14064. std::string compressed;
  14065. {
  14066. httplib::detail::gzip_compressor compressor;
  14067. bool ok =
  14068. compressor.compress(uncompressed.data(), uncompressed.size(),
  14069. /*last=*/true, [&](const char *buf, size_t len) {
  14070. compressed.append(buf, len);
  14071. return true;
  14072. });
  14073. ASSERT_TRUE(ok);
  14074. }
  14075. // Sanity: compressed data should be much smaller than the decompressed size
  14076. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14077. #ifndef _WIN32
  14078. signal(SIGPIPE, SIG_IGN);
  14079. #endif
  14080. // Set up the listening socket in the main thread so the server is guaranteed
  14081. // to be ready before the client connects (eliminates race condition).
  14082. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14083. default_socket_options(srv);
  14084. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14085. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14086. sockaddr_in addr{};
  14087. addr.sin_family = AF_INET;
  14088. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14089. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14090. int opt = 1;
  14091. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14092. #ifdef _WIN32
  14093. reinterpret_cast<const char *>(&opt),
  14094. #else
  14095. &opt,
  14096. #endif
  14097. sizeof(opt));
  14098. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14099. ASSERT_EQ(0, ::listen(srv, 1));
  14100. auto server_thread = std::thread([&compressed, srv] {
  14101. sockaddr_in cli_addr{};
  14102. socklen_t cli_len = sizeof(cli_addr);
  14103. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14104. if (cli != INVALID_SOCKET) {
  14105. // Read the full HTTP request (until \r\n\r\n)
  14106. char buf[4096];
  14107. size_t total = 0;
  14108. while (total < sizeof(buf)) {
  14109. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14110. if (n <= 0) break;
  14111. total += static_cast<size_t>(n);
  14112. // Check for end of headers
  14113. if (total >= 4) {
  14114. std::string req(buf, total);
  14115. if (req.find("\r\n\r\n") != std::string::npos) break;
  14116. }
  14117. }
  14118. // Malicious response: gzip-compressed body, no Content-Length
  14119. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14120. "Content-Encoding: gzip\r\n"
  14121. "Connection: close\r\n"
  14122. "\r\n";
  14123. ::send(cli,
  14124. #ifdef _WIN32
  14125. static_cast<const char *>(response_header.c_str()),
  14126. static_cast<int>(response_header.size()),
  14127. #else
  14128. response_header.c_str(), response_header.size(),
  14129. #endif
  14130. 0);
  14131. // Send the compressed payload (small on the wire, huge when decompressed)
  14132. size_t total_sent = 0;
  14133. while (total_sent < compressed.size()) {
  14134. auto to_send = std::min(compressed.size() - total_sent,
  14135. static_cast<size_t>(64 * 1024));
  14136. auto sent =
  14137. ::send(cli,
  14138. #ifdef _WIN32
  14139. static_cast<const char *>(compressed.c_str() + total_sent),
  14140. static_cast<int>(to_send),
  14141. #else
  14142. compressed.c_str() + total_sent, to_send,
  14143. #endif
  14144. 0);
  14145. if (sent <= 0) break;
  14146. total_sent += static_cast<size_t>(sent);
  14147. }
  14148. detail::close_socket(cli);
  14149. }
  14150. });
  14151. auto se = detail::scope_exit([&] {
  14152. detail::close_socket(srv);
  14153. server_thread.join();
  14154. });
  14155. size_t total_decompressed = 0;
  14156. {
  14157. Client cli("127.0.0.1", PORT + 3);
  14158. cli.set_read_timeout(5, 0);
  14159. cli.set_decompress(true);
  14160. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14161. auto stream = cli.open_stream("GET", "/zipbomb");
  14162. ASSERT_TRUE(stream.is_valid());
  14163. char buffer[64 * 1024];
  14164. ssize_t n;
  14165. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14166. total_decompressed += static_cast<size_t>(n);
  14167. }
  14168. }
  14169. // The decompressed size must be capped by payload_max_length. Without
  14170. // protection, the client would decompress the full 10MB from a tiny
  14171. // compressed payload, enabling a zip bomb DoS attack.
  14172. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14173. << "Client decompressed " << total_decompressed
  14174. << " bytes from a gzip response. The decompressed size should be "
  14175. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14176. }
  14177. #endif
  14178. TEST(HostAndPortPropertiesTest, NoSSL) {
  14179. httplib::Client cli("www.google.com", 1234);
  14180. ASSERT_EQ("www.google.com", cli.host());
  14181. ASSERT_EQ(1234, cli.port());
  14182. }
  14183. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14184. httplib::Client cli("www.google.com:1234");
  14185. ASSERT_EQ("www.google.com", cli.host());
  14186. ASSERT_EQ(1234, cli.port());
  14187. }
  14188. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14189. // Port number that overflows int — should not crash, client becomes invalid
  14190. httplib::Client cli("http://www.google.com:99999999999999999999");
  14191. ASSERT_FALSE(cli.is_valid());
  14192. }
  14193. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14194. // Port 99999 exceeds valid range (1-65535) — should not crash
  14195. httplib::Client cli("http://www.google.com:99999");
  14196. ASSERT_FALSE(cli.is_valid());
  14197. auto res = cli.Get("/");
  14198. EXPECT_FALSE(res);
  14199. EXPECT_EQ(Error::Connection, res.error());
  14200. }
  14201. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14202. httplib::Client cli("http://user:pass@localhost:1234");
  14203. ASSERT_FALSE(cli.is_valid());
  14204. EXPECT_FALSE(cli.Get("/"));
  14205. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14206. }
  14207. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14208. httplib::Client cli("http://www.google.com:80abc");
  14209. ASSERT_FALSE(cli.is_valid());
  14210. }
  14211. #ifdef CPPHTTPLIB_SSL_ENABLED
  14212. TEST(HostAndPortPropertiesTest, SSL) {
  14213. httplib::SSLClient cli("www.google.com");
  14214. ASSERT_EQ("www.google.com", cli.host());
  14215. ASSERT_EQ(443, cli.port());
  14216. }
  14217. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14218. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14219. std::string cert;
  14220. read_file(CA_CERT_FILE, cert);
  14221. httplib::SSLClient httplib_client("www.google.com");
  14222. // Load CA store first time
  14223. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14224. // Load CA store second time (update)
  14225. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14226. // Verify client is still valid and can make connections
  14227. httplib_client.enable_server_certificate_verification(true);
  14228. auto res = httplib_client.Get("/");
  14229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14230. // Google may return 200 or 301 depending on various factors
  14231. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14232. res->status == StatusCode::MovedPermanently_301);
  14233. }
  14234. TEST(SSLClientTest, ServerNameIndication_Online) {
  14235. auto host = "httpbingo.org";
  14236. auto path = std::string{"/get"};
  14237. SSLClient cli(host, 443);
  14238. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  14239. SKIP_ON_GATEWAY_ERROR(res);
  14240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14241. ASSERT_EQ(StatusCode::OK_200, res->status);
  14242. }
  14243. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14244. // Use a site that will cause SSL verification failure due to self-signed cert
  14245. SSLClient cli("self-signed.badssl.com", 443);
  14246. cli.enable_server_certificate_verification(true);
  14247. auto res = cli.Get("/");
  14248. ASSERT_TRUE(!res);
  14249. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14250. // Verify backend error is captured for SSLServerVerification
  14251. // This occurs when certificate verification fails
  14252. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14253. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14254. EXPECT_NE(0UL, res.ssl_backend_error());
  14255. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14256. res.ssl_error());
  14257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14258. #if !defined(_WIN32) || \
  14259. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14260. // On non-Windows or when Windows Schannel is disabled, the error comes
  14261. // from OpenSSL's verification
  14262. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14263. res.ssl_backend_error());
  14264. #endif
  14265. #endif
  14266. }
  14267. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14268. // Use a site where hostname doesn't match the certificate
  14269. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14270. SSLClient cli("wrong.host.badssl.com", 443);
  14271. cli.enable_server_certificate_verification(true);
  14272. cli.enable_server_hostname_verification(true);
  14273. auto res = cli.Get("/");
  14274. ASSERT_TRUE(!res);
  14275. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14276. // Verify backend error is captured for hostname verification failure
  14277. EXPECT_NE(0UL, res.ssl_backend_error());
  14278. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14279. res.ssl_error());
  14280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14281. #if !defined(_WIN32) || \
  14282. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14283. // On non-Windows or when Windows Schannel is disabled, the error comes
  14284. // from OpenSSL's hostname verification
  14285. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14286. res.ssl_backend_error());
  14287. #endif
  14288. #endif
  14289. }
  14290. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14291. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14292. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14293. SSLClient cli("www.google.com", 443);
  14294. cli.enable_server_certificate_verification(true);
  14295. auto res = cli.Get("/");
  14296. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14297. }
  14298. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14299. SSLClient cli("www.google.com", 443);
  14300. cli.enable_server_certificate_verification(true);
  14301. cli.enable_windows_certificate_verification(false);
  14302. auto res = cli.Get("/");
  14303. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14304. }
  14305. // The server sends an intermediate cross-signed by a root Windows trusts,
  14306. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14307. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14308. SSLClient cli("accounts.spotify.com", 443);
  14309. auto res = cli.Get("/");
  14310. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14311. << " ssl_backend_error=" << res.ssl_backend_error();
  14312. }
  14313. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14314. // policy status, which no backend reports for a self-signed certificate.
  14315. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14316. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14317. ASSERT_TRUE(svr.is_valid());
  14318. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14319. auto se = detail::scope_exit([&] {
  14320. svr.stop();
  14321. t.join();
  14322. ASSERT_FALSE(svr.is_running());
  14323. });
  14324. svr.wait_until_ready();
  14325. SSLClient cli("127.0.0.1", PORT);
  14326. cli.set_connection_timeout(30);
  14327. auto res = cli.Get("/");
  14328. ASSERT_FALSE(res);
  14329. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14330. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14331. }
  14332. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14333. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14336. auto se = detail::scope_exit([&] {
  14337. svr.stop();
  14338. t.join();
  14339. ASSERT_FALSE(svr.is_running());
  14340. });
  14341. svr.wait_until_ready();
  14342. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14343. {
  14344. ws::WebSocketClient client(url);
  14345. auto res = client.connect();
  14346. ASSERT_FALSE(res);
  14347. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14348. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14349. res.ssl_backend_error());
  14350. }
  14351. {
  14352. ws::WebSocketClient client(url);
  14353. client.enable_windows_certificate_verification(false);
  14354. auto res = client.connect();
  14355. ASSERT_FALSE(res);
  14356. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14357. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14358. res.ssl_backend_error());
  14359. }
  14360. }
  14361. #endif
  14362. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14363. Client cli("https://google.com");
  14364. auto res = cli.Get("/");
  14365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14366. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14367. }
  14368. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14369. SSLClient cli("google.com");
  14370. cli.set_ca_cert_path(CA_CERT_FILE);
  14371. auto res = cli.Get("/");
  14372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14373. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14374. }
  14375. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14376. SSLClient cli("google.com");
  14377. cli.enable_server_certificate_verification(true);
  14378. cli.set_ca_cert_path("hello");
  14379. auto res = cli.Get("/");
  14380. ASSERT_TRUE(!res);
  14381. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14382. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14383. // should be set
  14384. EXPECT_EQ(0, res.ssl_error());
  14385. // Verify backend error is captured for SSLLoadingCerts
  14386. // This error occurs when loading CA certificates fails
  14387. EXPECT_NE(0UL, res.ssl_backend_error());
  14388. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14389. // OpenSSL specific error codes:
  14390. // > openssl errstr 0x80000002
  14391. // error:80000002:system library::No such file or directory
  14392. // > openssl errstr 0xA000126
  14393. // error:0A000126:SSL routines::unexpected eof while reading
  14394. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14395. res.ssl_backend_error() == 0xA000126);
  14396. #endif
  14397. }
  14398. TEST(SSLClientTest, ServerCertificateVerification4) {
  14399. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14400. ASSERT_TRUE(svr.is_valid());
  14401. svr.Get("/test", [&](const Request &, Response &res) {
  14402. res.set_content("test", "text/plain");
  14403. svr.stop();
  14404. ASSERT_TRUE(true);
  14405. });
  14406. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14407. auto se = detail::scope_exit([&] {
  14408. t.join();
  14409. ASSERT_FALSE(svr.is_running());
  14410. });
  14411. svr.wait_until_ready();
  14412. SSLClient cli("127.0.0.1", PORT);
  14413. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14414. cli.enable_server_certificate_verification(true);
  14415. cli.set_connection_timeout(30);
  14416. auto res = cli.Get("/test");
  14417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14418. ASSERT_EQ(StatusCode::OK_200, res->status);
  14419. }
  14420. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14421. std::string cert;
  14422. read_file(CA_CERT_FILE, cert);
  14423. SSLClient cli("google.com");
  14424. cli.load_ca_cert_store(cert.data(), cert.size());
  14425. const auto res = cli.Get("/");
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14428. }
  14429. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14430. // clang-format off
  14431. static constexpr char cert[] =
  14432. "GlobalSign Root CA\n"
  14433. "==================\n"
  14434. "-----BEGIN CERTIFICATE-----\n"
  14435. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14436. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14437. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14438. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14439. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14440. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14441. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14442. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14443. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14444. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14445. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14446. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14447. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14448. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14449. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14450. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14451. "-----END CERTIFICATE-----\n";
  14452. // clang-format on
  14453. SSLClient cli("google.com");
  14454. cli.load_ca_cert_store(cert, sizeof(cert));
  14455. const auto res = cli.Get("/");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14458. }
  14459. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14460. SSLClient cli("www.youtube.com");
  14461. cli.set_ca_cert_path(CA_CERT_FILE);
  14462. cli.enable_server_certificate_verification(true);
  14463. cli.set_follow_location(true);
  14464. auto res = cli.Get("/");
  14465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14466. ASSERT_EQ(StatusCode::OK_200, res->status);
  14467. }
  14468. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14469. SSLClient cli("wWw.YouTube.Com");
  14470. cli.set_ca_cert_path(CA_CERT_FILE);
  14471. cli.enable_server_certificate_verification(true);
  14472. cli.enable_server_hostname_verification(true);
  14473. cli.set_follow_location(true);
  14474. auto res = cli.Get("/");
  14475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14476. ASSERT_EQ(StatusCode::OK_200, res->status);
  14477. }
  14478. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14479. SSLClient cli("gOoGlE.COm");
  14480. cli.enable_server_certificate_verification(true);
  14481. cli.enable_server_hostname_verification(true);
  14482. cli.set_follow_location(true);
  14483. auto res = cli.Get("/");
  14484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14485. ASSERT_EQ(StatusCode::OK_200, res->status);
  14486. }
  14487. TEST(SSLClientTest, Issue2004_Online) {
  14488. Client client("https://google.com");
  14489. client.set_follow_location(true);
  14490. auto res = client.Get("/");
  14491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14492. ASSERT_EQ(StatusCode::OK_200, res->status);
  14493. auto body = res->body;
  14494. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14495. }
  14496. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14497. // Create SSLClient with invalid cert/key to make is_valid() return false
  14498. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14499. "nonexistent_key.pem");
  14500. // is_valid() should be false due to cert loading failure
  14501. ASSERT_FALSE(cli.is_valid());
  14502. auto res = cli.Get("/");
  14503. ASSERT_FALSE(res);
  14504. EXPECT_EQ(Error::SSLConnection, res.error());
  14505. }
  14506. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14507. // Test for Issue #2251: SSL error not properly reported when client cert
  14508. // and key paths are swapped or mismatched
  14509. // This simulates the scenario where user accidentally swaps the cert and key
  14510. // files
  14511. // Using client cert file as private key and vice versa (completely wrong)
  14512. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14513. // Should fail validation due to cert/key mismatch
  14514. ASSERT_FALSE(cli.is_valid());
  14515. // Attempt to make a request should fail with proper error
  14516. auto res = cli.Get("/");
  14517. ASSERT_FALSE(res);
  14518. EXPECT_EQ(Error::SSLConnection, res.error());
  14519. // SSL error should be recorded in the Result object (this is the key fix for
  14520. // Issue #2251)
  14521. auto backend_error = res.ssl_backend_error();
  14522. EXPECT_NE(0u, backend_error);
  14523. }
  14524. // Tests cert/key mismatch detection at the TLS context level
  14525. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14526. // Test that using mismatched cert/key causes connection failure.
  14527. // We verify this at the SSLClient level rather than through internal
  14528. // TLS API functions.
  14529. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14530. cli.enable_server_certificate_verification(false);
  14531. cli.set_connection_timeout(2);
  14532. // The mismatch should cause a connection or handshake error
  14533. auto res = cli.Get("/test");
  14534. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14535. // Either way, the request should fail
  14536. EXPECT_FALSE(res);
  14537. }
  14538. #endif
  14539. #if 0
  14540. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14541. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14542. ASSERT_TRUE(cli != nullptr);
  14543. cli->set_address_family(AF_INET6);
  14544. cli->set_interface("en0");
  14545. auto res = cli->Get("/get");
  14546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14547. ASSERT_EQ(StatusCode::OK_200, res->status);
  14548. }
  14549. #endif
  14550. // Client certificate tests - work with all TLS backends
  14551. #ifdef CPPHTTPLIB_SSL_ENABLED
  14552. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14553. void ClientCertPresent(
  14554. const std::string &client_cert_file,
  14555. const std::string &client_private_key_file,
  14556. const std::string &client_encrypted_private_key_pass = std::string(),
  14557. const ClientCertServerSetup &setup = nullptr) {
  14558. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14559. ASSERT_TRUE(svr.is_valid());
  14560. if (setup) { setup(svr); }
  14561. svr.Get("/test", [&](const Request &req, Response &res) {
  14562. res.set_content("test", "text/plain");
  14563. auto cert = req.peer_cert();
  14564. ASSERT_TRUE(static_cast<bool>(cert));
  14565. std::string common_name = cert.subject_cn();
  14566. EXPECT_EQ("Common Name", common_name);
  14567. });
  14568. auto port = svr.bind_to_any_port(HOST);
  14569. ASSERT_LT(0, port);
  14570. thread t = thread([&]() { svr.listen_after_bind(); });
  14571. auto se = detail::scope_exit([&] {
  14572. svr.stop();
  14573. t.join();
  14574. ASSERT_FALSE(svr.is_running());
  14575. });
  14576. svr.wait_until_ready();
  14577. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14578. client_encrypted_private_key_pass);
  14579. cli.enable_server_certificate_verification(false);
  14580. cli.set_connection_timeout(30);
  14581. auto res = cli.Get("/test");
  14582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14583. ASSERT_EQ(StatusCode::OK_200, res->status);
  14584. }
  14585. TEST(SSLClientServerTest, ClientCertPresent) {
  14586. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14587. }
  14588. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14589. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14590. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14591. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14592. }
  14593. // Expects svr, which must require client certificates, to reject a client
  14594. // that has none
  14595. void RejectsClientWithoutCert(SSLServer &svr) {
  14596. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14597. auto port = svr.bind_to_any_port(HOST);
  14598. ASSERT_LT(0, port);
  14599. thread t = thread([&]() { svr.listen_after_bind(); });
  14600. auto se = detail::scope_exit([&] {
  14601. svr.stop();
  14602. t.join();
  14603. ASSERT_FALSE(svr.is_running());
  14604. });
  14605. svr.wait_until_ready();
  14606. SSLClient cli(HOST, port);
  14607. cli.set_connection_timeout(30);
  14608. // Skip the server certificate check, so that the request fails because the
  14609. // client certificate is missing rather than because cert.pem is not trusted
  14610. cli.enable_server_certificate_verification(false);
  14611. auto res = cli.Get("/test");
  14612. ASSERT_FALSE(res);
  14613. // The server rejects the client during the handshake, or on TLS 1.3 right
  14614. // after it, which the client notices on its first write or read
  14615. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14616. res.error() == Error::Write || res.error() == Error::Read)
  14617. << to_string(res.error());
  14618. if (res.error() == Error::SSLConnection) {
  14619. EXPECT_NE(0UL, res.ssl_backend_error());
  14620. }
  14621. // A rejection noticed on the write keeps the TLS error the write hit
  14622. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14623. }
  14624. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14626. ASSERT_TRUE(svr.is_valid());
  14627. if (setup) { setup(svr); }
  14628. RejectsClientWithoutCert(svr);
  14629. }
  14630. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14631. // A server that requires client certificates must keep requiring them after
  14632. // setup changes it, and keep accepting a client that has one
  14633. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14634. ClientCertMissing(setup);
  14635. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14636. setup);
  14637. }
  14638. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14639. ClientCertStillRequired([](SSLServer &svr) {
  14640. ASSERT_TRUE(tls::set_verify_callback(
  14641. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14642. });
  14643. }
  14644. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14645. ClientCertStillRequired([](SSLServer &svr) {
  14646. ASSERT_TRUE(tls::set_verify_callback(
  14647. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14648. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14649. });
  14650. }
  14651. // The client verifies the server certificate during the handshake, so a
  14652. // server that fails the check never gets the client certificate, even when a
  14653. // verifier of the client's own accepts it
  14654. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14655. struct Case {
  14656. const char *trusted_ca;
  14657. const char *host;
  14658. Error error;
  14659. };
  14660. // cert2.pem names localhost: the first client does not trust it, and the
  14661. // second trusts it but asks for another name
  14662. for (const auto &c :
  14663. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14664. Case{SERVER_CERT2_FILE, "example.com",
  14665. Error::SSLServerHostnameVerification}}) {
  14666. for (auto with_verifier : {false, true}) {
  14667. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14668. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14669. CLIENT_CA_CERT_FILE);
  14670. ASSERT_TRUE(svr.is_valid());
  14671. std::atomic<bool> got_client_cert{false};
  14672. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14673. [&](const tls::VerifyContext &) {
  14674. got_client_cert = true;
  14675. return true;
  14676. }));
  14677. auto port = svr.bind_to_any_port("127.0.0.1");
  14678. ASSERT_LT(0, port);
  14679. thread t = thread([&] { svr.listen_after_bind(); });
  14680. svr.wait_until_ready();
  14681. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14682. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14683. cli.set_ca_cert_path(c.trusted_ca);
  14684. if (with_verifier) {
  14685. cli.set_server_certificate_verifier(
  14686. [](const tls::VerifyContext &) { return true; });
  14687. }
  14688. auto res = cli.Get("/");
  14689. EXPECT_FALSE(res);
  14690. EXPECT_EQ(c.error, res.error());
  14691. svr.stop();
  14692. t.join();
  14693. EXPECT_FALSE(got_client_cert);
  14694. }
  14695. }
  14696. }
  14697. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14698. std::string cert_pem, key_pem, ca_pem;
  14699. read_file(SERVER_CERT_FILE, cert_pem);
  14700. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14701. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14702. ASSERT_TRUE(
  14703. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14704. }
  14705. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14707. ASSERT_TRUE(svr.is_valid());
  14708. UpdateCertsPemWithClientCA(svr);
  14709. RejectsClientWithoutCert(svr);
  14710. }
  14711. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14712. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14713. }
  14714. // A TLS error from one request must not show up in a later request's Result
  14715. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14717. ASSERT_TRUE(svr.is_valid());
  14718. svr.Get("/test", [](const Request &, Response &res) {
  14719. res.set_content("test", "text/plain");
  14720. });
  14721. auto port = svr.bind_to_any_port(HOST);
  14722. ASSERT_LT(0, port);
  14723. thread t = thread([&]() { svr.listen_after_bind(); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. ASSERT_FALSE(svr.is_running());
  14728. });
  14729. svr.wait_until_ready();
  14730. SSLClient cli(HOST, port);
  14731. cli.set_connection_timeout(30);
  14732. cli.enable_server_hostname_verification(false);
  14733. // cert.pem is not trusted, so the handshake fails
  14734. ASSERT_FALSE(cli.Get("/test"));
  14735. cli.enable_server_certificate_verification(false);
  14736. auto res = cli.Get("/test");
  14737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14738. EXPECT_EQ(0, res.ssl_error());
  14739. EXPECT_EQ(0UL, res.ssl_backend_error());
  14740. }
  14741. // PEM memory-based constructor tests (works with all TLS backends).
  14742. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14743. // terminator after it.
  14744. void PemMemoryClientCertPresent(
  14745. const std::string &client_cert_file,
  14746. const std::string &client_private_key_file,
  14747. const std::string &client_encrypted_private_key_pass = std::string(),
  14748. bool exact_size = false) {
  14749. // Read PEM files into memory
  14750. std::string server_cert_pem, server_key_pem;
  14751. std::string client_ca_pem;
  14752. std::string client_cert_pem, client_key_pem;
  14753. read_file(SERVER_CERT_FILE, server_cert_pem);
  14754. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14755. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14756. read_file(client_cert_file, client_cert_pem);
  14757. read_file(client_private_key_file, client_key_pem);
  14758. std::list<std::vector<char>> exact_copies;
  14759. auto data = [&](const std::string &pem) -> const char * {
  14760. if (!exact_size) { return pem.c_str(); }
  14761. exact_copies.emplace_back(pem.begin(), pem.end());
  14762. return exact_copies.back().data();
  14763. };
  14764. // Create server with PEM memory
  14765. SSLServer::PemMemory server_pem = {
  14766. data(server_cert_pem),
  14767. server_cert_pem.size(),
  14768. data(server_key_pem),
  14769. server_key_pem.size(),
  14770. data(client_ca_pem),
  14771. client_ca_pem.size(),
  14772. nullptr // no password for server key
  14773. };
  14774. SSLServer svr(server_pem);
  14775. ASSERT_TRUE(svr.is_valid());
  14776. svr.Get("/test", [&](const Request &req, Response &res) {
  14777. res.set_content("test", "text/plain");
  14778. auto cert = req.peer_cert();
  14779. ASSERT_TRUE(static_cast<bool>(cert));
  14780. EXPECT_EQ("Common Name", cert.subject_cn());
  14781. });
  14782. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14783. auto se = detail::scope_exit([&] {
  14784. svr.stop();
  14785. t.join();
  14786. ASSERT_FALSE(svr.is_running());
  14787. });
  14788. svr.wait_until_ready();
  14789. // Create client with PEM memory
  14790. const char *password = client_encrypted_private_key_pass.empty()
  14791. ? nullptr
  14792. : client_encrypted_private_key_pass.c_str();
  14793. SSLClient::PemMemory client_pem = {
  14794. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14795. client_key_pem.size(), password};
  14796. SSLClient cli(HOST, PORT, client_pem);
  14797. cli.enable_server_certificate_verification(false);
  14798. cli.set_connection_timeout(30);
  14799. auto res = cli.Get("/test");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. ASSERT_EQ(StatusCode::OK_200, res->status);
  14802. }
  14803. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14804. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14805. }
  14806. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14807. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14808. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14809. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14810. }
  14811. // A server built from PEM memory with a client CA requires client certificates,
  14812. // also when the CA is a NUL-terminated string passed with a length of 0
  14813. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14814. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14815. read_file(SERVER_CERT_FILE, server_cert_pem);
  14816. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14817. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14818. SSLServer::PemMemory server_pem = {
  14819. server_cert_pem.c_str(),
  14820. server_cert_pem.size(),
  14821. server_key_pem.c_str(),
  14822. server_key_pem.size(),
  14823. client_ca_pem.c_str(),
  14824. client_ca_pem.size(),
  14825. nullptr // no password for server key
  14826. };
  14827. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14828. SCOPED_TRACE(client_ca_pem_len);
  14829. server_pem.client_ca_pem_len = client_ca_pem_len;
  14830. SSLServer svr(server_pem);
  14831. ASSERT_TRUE(svr.is_valid());
  14832. RejectsClientWithoutCert(svr);
  14833. }
  14834. // An empty CA fails to load instead of turning the check off
  14835. server_pem.client_ca_pem = "";
  14836. server_pem.client_ca_pem_len = 0;
  14837. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14838. }
  14839. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14840. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14841. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14842. true);
  14843. }
  14844. // A length shorter than the PEM cuts it short, so it no longer loads
  14845. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14846. std::string cert, key;
  14847. read_file(SERVER_CERT_FILE, cert);
  14848. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14849. for (auto cut_cert : {true, false}) {
  14850. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14851. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14852. SSLServer::PemMemory server_pem = {
  14853. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14854. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14855. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14856. key_len, nullptr};
  14857. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14858. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14859. key.c_str(), key_len, nullptr};
  14860. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14861. }
  14862. }
  14863. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14864. class NoListenSSLServer : public SSLServer {
  14865. public:
  14866. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14867. const char *client_ca_cert_file_path,
  14868. const char *client_ca_cert_dir_path = nullptr)
  14869. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14870. client_ca_cert_dir_path),
  14871. stop_(false) {}
  14872. std::atomic_bool stop_;
  14873. private:
  14874. bool process_and_close_socket(socket_t /*sock*/) override {
  14875. // Don't create SSL context
  14876. while (!stop_.load()) {
  14877. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14878. }
  14879. return true;
  14880. }
  14881. };
  14882. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14883. CLIENT_CA_CERT_FILE);
  14884. ASSERT_TRUE(svr.is_valid());
  14885. // Keep-alive parking would bypass the override.
  14886. svr.set_keep_alive_parking(false);
  14887. svr.Get("/test", [&](const Request &, Response &res) {
  14888. res.set_content("test", "text/plain");
  14889. });
  14890. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14891. auto se = detail::scope_exit([&] {
  14892. svr.stop_ = true;
  14893. svr.stop();
  14894. t.join();
  14895. ASSERT_FALSE(svr.is_running());
  14896. });
  14897. svr.wait_until_ready();
  14898. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14899. cli.enable_server_certificate_verification(false);
  14900. cli.set_connection_timeout(1);
  14901. auto res = cli.Get("/test");
  14902. ASSERT_TRUE(!res);
  14903. EXPECT_EQ(Error::SSLConnection, res.error());
  14904. // Timeout results in WantRead error code (maps to backend-specific value)
  14905. EXPECT_NE(0, res.ssl_error());
  14906. }
  14907. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14908. // Test SSLServer with client certificate verification using the standard
  14909. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14911. CLIENT_CA_CERT_DIR);
  14912. ASSERT_TRUE(svr.is_valid());
  14913. svr.Get("/test", [&](const Request &req, Response &res) {
  14914. res.set_content("test", "text/plain");
  14915. auto cert = req.peer_cert();
  14916. ASSERT_TRUE(static_cast<bool>(cert));
  14917. auto common_name = cert.subject_cn();
  14918. EXPECT_EQ("Common Name", common_name);
  14919. });
  14920. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14921. auto se = detail::scope_exit([&] {
  14922. svr.stop();
  14923. t.join();
  14924. ASSERT_FALSE(svr.is_running());
  14925. });
  14926. svr.wait_until_ready();
  14927. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14928. cli.enable_server_certificate_verification(false);
  14929. cli.set_connection_timeout(30);
  14930. auto res = cli.Get("/test");
  14931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14932. ASSERT_EQ(StatusCode::OK_200, res->status);
  14933. }
  14934. // Test verify_hostname on every backend: a host is named by a SAN only
  14935. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14936. using namespace httplib::tls;
  14937. // We need a running server to test against
  14938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14939. ASSERT_TRUE(svr.is_valid());
  14940. svr.Get("/test", [](const Request &, Response &res) {
  14941. res.set_content("ok", "text/plain");
  14942. });
  14943. thread t([&]() { svr.listen(HOST, PORT); });
  14944. auto se = detail::scope_exit([&] {
  14945. svr.stop();
  14946. t.join();
  14947. });
  14948. svr.wait_until_ready();
  14949. bool verify_callback_called = false;
  14950. bool verify_result_wrong = false;
  14951. SSLClient cli(HOST, PORT);
  14952. cli.enable_server_certificate_verification(true);
  14953. cli.set_ca_cert_path(CA_CERT_FILE);
  14954. cli.set_connection_timeout(5);
  14955. // Note: Test certificate has CN="Common Name", not "localhost"
  14956. bool verify_result_cn = false;
  14957. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14958. verify_callback_called = true;
  14959. if (!ctx.cert) return false;
  14960. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14961. verify_result_cn = ctx.check_hostname("Common Name");
  14962. // Test 2: wrong hostname should not match
  14963. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14964. return true; // Accept for the purpose of this test
  14965. });
  14966. auto res = cli.Get("/test");
  14967. // The request may succeed or fail depending on cert configuration
  14968. // but the callback should have been called
  14969. ASSERT_TRUE(verify_callback_called)
  14970. << "Verify callback should have been called";
  14971. EXPECT_FALSE(verify_result_cn)
  14972. << "verify_hostname must not match the certificate CN (no SAN)";
  14973. // Wrong hostname should not match
  14974. EXPECT_FALSE(verify_result_wrong)
  14975. << "verify_hostname should not match 'wronghost.example.com'";
  14976. }
  14977. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14978. // backend verifies it.
  14979. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14980. // Certificate CN is "localhost" and it carries no SAN.
  14981. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14982. ASSERT_TRUE(svr.is_valid());
  14983. svr.Get("/test", [](const Request &, Response &res) {
  14984. res.set_content("ok", "text/plain");
  14985. });
  14986. auto port = svr.bind_to_any_port(HOST);
  14987. thread t([&]() { svr.listen_after_bind(); });
  14988. auto se = detail::scope_exit([&] {
  14989. svr.stop();
  14990. t.join();
  14991. });
  14992. svr.wait_until_ready();
  14993. SSLClient cli("localhost", port);
  14994. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14995. cli.enable_server_certificate_verification(true);
  14996. cli.set_connection_timeout(5);
  14997. auto res = cli.Get("/test");
  14998. ASSERT_FALSE(res);
  14999. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15000. // The same certificate is accepted once host name verification is off, so the
  15001. // failure above is the host name and not the chain.
  15002. cli.enable_server_hostname_verification(false);
  15003. res = cli.Get("/test");
  15004. ASSERT_TRUE(res) << to_string(res.error());
  15005. EXPECT_EQ(StatusCode::OK_200, res->status);
  15006. }
  15007. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15008. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15009. // X509_check_ip behavior and must hold for every backend.
  15010. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15011. using namespace httplib::tls;
  15012. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15013. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15014. ASSERT_TRUE(svr.is_valid());
  15015. svr.Get("/test", [](const Request &, Response &res) {
  15016. res.set_content("ok", "text/plain");
  15017. });
  15018. thread t([&]() { svr.listen(HOST, PORT); });
  15019. auto se = detail::scope_exit([&] {
  15020. svr.stop();
  15021. t.join();
  15022. });
  15023. svr.wait_until_ready();
  15024. bool verify_callback_called = false;
  15025. bool ip_matched_via_cn = true;
  15026. SSLClient cli(HOST, PORT);
  15027. cli.enable_server_certificate_verification(true);
  15028. cli.set_ca_cert_path(CA_CERT_FILE);
  15029. cli.set_connection_timeout(5);
  15030. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15031. verify_callback_called = true;
  15032. if (!ctx.cert) return false;
  15033. // The IP appears only in the CN, so it must NOT be accepted.
  15034. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15035. return true; // Accept for the purpose of this test
  15036. });
  15037. cli.Get("/test");
  15038. ASSERT_TRUE(verify_callback_called)
  15039. << "Verify callback should have been called";
  15040. EXPECT_FALSE(ip_matched_via_cn)
  15041. << "An IP host must not be authenticated via the certificate CN";
  15042. }
  15043. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15044. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15045. using namespace httplib::tls;
  15046. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15047. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15048. ASSERT_TRUE(svr.is_valid());
  15049. svr.Get("/test", [](const Request &, Response &res) {
  15050. res.set_content("ok", "text/plain");
  15051. });
  15052. thread t([&]() { svr.listen(HOST, PORT); });
  15053. auto se = detail::scope_exit([&] {
  15054. svr.stop();
  15055. t.join();
  15056. });
  15057. svr.wait_until_ready();
  15058. bool verify_callback_called = false;
  15059. bool san_matched = false;
  15060. bool wrong_ipv6_matched = true;
  15061. bool cn_ipv6_matched = true;
  15062. SSLClient cli(HOST, PORT);
  15063. cli.enable_server_certificate_verification(true);
  15064. cli.set_ca_cert_path(CA_CERT_FILE);
  15065. cli.set_connection_timeout(5);
  15066. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15067. verify_callback_called = true;
  15068. if (!ctx.cert) return false;
  15069. // Matches the IPv6 iPAddress SAN.
  15070. san_matched = ctx.check_hostname("2001:db8::1");
  15071. // A different IPv6 address must not match.
  15072. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15073. // "::1" lives only in the CN, so it must not be accepted.
  15074. cn_ipv6_matched = ctx.check_hostname("::1");
  15075. return true; // Accept for the purpose of this test
  15076. });
  15077. cli.Get("/test");
  15078. ASSERT_TRUE(verify_callback_called)
  15079. << "Verify callback should have been called";
  15080. EXPECT_TRUE(san_matched)
  15081. << "verify_hostname should match an IPv6 iPAddress SAN";
  15082. EXPECT_FALSE(wrong_ipv6_matched)
  15083. << "verify_hostname should not match a non-matching IPv6 address";
  15084. EXPECT_FALSE(cn_ipv6_matched)
  15085. << "An IPv6 host must not be authenticated via the certificate CN";
  15086. }
  15087. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15088. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15089. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15090. using namespace httplib::tls;
  15091. // SANs: DNS:a.zz, IP:42.46.122.122
  15092. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15093. ASSERT_TRUE(svr.is_valid());
  15094. svr.Get("/test", [](const Request &, Response &res) {
  15095. res.set_content("ok", "text/plain");
  15096. });
  15097. auto port = svr.bind_to_any_port(HOST);
  15098. thread t([&]() { svr.listen_after_bind(); });
  15099. auto se = detail::scope_exit([&] {
  15100. svr.stop();
  15101. t.join();
  15102. });
  15103. svr.wait_until_ready();
  15104. bool verify_callback_called = false;
  15105. bool dns_san_matched = false;
  15106. bool ip_san_matched = false;
  15107. bool ip_matched_via_dns_san = true;
  15108. bool dns_matched_via_ip_san = true;
  15109. bool cn_matched_next_to_dns_san = true;
  15110. SSLClient cli(HOST, port);
  15111. cli.enable_server_certificate_verification(true);
  15112. cli.set_ca_cert_path(CA_CERT_FILE);
  15113. cli.set_connection_timeout(5);
  15114. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15115. verify_callback_called = true;
  15116. if (!ctx.cert) return false;
  15117. dns_san_matched = ctx.check_hostname("a.zz");
  15118. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15119. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15120. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15121. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15122. return true; // Accept for the purpose of this test
  15123. });
  15124. cli.Get("/test");
  15125. ASSERT_TRUE(verify_callback_called)
  15126. << "Verify callback should have been called";
  15127. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15128. EXPECT_TRUE(ip_san_matched)
  15129. << "verify_hostname should match an iPAddress SAN";
  15130. EXPECT_FALSE(ip_matched_via_dns_san)
  15131. << "An IP host must not be authenticated via a dNSName SAN";
  15132. EXPECT_FALSE(dns_matched_via_ip_san)
  15133. << "A DNS host must not be authenticated via an iPAddress SAN";
  15134. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15135. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15136. }
  15137. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15138. // "www.*.example.test" names one host and not every host under example.test.
  15139. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15140. using namespace httplib::tls;
  15141. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15142. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15143. ASSERT_TRUE(svr.is_valid());
  15144. svr.Get("/test", [](const Request &, Response &res) {
  15145. res.set_content("ok", "text/plain");
  15146. });
  15147. auto port = svr.bind_to_any_port(HOST);
  15148. thread t([&]() { svr.listen_after_bind(); });
  15149. auto se = detail::scope_exit([&] {
  15150. svr.stop();
  15151. t.join();
  15152. });
  15153. svr.wait_until_ready();
  15154. bool verify_callback_called = false;
  15155. bool leftmost_wildcard_matched = false;
  15156. bool wildcard_spanned_labels = true;
  15157. bool inner_wildcard_matched = true;
  15158. SSLClient cli(HOST, port);
  15159. cli.enable_server_certificate_verification(true);
  15160. cli.set_ca_cert_path(CA_CERT_FILE);
  15161. cli.set_connection_timeout(5);
  15162. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15163. verify_callback_called = true;
  15164. if (!ctx.cert) return false;
  15165. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15166. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15167. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15168. return true; // Accept for the purpose of this test
  15169. });
  15170. cli.Get("/test");
  15171. ASSERT_TRUE(verify_callback_called)
  15172. << "Verify callback should have been called";
  15173. EXPECT_TRUE(leftmost_wildcard_matched)
  15174. << "A leftmost wildcard should match a single label";
  15175. EXPECT_FALSE(wildcard_spanned_labels)
  15176. << "A wildcard label must not match more than one label";
  15177. EXPECT_FALSE(inner_wildcard_matched)
  15178. << "A wildcard outside the leftmost label must not be honoured";
  15179. }
  15180. // sans() must report each SAN entry under its own type.
  15181. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15182. using namespace httplib::tls;
  15183. // SANs: DNS:a.zz, IP:42.46.122.122
  15184. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15185. ASSERT_TRUE(svr.is_valid());
  15186. svr.Get("/test", [](const Request &, Response &res) {
  15187. res.set_content("ok", "text/plain");
  15188. });
  15189. auto port = svr.bind_to_any_port(HOST);
  15190. thread t([&]() { svr.listen_after_bind(); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. });
  15195. svr.wait_until_ready();
  15196. bool verify_callback_called = false;
  15197. std::vector<SanEntry> sans;
  15198. SSLClient cli(HOST, port);
  15199. cli.enable_server_certificate_verification(true);
  15200. cli.set_ca_cert_path(CA_CERT_FILE);
  15201. cli.set_connection_timeout(5);
  15202. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15203. verify_callback_called = true;
  15204. if (!ctx.cert) return false;
  15205. sans = ctx.sans();
  15206. return true; // Accept for the purpose of this test
  15207. });
  15208. cli.Get("/test");
  15209. ASSERT_TRUE(verify_callback_called)
  15210. << "Verify callback should have been called";
  15211. auto has_san = [&](SanType type, const std::string &value) {
  15212. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15213. return san.type == type && san.value == value;
  15214. });
  15215. };
  15216. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15217. << "sans() should report the dNSName SAN";
  15218. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15219. << "sans() should report the iPAddress SAN";
  15220. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15221. << "sans() must not report the dNSName SAN as an address";
  15222. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15223. << "sans() must not report the iPAddress SAN as a DNS name";
  15224. }
  15225. #endif
  15226. // mbedTLS-specific callback constructor test
  15227. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15228. #ifdef CPPHTTPLIB_SSL_ENABLED
  15229. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15230. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15231. ASSERT_TRUE(svr.is_valid());
  15232. // Set up a handler to verify client certificate is present
  15233. bool client_cert_verified = false;
  15234. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15235. // Verify that client certificate was provided
  15236. client_cert_verified = true;
  15237. res.set_content("success", "text/plain");
  15238. });
  15239. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15240. auto se = detail::scope_exit([&] {
  15241. svr.stop();
  15242. t.join();
  15243. ASSERT_FALSE(svr.is_running());
  15244. });
  15245. svr.wait_until_ready();
  15246. // Client with certificate
  15247. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15248. cli.enable_server_certificate_verification(false);
  15249. cli.set_connection_timeout(30);
  15250. auto res = cli.Get("/test");
  15251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15252. ASSERT_EQ(StatusCode::OK_200, res->status);
  15253. ASSERT_TRUE(client_cert_verified);
  15254. EXPECT_EQ("success", res->body);
  15255. }
  15256. #endif
  15257. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15258. // backends
  15259. #ifdef CPPHTTPLIB_SSL_ENABLED
  15260. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15261. using namespace httplib::tls;
  15262. // Test that when client CA cert file is provided,
  15263. // the server properly requests and validates client certificates
  15264. // Create a server with client authentication
  15265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15266. ASSERT_TRUE(svr.is_valid());
  15267. bool handler_called = false;
  15268. svr.Get("/test", [&](const Request &req, Response &res) {
  15269. handler_called = true;
  15270. // Verify that a client certificate was provided
  15271. auto cert = req.peer_cert();
  15272. ASSERT_TRUE(static_cast<bool>(cert));
  15273. // Get the issuer name
  15274. std::string issuer_str = cert.issuer_name();
  15275. ASSERT_FALSE(issuer_str.empty());
  15276. // The client certificate should be issued by our test CA
  15277. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15278. res.set_content("authenticated", "text/plain");
  15279. });
  15280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15281. auto se = detail::scope_exit([&] {
  15282. svr.stop();
  15283. t.join();
  15284. ASSERT_FALSE(svr.is_running());
  15285. });
  15286. svr.wait_until_ready();
  15287. // Connect with a client certificate issued by the CA
  15288. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15289. cli.enable_server_certificate_verification(false);
  15290. cli.set_connection_timeout(30);
  15291. auto res = cli.Get("/test");
  15292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15293. ASSERT_EQ(StatusCode::OK_200, res->status);
  15294. ASSERT_TRUE(handler_called);
  15295. EXPECT_EQ("authenticated", res->body);
  15296. }
  15297. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15298. using namespace httplib::tls;
  15299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15300. ASSERT_TRUE(svr.is_valid());
  15301. svr.Get("/test", [](const Request &, Response &res) {
  15302. res.set_content("ok", "text/plain");
  15303. });
  15304. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15305. auto se = detail::scope_exit([&] {
  15306. svr.stop();
  15307. t.join();
  15308. });
  15309. svr.wait_until_ready();
  15310. SSLClient cli(HOST, PORT);
  15311. cli.enable_server_certificate_verification(false);
  15312. cli.set_connection_timeout(30);
  15313. bool cert_checked = false;
  15314. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15315. if (ctx.cert) {
  15316. auto sans = ctx.sans();
  15317. // Test certificate may or may not have SANs - just verify the API
  15318. // works If SANs exist, verify the types are valid
  15319. for (const auto &san : sans) {
  15320. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15321. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15322. san.type == SanType::OTHER);
  15323. EXPECT_FALSE(san.value.empty());
  15324. }
  15325. cert_checked = true;
  15326. }
  15327. return true;
  15328. });
  15329. auto res = cli.Get("/test");
  15330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15331. EXPECT_TRUE(cert_checked);
  15332. }
  15333. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15334. using namespace httplib::tls;
  15335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15336. ASSERT_TRUE(svr.is_valid());
  15337. svr.Get("/test", [](const Request &, Response &res) {
  15338. res.set_content("ok", "text/plain");
  15339. });
  15340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15341. auto se = detail::scope_exit([&] {
  15342. svr.stop();
  15343. t.join();
  15344. });
  15345. svr.wait_until_ready();
  15346. SSLClient cli(HOST, PORT);
  15347. cli.enable_server_certificate_verification(false);
  15348. cli.set_connection_timeout(30);
  15349. bool validity_checked = false;
  15350. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15351. if (ctx.cert) {
  15352. time_t not_before = 0, not_after = 0;
  15353. bool result = ctx.validity(not_before, not_after);
  15354. EXPECT_TRUE(result);
  15355. // Verify that not_before < now < not_after for a valid cert
  15356. time_t now = time(nullptr);
  15357. EXPECT_LT(not_before, now);
  15358. EXPECT_GT(not_after, now);
  15359. validity_checked = true;
  15360. }
  15361. return true;
  15362. });
  15363. auto res = cli.Get("/test");
  15364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15365. EXPECT_TRUE(validity_checked);
  15366. }
  15367. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15368. using namespace httplib::tls;
  15369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15370. ASSERT_TRUE(svr.is_valid());
  15371. svr.Get("/test", [](const Request &, Response &res) {
  15372. res.set_content("ok", "text/plain");
  15373. });
  15374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15375. auto se = detail::scope_exit([&] {
  15376. svr.stop();
  15377. t.join();
  15378. });
  15379. svr.wait_until_ready();
  15380. SSLClient cli(HOST, PORT);
  15381. cli.enable_server_certificate_verification(false);
  15382. cli.set_connection_timeout(30);
  15383. bool serial_checked = false;
  15384. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15385. if (ctx.cert) {
  15386. std::string serial = ctx.serial();
  15387. EXPECT_FALSE(serial.empty());
  15388. // Serial should be a hex string
  15389. for (char c : serial) {
  15390. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15391. (c >= 'a' && c <= 'f'));
  15392. }
  15393. serial_checked = true;
  15394. }
  15395. return true;
  15396. });
  15397. auto res = cli.Get("/test");
  15398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15399. EXPECT_TRUE(serial_checked);
  15400. }
  15401. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15402. // Test 1: Valid CA file - no error should be recorded
  15403. {
  15404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15405. CLIENT_CA_CERT_FILE);
  15406. ASSERT_TRUE(svr.is_valid());
  15407. // With valid setup, last_ssl_error should be 0
  15408. EXPECT_EQ(0, svr.ssl_last_error());
  15409. }
  15410. // Test 2: Invalid CA file content
  15411. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15412. {
  15413. // Create a temporary file with completely invalid content
  15414. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15415. {
  15416. std::ofstream ofs(temp_invalid_ca);
  15417. ofs << "This is not a certificate file at all\n";
  15418. ofs << "Just plain text content\n";
  15419. }
  15420. // Create server with invalid CA file
  15421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15422. // Clean up temporary file
  15423. std::remove(temp_invalid_ca);
  15424. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15425. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15426. // Note: SSL_CTX_load_verify_locations typically fails first,
  15427. // but our error handling code path is still exercised
  15428. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15429. }
  15430. }
  15431. TEST(VerifyCallbackTest, VerifyContextFields) {
  15432. using namespace httplib::tls;
  15433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15434. ASSERT_TRUE(svr.is_valid());
  15435. svr.Get("/test", [](const Request &, Response &res) {
  15436. res.set_content("ok", "text/plain");
  15437. });
  15438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. });
  15443. svr.wait_until_ready();
  15444. SSLClient cli(HOST, PORT);
  15445. cli.enable_server_certificate_verification(false);
  15446. cli.set_connection_timeout(30);
  15447. int callback_count = 0;
  15448. bool saw_leaf_cert = false;
  15449. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15450. if (ctx.cert) {
  15451. callback_count++;
  15452. // We should see at least one certificate (the leaf)
  15453. std::string cn = ctx.subject_cn();
  15454. if (!cn.empty()) { saw_leaf_cert = true; }
  15455. // Verify context fields are populated
  15456. EXPECT_NE(ctx.session, nullptr);
  15457. EXPECT_GE(ctx.depth, 0);
  15458. }
  15459. return true;
  15460. });
  15461. auto res = cli.Get("/test");
  15462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15463. EXPECT_GT(callback_count, 0);
  15464. EXPECT_TRUE(saw_leaf_cert);
  15465. }
  15466. // A verifier that accepts runs alongside the built-in verification, and is the
  15467. // only check once that is turned off.
  15468. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15469. using namespace httplib::tls;
  15470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15471. ASSERT_TRUE(svr.is_valid());
  15472. svr.Get("/test", [](const Request &, Response &res) {
  15473. res.set_content("ok", "text/plain");
  15474. });
  15475. auto port = svr.bind_to_any_port(HOST);
  15476. thread t([&]() { svr.listen_after_bind(); });
  15477. auto se = detail::scope_exit([&] {
  15478. svr.stop();
  15479. t.join();
  15480. });
  15481. svr.wait_until_ready();
  15482. SSLClient cli(HOST, port);
  15483. cli.enable_server_hostname_verification(false);
  15484. auto calls = 0;
  15485. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15486. calls++;
  15487. return true;
  15488. });
  15489. // cert.pem is not trusted
  15490. auto res = cli.Get("/test");
  15491. ASSERT_FALSE(res);
  15492. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15493. EXPECT_GT(calls, 0);
  15494. cli.enable_server_certificate_verification(false);
  15495. res = cli.Get("/test");
  15496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15497. EXPECT_EQ("ok", res->body);
  15498. }
  15499. // A verifier belongs to the client that set it, not to the thread that set it.
  15500. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15501. using namespace httplib::tls;
  15502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15503. ASSERT_TRUE(svr.is_valid());
  15504. svr.Get("/test", [](const Request &, Response &res) {
  15505. res.set_content("ok", "text/plain");
  15506. });
  15507. auto port = svr.bind_to_any_port(HOST);
  15508. thread t([&]() { svr.listen_after_bind(); });
  15509. auto se = detail::scope_exit([&] {
  15510. svr.stop();
  15511. t.join();
  15512. });
  15513. svr.wait_until_ready();
  15514. auto rejecting_calls = 0;
  15515. SSLClient rejecting(HOST, port);
  15516. rejecting.enable_server_certificate_verification(false);
  15517. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15518. rejecting_calls++;
  15519. return false;
  15520. });
  15521. auto accepting_calls = 0;
  15522. SSLClient accepting(HOST, port);
  15523. accepting.enable_server_certificate_verification(false);
  15524. // Set on another thread than the requests below.
  15525. thread([&]() {
  15526. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15527. accepting_calls++;
  15528. return true;
  15529. });
  15530. }).join();
  15531. // Requested on another thread than the verifier was set on.
  15532. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15533. EXPECT_GT(rejecting_calls, 0);
  15534. auto res = accepting.Get("/test");
  15535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15536. EXPECT_GT(accepting_calls, 0);
  15537. }
  15538. // A verifier replaced while a handshake runs it lives until it returns.
  15539. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15540. using namespace httplib::tls;
  15541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15542. ASSERT_TRUE(svr.is_valid());
  15543. svr.Get("/test", [](const Request &, Response &res) {
  15544. res.set_content("ok", "text/plain");
  15545. });
  15546. auto port = svr.bind_to_any_port(HOST);
  15547. thread t([&]() { svr.listen_after_bind(); });
  15548. auto se = detail::scope_exit([&] {
  15549. svr.stop();
  15550. t.join();
  15551. });
  15552. svr.wait_until_ready();
  15553. SSLClient cli(HOST, port);
  15554. cli.enable_server_certificate_verification(false);
  15555. std::promise<void> entered;
  15556. std::promise<void> replaced;
  15557. auto replaced_future = replaced.get_future();
  15558. auto first_call = true;
  15559. // Long enough to live on the heap
  15560. std::string expected(64, 'v');
  15561. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15562. if (first_call) {
  15563. first_call = false;
  15564. entered.set_value();
  15565. replaced_future.wait();
  15566. }
  15567. return expected == std::string(64, 'v');
  15568. });
  15569. thread request([&]() {
  15570. auto res = cli.Get("/test");
  15571. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15572. });
  15573. entered.get_future().wait();
  15574. cli.set_server_certificate_verifier(
  15575. [](const VerifyContext &) { return true; });
  15576. replaced.set_value();
  15577. request.join();
  15578. }
  15579. // VerifyContext::session is the same handle the other tls:: functions take.
  15580. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15581. using namespace httplib::tls;
  15582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15583. ASSERT_TRUE(svr.is_valid());
  15584. svr.Get("/test", [](const Request &, Response &res) {
  15585. res.set_content("ok", "text/plain");
  15586. });
  15587. auto port = svr.bind_to_any_port(HOST);
  15588. thread t([&]() { svr.listen_after_bind(); });
  15589. auto se = detail::scope_exit([&] {
  15590. svr.stop();
  15591. t.join();
  15592. });
  15593. svr.wait_until_ready();
  15594. SSLClient cli(HOST, port);
  15595. cli.enable_server_certificate_verification(false);
  15596. session_t verifier_session = nullptr;
  15597. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15598. verifier_session = ctx.session;
  15599. return true;
  15600. });
  15601. session_t session_verifier_session = nullptr;
  15602. cli.set_session_verifier([&](session_t session) {
  15603. session_verifier_session = session;
  15604. return SSLVerifierResponse::NoDecisionMade;
  15605. });
  15606. auto res = cli.Get("/test");
  15607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15608. EXPECT_NE(nullptr, verifier_session);
  15609. EXPECT_EQ(session_verifier_session, verifier_session);
  15610. }
  15611. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15612. using httplib::tls::TlsError;
  15613. // Test that verify_error_to_string returns empty for success
  15614. std::string success_str = TlsError::verify_error_to_string(0);
  15615. EXPECT_TRUE(success_str.empty());
  15616. // Test that verify_error_to_string returns non-empty for error codes
  15617. // Using a common error code (certificate expired)
  15618. std::string error_str =
  15619. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15620. EXPECT_FALSE(error_str.empty());
  15621. }
  15622. TEST(SessionVerifierTest, CertificateAccepted) {
  15623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15624. ASSERT_TRUE(svr.is_valid());
  15625. svr.Get("/test", [](const Request &, Response &res) {
  15626. res.set_content("ok", "text/plain");
  15627. });
  15628. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15629. auto se = detail::scope_exit([&] {
  15630. svr.stop();
  15631. t.join();
  15632. });
  15633. svr.wait_until_ready();
  15634. SSLClient cli(HOST, PORT);
  15635. cli.enable_server_certificate_verification(false);
  15636. cli.set_connection_timeout(30);
  15637. bool callback_called = false;
  15638. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15639. EXPECT_NE(session, nullptr);
  15640. callback_called = true;
  15641. return SSLVerifierResponse::CertificateAccepted;
  15642. });
  15643. auto res = cli.Get("/test");
  15644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15645. EXPECT_EQ(200, res->status);
  15646. EXPECT_TRUE(callback_called);
  15647. }
  15648. TEST(SessionVerifierTest, CertificateRejected) {
  15649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15650. ASSERT_TRUE(svr.is_valid());
  15651. svr.Get("/test", [](const Request &, Response &res) {
  15652. res.set_content("ok", "text/plain");
  15653. });
  15654. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15655. auto se = detail::scope_exit([&] {
  15656. svr.stop();
  15657. t.join();
  15658. });
  15659. svr.wait_until_ready();
  15660. SSLClient cli(HOST, PORT);
  15661. cli.enable_server_certificate_verification(false);
  15662. cli.set_connection_timeout(30);
  15663. bool callback_called = false;
  15664. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15665. EXPECT_NE(session, nullptr);
  15666. callback_called = true;
  15667. return SSLVerifierResponse::CertificateRejected;
  15668. });
  15669. auto res = cli.Get("/test");
  15670. EXPECT_FALSE(res);
  15671. EXPECT_TRUE(callback_called);
  15672. }
  15673. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15675. ASSERT_TRUE(svr.is_valid());
  15676. svr.Get("/test", [](const Request &, Response &res) {
  15677. res.set_content("ok", "text/plain");
  15678. });
  15679. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15680. auto se = detail::scope_exit([&] {
  15681. svr.stop();
  15682. t.join();
  15683. });
  15684. svr.wait_until_ready();
  15685. // NoDecisionMade with verification disabled should succeed (no default check)
  15686. SSLClient cli(HOST, PORT);
  15687. cli.enable_server_certificate_verification(false);
  15688. cli.set_connection_timeout(30);
  15689. bool callback_called = false;
  15690. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15691. EXPECT_NE(session, nullptr);
  15692. callback_called = true;
  15693. return SSLVerifierResponse::NoDecisionMade;
  15694. });
  15695. auto res = cli.Get("/test");
  15696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15697. EXPECT_EQ(200, res->status);
  15698. EXPECT_TRUE(callback_called);
  15699. }
  15700. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15702. ASSERT_TRUE(svr.is_valid());
  15703. svr.Get("/test", [](const Request &, Response &res) {
  15704. res.set_content("ok", "text/plain");
  15705. });
  15706. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15707. auto se = detail::scope_exit([&] {
  15708. svr.stop();
  15709. t.join();
  15710. });
  15711. svr.wait_until_ready();
  15712. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15713. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15714. // so we only check that the request fails, not whether the callback was
  15715. // called.
  15716. SSLClient cli(HOST, PORT);
  15717. cli.enable_server_certificate_verification(true);
  15718. cli.set_connection_timeout(30);
  15719. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15720. EXPECT_NE(session, nullptr);
  15721. return SSLVerifierResponse::NoDecisionMade;
  15722. });
  15723. auto res = cli.Get("/test");
  15724. EXPECT_FALSE(res);
  15725. }
  15726. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15727. // Test SSL server using PemMemory constructor with client CA certificates
  15728. // Read PEM files
  15729. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15730. read_file(SERVER_CERT_FILE, server_cert_pem);
  15731. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15732. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15733. // Create SSLServer with PemMemory constructor including client CA
  15734. SSLServer::PemMemory server_pem = {
  15735. server_cert_pem.c_str(),
  15736. server_cert_pem.size(),
  15737. server_key_pem.c_str(),
  15738. server_key_pem.size(),
  15739. client_ca_pem.c_str(),
  15740. client_ca_pem.size(),
  15741. nullptr // no password for server key
  15742. };
  15743. SSLServer svr(server_pem);
  15744. ASSERT_TRUE(svr.is_valid());
  15745. // No SSL error should be recorded for valid setup
  15746. EXPECT_EQ(0, svr.ssl_last_error());
  15747. // Set up server endpoints
  15748. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15749. res.set_content("ok", "text/plain");
  15750. });
  15751. // Start server in a thread
  15752. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15753. svr.wait_until_ready();
  15754. // Connect with client certificate (using constructor with paths)
  15755. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15756. cli.enable_server_certificate_verification(false);
  15757. auto res = cli.Get("/test-pem-ca");
  15758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15759. EXPECT_EQ(200, res->status);
  15760. EXPECT_EQ("ok", res->body);
  15761. svr.stop();
  15762. server_thread.join();
  15763. }
  15764. #endif
  15765. #ifdef _WIN32
  15766. TEST(CleanupTest, WSACleanup) {
  15767. int ret = WSACleanup();
  15768. ASSERT_EQ(0, ret);
  15769. }
  15770. #endif
  15771. #ifndef CPPHTTPLIB_SSL_ENABLED
  15772. TEST(NoSSLSupport, SimpleInterface) {
  15773. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15774. }
  15775. #endif
  15776. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15777. TEST(InvalidScheme, SimpleInterface) {
  15778. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15779. }
  15780. #endif
  15781. TEST(NoScheme, SimpleInterface) {
  15782. Client cli("yahoo.com:80");
  15783. ASSERT_TRUE(cli.is_valid());
  15784. }
  15785. TEST(SendAPI, SimpleInterface_Online) {
  15786. Client cli("http://yahoo.com");
  15787. Request req;
  15788. req.method = "GET";
  15789. req.path = "/";
  15790. auto res = cli.send(req);
  15791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15792. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15793. }
  15794. TEST(SendAPI, WithParamsInRequest) {
  15795. Server svr;
  15796. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15797. EXPECT_TRUE(req.has_param("test"));
  15798. EXPECT_EQ("test_value", req.get_param_value("test"));
  15799. });
  15800. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. });
  15806. svr.wait_until_ready();
  15807. Client cli(HOST, PORT);
  15808. {
  15809. Request req;
  15810. req.method = "GET";
  15811. req.path = "/";
  15812. req.params.emplace("test", "test_value");
  15813. auto res = cli.send(req);
  15814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15815. }
  15816. {
  15817. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15819. }
  15820. }
  15821. TEST(ClientImplMethods, GetSocketTest) {
  15822. httplib::Server svr;
  15823. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15824. res.status = StatusCode::OK_200;
  15825. });
  15826. auto port = svr.bind_to_any_port("127.0.0.1");
  15827. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15828. auto se = detail::scope_exit([&] {
  15829. svr.stop();
  15830. thread.join();
  15831. ASSERT_FALSE(svr.is_running());
  15832. });
  15833. svr.wait_until_ready();
  15834. {
  15835. httplib::Client cli("127.0.0.1", port);
  15836. cli.set_keep_alive(true);
  15837. // Use the behavior of cpp-httplib of opening the connection
  15838. // only when the first request happens. If that changes,
  15839. // this test would be obsolete.
  15840. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15841. // This also implicitly tests the server. But other tests would fail much
  15842. // earlier than this one to be considered.
  15843. auto res = cli.Get("/");
  15844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15845. EXPECT_EQ(StatusCode::OK_200, res->status);
  15846. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15847. }
  15848. }
  15849. #ifdef CPPHTTPLIB_SSL_ENABLED
  15850. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15851. Client cli("http://yahoo.com");
  15852. auto res = cli.Get("/");
  15853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15854. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15855. cli.set_follow_location(true);
  15856. res = cli.Get("/");
  15857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15858. EXPECT_EQ(StatusCode::OK_200, res->status);
  15859. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15860. }
  15861. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15862. Client cli("https://yahoo.com");
  15863. auto res = cli.Get("/");
  15864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15865. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15866. cli.set_follow_location(true);
  15867. res = cli.Get("/");
  15868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15869. EXPECT_EQ(StatusCode::OK_200, res->status);
  15870. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15871. }
  15872. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15873. Client cli("https://yahoo.com");
  15874. auto res = cli.Get("/");
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. ASSERT_FALSE(!res);
  15877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15878. ASSERT_FALSE(res == nullptr);
  15879. ASSERT_TRUE(res != nullptr);
  15880. EXPECT_EQ(Error::Success, res.error());
  15881. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15882. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15883. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15884. cli.set_follow_location(true);
  15885. res = cli.Get("/");
  15886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15887. EXPECT_EQ(Error::Success, res.error());
  15888. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15889. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15890. EXPECT_EQ(StatusCode::OK_200, res->status);
  15891. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15892. }
  15893. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15894. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15895. Client cli("https://cdnjs.cloudflare.com");
  15896. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15897. Headers{{"Accept-Encoding", "br"}});
  15898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15899. EXPECT_EQ(StatusCode::OK_200, res->status);
  15900. EXPECT_EQ(287630U, res->body.size());
  15901. EXPECT_EQ("application/javascript; charset=utf-8",
  15902. res->get_header_value("Content-Type"));
  15903. }
  15904. #endif
  15905. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15906. #undef REDIR_HOST // Silence compiler warning
  15907. #define REDIR_HOST "https://httpbingo.org"
  15908. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15909. Client cli(REDIR_HOST);
  15910. cli.set_follow_location(true);
  15911. auto res = retry_gateway_errors([&] {
  15912. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15913. });
  15914. SKIP_ON_GATEWAY_ERROR(res);
  15915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15916. EXPECT_EQ(StatusCode::OK_200, res->status);
  15917. }
  15918. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15919. Client cli(REDIR_HOST);
  15920. cli.set_follow_location(true);
  15921. Params params;
  15922. params.emplace("url", "http://example.com");
  15923. params.emplace("status_code", "302");
  15924. auto res = retry_gateway_errors(
  15925. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15926. SKIP_ON_GATEWAY_ERROR(res);
  15927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15928. EXPECT_EQ(StatusCode::OK_200, res->status);
  15929. }
  15930. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15931. Client cli(REDIR_HOST);
  15932. cli.set_follow_location(true);
  15933. Params params;
  15934. params.emplace("url", "http://example.com");
  15935. auto res = retry_gateway_errors([&] {
  15936. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15937. });
  15938. SKIP_ON_GATEWAY_ERROR(res);
  15939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15940. EXPECT_EQ(StatusCode::OK_200, res->status);
  15941. }
  15942. TEST(HttpToHttpsRedirectTest, CertFile) {
  15943. auto ssl_port = PORT + 1;
  15944. Server svr;
  15945. ASSERT_TRUE(svr.is_valid());
  15946. svr.Get("/index", [&](const Request &, Response &res) {
  15947. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15948. "/index");
  15949. svr.stop();
  15950. });
  15951. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15952. ASSERT_TRUE(ssl_svr.is_valid());
  15953. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15954. res.set_content("test", "text/plain");
  15955. ssl_svr.stop();
  15956. });
  15957. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15958. thread t2 =
  15959. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15960. auto se = detail::scope_exit([&] {
  15961. t2.join();
  15962. t.join();
  15963. ASSERT_FALSE(svr.is_running());
  15964. });
  15965. svr.wait_until_ready();
  15966. ssl_svr.wait_until_ready();
  15967. Client cli("127.0.0.1", PORT);
  15968. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15969. cli.enable_server_certificate_verification(true);
  15970. cli.set_follow_location(true);
  15971. cli.set_connection_timeout(30);
  15972. auto res = cli.Get("/index");
  15973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15974. ASSERT_EQ(StatusCode::OK_200, res->status);
  15975. }
  15976. TEST(UppercaseSchemeTest, UsesTLS) {
  15977. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15978. ASSERT_TRUE(ssl_svr.is_valid());
  15979. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15980. res.set_content("test", "text/plain");
  15981. });
  15982. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15983. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15984. Server svr;
  15985. svr.Get("/index", [&](const Request &, Response &res) {
  15986. res.set_redirect(https_url + "/index");
  15987. });
  15988. auto port = svr.bind_to_any_port("127.0.0.1");
  15989. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15990. auto t2 = thread([&] { svr.listen_after_bind(); });
  15991. auto se = detail::scope_exit([&] {
  15992. svr.stop();
  15993. ssl_svr.stop();
  15994. t2.join();
  15995. t.join();
  15996. });
  15997. ssl_svr.wait_until_ready();
  15998. svr.wait_until_ready();
  15999. {
  16000. Client cli(https_url);
  16001. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16002. auto res = cli.Get("/index");
  16003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16004. EXPECT_EQ("test", res->body);
  16005. }
  16006. {
  16007. Client cli("127.0.0.1", port);
  16008. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16009. cli.set_follow_location(true);
  16010. auto res = cli.Get("/index");
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. EXPECT_EQ("test", res->body);
  16013. }
  16014. }
  16015. TEST(SSLClientRedirectTest, CertFile) {
  16016. auto ssl_port = PORT + 1;
  16017. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16018. ASSERT_TRUE(ssl_svr1.is_valid());
  16019. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16020. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16021. "/index");
  16022. ssl_svr1.stop();
  16023. });
  16024. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16025. ASSERT_TRUE(ssl_svr2.is_valid());
  16026. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16027. res.set_content("test", "text/plain");
  16028. ssl_svr2.stop();
  16029. });
  16030. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16031. thread t2 =
  16032. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16033. auto se = detail::scope_exit([&] {
  16034. t2.join();
  16035. t.join();
  16036. ASSERT_FALSE(ssl_svr1.is_running());
  16037. });
  16038. ssl_svr1.wait_until_ready();
  16039. ssl_svr2.wait_until_ready();
  16040. SSLClient cli("127.0.0.1", PORT);
  16041. std::string cert;
  16042. read_file(SERVER_CERT2_FILE, cert);
  16043. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16044. cli.enable_server_certificate_verification(true);
  16045. cli.set_follow_location(true);
  16046. cli.set_connection_timeout(30);
  16047. auto res = cli.Get("/index");
  16048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16049. ASSERT_EQ(StatusCode::OK_200, res->status);
  16050. }
  16051. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16052. // another port, so the client follows it with a new client.
  16053. static Result GetThroughTlsRedirectToDifferentPort(
  16054. const std::function<void(SSLClient &)> &setup,
  16055. const char *target_cert = SERVER_CERT2_FILE,
  16056. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16057. auto ssl_port = PORT + 1;
  16058. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16059. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16060. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16061. "/index");
  16062. });
  16063. SSLServer ssl_svr2(target_cert, target_key);
  16064. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16065. res.set_content("test", "text/plain");
  16066. });
  16067. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16068. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16069. auto se = detail::scope_exit([&] {
  16070. ssl_svr2.stop();
  16071. ssl_svr1.stop();
  16072. t2.join();
  16073. t.join();
  16074. });
  16075. ssl_svr1.wait_until_ready();
  16076. ssl_svr2.wait_until_ready();
  16077. SSLClient cli("127.0.0.1", PORT);
  16078. cli.set_follow_location(true);
  16079. cli.set_connection_timeout(30);
  16080. setup(cli);
  16081. return cli.Get("/index");
  16082. }
  16083. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16084. auto calls = 0;
  16085. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16086. cli.enable_server_certificate_verification(false);
  16087. // Accept the first server only.
  16088. cli.set_session_verifier([&](tls::session_t) {
  16089. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16090. : SSLVerifierResponse::CertificateRejected;
  16091. });
  16092. });
  16093. ASSERT_FALSE(res);
  16094. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16095. EXPECT_EQ(2, calls);
  16096. }
  16097. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16098. std::string pinned;
  16099. auto res = GetThroughTlsRedirectToDifferentPort(
  16100. [&](SSLClient &cli) {
  16101. cli.enable_server_certificate_verification(false);
  16102. // Pin the first certificate seen.
  16103. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16104. if (pinned.empty()) { pinned = ctx.serial(); }
  16105. return ctx.serial() == pinned;
  16106. });
  16107. },
  16108. // A certificate other than the first server's.
  16109. SERVER_CERT_FILE);
  16110. EXPECT_FALSE(res);
  16111. EXPECT_FALSE(pinned.empty());
  16112. }
  16113. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16114. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16115. std::string cert;
  16116. read_file(SERVER_CERT2_FILE, cert);
  16117. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16118. });
  16119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16120. EXPECT_EQ(StatusCode::OK_200, res->status);
  16121. }
  16122. // The target's certificate is signed by the root CA, which the first server's
  16123. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16124. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16125. auto res = GetThroughTlsRedirectToDifferentPort(
  16126. [](SSLClient &cli) {
  16127. std::string root_ca, cert;
  16128. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16129. read_file(SERVER_CERT2_FILE, cert);
  16130. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16131. cli.load_ca_cert_store(cert.data(), cert.size());
  16132. cli.enable_server_hostname_verification(false);
  16133. },
  16134. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16136. EXPECT_EQ(StatusCode::OK_200, res->status);
  16137. }
  16138. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16139. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16140. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16141. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16142. auto res = GetThroughTlsRedirectToDifferentPort(
  16143. [](SSLClient &cli) {
  16144. std::string root_ca, cert;
  16145. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16146. read_file(SERVER_CERT2_FILE, cert);
  16147. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16148. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16149. cli.enable_server_hostname_verification(false);
  16150. },
  16151. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16152. ASSERT_FALSE(res);
  16153. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16154. }
  16155. #endif
  16156. #endif
  16157. #ifdef CPPHTTPLIB_SSL_ENABLED
  16158. // Test that set_ca_cert_store() skips system certs (consistent with
  16159. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16160. // should be trusted - system certs should NOT be loaded.
  16161. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16162. // Load a specific cert that is NOT a system CA cert
  16163. std::string cert;
  16164. read_file(SERVER_CERT2_FILE, cert);
  16165. SSLClient cli("google.com");
  16166. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16167. cli.enable_server_certificate_verification(true);
  16168. // This should FAIL because:
  16169. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16170. // 2. System certs should NOT be loaded when custom store is set
  16171. // If system certs WERE loaded, this would succeed
  16172. auto res = cli.Get("/");
  16173. ASSERT_FALSE(res);
  16174. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16175. }
  16176. // Same as above, but through the native store handle path. Regression test:
  16177. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16178. // merged system certs into the user-provided store.
  16179. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16180. std::string cert;
  16181. read_file(SERVER_CERT2_FILE, cert);
  16182. SSLClient cli("google.com");
  16183. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16184. cli.enable_server_certificate_verification(true);
  16185. auto res = cli.Get("/");
  16186. ASSERT_FALSE(res);
  16187. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16188. }
  16189. // A custom store set via the native handle must still verify a server whose
  16190. // cert it does contain.
  16191. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16192. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16193. ASSERT_TRUE(svr.is_valid());
  16194. svr.Get("/test", [&](const Request &, Response &res) {
  16195. res.set_content("test", "text/plain");
  16196. });
  16197. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16198. auto se = detail::scope_exit([&] {
  16199. svr.stop();
  16200. t.join();
  16201. ASSERT_FALSE(svr.is_running());
  16202. });
  16203. svr.wait_until_ready();
  16204. SSLClient cli("127.0.0.1", PORT);
  16205. std::string cert;
  16206. read_file(SERVER_CERT2_FILE, cert);
  16207. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16208. cli.enable_server_certificate_verification(true);
  16209. cli.set_connection_timeout(30);
  16210. auto res = cli.Get("/test");
  16211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16212. ASSERT_EQ(StatusCode::OK_200, res->status);
  16213. }
  16214. // CA certs loaded through the universal Client must be transferred to the
  16215. // client created internally for following an HTTPS redirect. Regression test:
  16216. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16217. // the CA data for redirect transfer.
  16218. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16219. auto ssl_port = PORT + 1;
  16220. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16221. ASSERT_TRUE(ssl_svr1.is_valid());
  16222. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16223. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16224. "/index");
  16225. });
  16226. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16227. ASSERT_TRUE(ssl_svr2.is_valid());
  16228. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16229. res.set_content("test", "text/plain");
  16230. });
  16231. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16232. thread t2 =
  16233. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16234. auto se = detail::scope_exit([&] {
  16235. ssl_svr2.stop();
  16236. ssl_svr1.stop();
  16237. t2.join();
  16238. t.join();
  16239. ASSERT_FALSE(ssl_svr1.is_running());
  16240. });
  16241. ssl_svr1.wait_until_ready();
  16242. ssl_svr2.wait_until_ready();
  16243. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16244. std::string cert;
  16245. read_file(SERVER_CERT2_FILE, cert);
  16246. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16247. cli.enable_server_certificate_verification(true);
  16248. cli.set_follow_location(true);
  16249. cli.set_connection_timeout(30);
  16250. auto res = cli.Get("/index");
  16251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16252. ASSERT_EQ(StatusCode::OK_200, res->status);
  16253. }
  16254. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16255. // so a host signed by a system CA verifies even though a custom CA is set
  16256. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16257. std::string cert;
  16258. read_file(SERVER_CERT2_FILE, cert);
  16259. SSLClient cli("google.com");
  16260. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16261. cli.enable_system_ca(true);
  16262. cli.enable_server_certificate_verification(true);
  16263. auto res = cli.Get("/");
  16264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16265. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16266. }
  16267. // The custom CA remains effective when combined with the system CA
  16268. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16269. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16270. ASSERT_TRUE(svr.is_valid());
  16271. svr.Get("/test", [&](const Request &, Response &res) {
  16272. res.set_content("test", "text/plain");
  16273. });
  16274. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16275. auto se = detail::scope_exit([&] {
  16276. svr.stop();
  16277. t.join();
  16278. ASSERT_FALSE(svr.is_running());
  16279. });
  16280. svr.wait_until_ready();
  16281. SSLClient cli("127.0.0.1", PORT);
  16282. std::string cert;
  16283. read_file(SERVER_CERT2_FILE, cert);
  16284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16285. cli.enable_system_ca(true);
  16286. cli.enable_server_certificate_verification(true);
  16287. cli.set_connection_timeout(30);
  16288. auto res = cli.Get("/test");
  16289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16290. ASSERT_EQ(StatusCode::OK_200, res->status);
  16291. }
  16292. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16293. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16294. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16295. static CFDictionaryRef
  16296. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16297. const SecTrustSettingsResult *result) {
  16298. auto constraint =
  16299. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16300. &kCFTypeDictionaryValueCallBacks);
  16301. if (policy) {
  16302. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16303. }
  16304. if (policy_string) {
  16305. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16306. kCFStringEncodingUTF8);
  16307. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16308. CFRelease(str);
  16309. }
  16310. if (result) {
  16311. auto number_value = static_cast<SInt32>(*result);
  16312. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16313. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16314. CFRelease(number);
  16315. }
  16316. return constraint;
  16317. }
  16318. static SecTrustSettingsResult
  16319. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16320. auto trust_settings =
  16321. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16322. for (auto constraint : constraints) {
  16323. CFArrayAppendValue(trust_settings, constraint);
  16324. CFRelease(constraint);
  16325. }
  16326. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16327. CFRelease(trust_settings);
  16328. return result;
  16329. }
  16330. // The system CA loader takes a Keychain certificate as a trusted root only
  16331. // when its Trust Settings say so for SSL, not merely because it has some.
  16332. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16333. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16334. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16335. const auto deny = kSecTrustSettingsResultDeny;
  16336. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16337. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16338. auto x509_policy = SecPolicyCreateBasicX509();
  16339. // "Always Trust", which stores no constraint at all
  16340. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16341. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16342. ssl_trust_settings_result(
  16343. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16344. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16345. ssl_trust_settings_result(
  16346. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16347. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16348. ssl_trust_settings_result(
  16349. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16350. // "Never Trust", for everything or for SSL
  16351. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16352. ssl_trust_settings_result(
  16353. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16354. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16355. ssl_trust_settings_result(
  16356. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16357. // Trusted for another policy, for one host, or not at all
  16358. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16359. ssl_trust_settings_result(
  16360. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16361. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16362. ssl_trust_settings_result({make_usage_constraint(
  16363. ssl_policy, "www.example.com", &trust_root)}));
  16364. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16365. ssl_trust_settings_result(
  16366. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16367. // The first constraint that applies to SSL decides
  16368. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16369. ssl_trust_settings_result(
  16370. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16371. make_usage_constraint(nullptr, nullptr, &deny)}));
  16372. CFRelease(x509_policy);
  16373. CFRelease(ssl_policy);
  16374. }
  16375. #endif
  16376. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16377. // skip chain verification entirely (only the certificate identity was
  16378. // checked), so a server presenting an untrusted certificate with a matching
  16379. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16380. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16382. ASSERT_TRUE(svr.is_valid());
  16383. svr.Get("/test", [&](const Request &, Response &res) {
  16384. res.set_content("test", "text/plain");
  16385. });
  16386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16387. auto se = detail::scope_exit([&] {
  16388. svr.stop();
  16389. t.join();
  16390. ASSERT_FALSE(svr.is_running());
  16391. });
  16392. svr.wait_until_ready();
  16393. SSLClient cli("127.0.0.1", PORT);
  16394. std::string cert;
  16395. // A trusted CA that did not sign the server certificate. The server cert
  16396. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16397. // this connection.
  16398. read_file(CLIENT_CA_CERT_FILE, cert);
  16399. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16400. cli.enable_server_certificate_verification(true);
  16401. cli.set_connection_timeout(30);
  16402. auto res = cli.Get("/test");
  16403. ASSERT_FALSE(res);
  16404. }
  16405. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16406. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16407. // CA that failed to come through fails verification instead of trusting them.
  16408. // (wolfSSL does not list the system CAs it loaded.)
  16409. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16410. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16411. ASSERT_TRUE(svr.is_valid());
  16412. auto port = svr.bind_to_any_port("127.0.0.1");
  16413. ASSERT_LT(0, port);
  16414. thread t = thread([&] { svr.listen_after_bind(); });
  16415. auto se = detail::scope_exit([&] {
  16416. svr.stop();
  16417. t.join();
  16418. ASSERT_FALSE(svr.is_running());
  16419. });
  16420. svr.wait_until_ready();
  16421. // The CAs a client trusts once its first request has loaded them
  16422. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16423. Client cli("https://127.0.0.1:" + std::to_string(port));
  16424. setup(cli);
  16425. cli.Get("/");
  16426. return tls::get_ca_names(cli.tls_context()).size();
  16427. };
  16428. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16429. EXPECT_EQ(0u,
  16430. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16431. }
  16432. #endif
  16433. // A TLS setting changed between requests applies to the next one, not just to
  16434. // the next connection
  16435. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16436. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16437. ASSERT_TRUE(svr.is_valid());
  16438. svr.Get("/", [](const Request &req, Response &res) {
  16439. res.set_content(std::to_string(req.remote_port), "text/plain");
  16440. });
  16441. auto port = svr.bind_to_any_port("127.0.0.1");
  16442. ASSERT_LT(0, port);
  16443. thread t = thread([&] { svr.listen_after_bind(); });
  16444. auto se = detail::scope_exit([&] {
  16445. svr.stop();
  16446. t.join();
  16447. ASSERT_FALSE(svr.is_running());
  16448. });
  16449. svr.wait_until_ready();
  16450. SSLClient cli("127.0.0.1", port);
  16451. cli.set_keep_alive(true);
  16452. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16453. cli.enable_server_certificate_verification(false);
  16454. // The port the request went out from, so a new one means a new connection
  16455. auto client_port = [&] {
  16456. auto res = cli.Get("/");
  16457. return res ? res->body : std::string();
  16458. };
  16459. auto last = client_port();
  16460. ASSERT_FALSE(last.empty());
  16461. // Setting a value it already has keeps the connection
  16462. cli.enable_server_certificate_verification(false);
  16463. cli.enable_server_hostname_verification(true);
  16464. EXPECT_EQ(last, client_port());
  16465. cli.enable_server_certificate_verification(true);
  16466. auto res = cli.Get("/");
  16467. EXPECT_FALSE(res);
  16468. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16469. std::string ca;
  16470. read_file(SERVER_CERT2_FILE, ca);
  16471. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16472. last = client_port();
  16473. ASSERT_FALSE(last.empty());
  16474. std::vector<std::function<void()>> setters = {
  16475. [&] { cli.enable_server_hostname_verification(false); },
  16476. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16477. [&] {
  16478. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16479. },
  16480. [&] {
  16481. cli.set_server_certificate_verifier(
  16482. [](const tls::VerifyContext &) { return true; });
  16483. },
  16484. [&] {
  16485. cli.set_session_verifier(
  16486. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16487. },
  16488. };
  16489. for (const auto &setter : setters) {
  16490. setter();
  16491. auto next = client_port();
  16492. ASSERT_FALSE(next.empty());
  16493. EXPECT_NE(last, next);
  16494. last = next;
  16495. }
  16496. cli.set_session_verifier(
  16497. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16498. auto handle = cli.open_stream("GET", "/");
  16499. EXPECT_FALSE(handle.is_valid());
  16500. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16501. }
  16502. // A PEM given to create_ca_store() needs no NUL after it
  16503. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16504. std::string pem;
  16505. read_file(SERVER_CERT2_FILE, pem);
  16506. auto buf = pem + "X";
  16507. auto store = tls::create_ca_store(buf.data(), pem.size());
  16508. EXPECT_TRUE(store != nullptr);
  16509. SSLClient cli("localhost");
  16510. cli.set_ca_cert_store(store);
  16511. }
  16512. // enable_system_ca(false) prevents system CA loading entirely
  16513. TEST(SSLClientTest, DisableSystemCa_Online) {
  16514. SSLClient cli("google.com");
  16515. cli.enable_system_ca(false);
  16516. cli.enable_server_certificate_verification(true);
  16517. auto res = cli.Get("/");
  16518. ASSERT_FALSE(res);
  16519. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16520. // itself when the CA chain is empty
  16521. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16522. res.error() == Error::SSLConnection);
  16523. }
  16524. // The universal Client forwards enable_system_ca()
  16525. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16526. std::string cert;
  16527. read_file(SERVER_CERT2_FILE, cert);
  16528. Client cli("https://google.com");
  16529. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16530. cli.enable_system_ca(true);
  16531. cli.enable_server_certificate_verification(true);
  16532. auto res = cli.Get("/");
  16533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16534. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16535. }
  16536. // The system CA policy must carry over to the client created internally for
  16537. // following a cross-host HTTPS redirect
  16538. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16539. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16540. ASSERT_TRUE(svr.is_valid());
  16541. svr.Get("/index", [&](const Request &, Response &res) {
  16542. res.set_redirect("https://www.google.com/");
  16543. });
  16544. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16545. auto se = detail::scope_exit([&] {
  16546. svr.stop();
  16547. t.join();
  16548. ASSERT_FALSE(svr.is_running());
  16549. });
  16550. svr.wait_until_ready();
  16551. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16552. std::string cert;
  16553. read_file(SERVER_CERT2_FILE, cert);
  16554. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16555. cli.enable_system_ca(true);
  16556. cli.enable_server_certificate_verification(true);
  16557. cli.set_follow_location(true);
  16558. cli.set_connection_timeout(30);
  16559. // Receiving any response proves the redirect client completed the TLS
  16560. // handshake with a system-CA-signed host
  16561. auto res = cli.Get("/index");
  16562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16563. }
  16564. TEST(MultipartFormDataTest, LargeData) {
  16565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16566. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16567. const ContentReader &content_reader) {
  16568. if (req.is_multipart_form_data()) {
  16569. std::vector<FormData> items;
  16570. content_reader(
  16571. [&](const FormData &file) {
  16572. items.push_back(file);
  16573. return true;
  16574. },
  16575. [&](const char *data, size_t data_length) {
  16576. items.back().content.append(data, data_length);
  16577. return true;
  16578. });
  16579. EXPECT_TRUE(std::string(items[0].name) == "document");
  16580. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16581. EXPECT_TRUE(items[0].filename == "2MB_data");
  16582. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16583. EXPECT_TRUE(items[1].name == "hello");
  16584. EXPECT_TRUE(items[1].content == "world");
  16585. EXPECT_TRUE(items[1].filename == "");
  16586. EXPECT_TRUE(items[1].content_type == "");
  16587. } else {
  16588. std::string body;
  16589. content_reader([&](const char *data, size_t data_length) {
  16590. body.append(data, data_length);
  16591. return true;
  16592. });
  16593. }
  16594. });
  16595. auto port = svr.bind_to_any_port(HOST);
  16596. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16597. auto se = detail::scope_exit([&] {
  16598. svr.stop();
  16599. t.join();
  16600. ASSERT_FALSE(svr.is_running());
  16601. });
  16602. svr.wait_until_ready();
  16603. {
  16604. std::string data(1024 * 1024 * 2, '.');
  16605. std::stringstream buffer;
  16606. buffer << data;
  16607. SSLClient cli(HOST, port);
  16608. cli.enable_server_certificate_verification(false);
  16609. UploadFormDataItems items{
  16610. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16611. {"hello", "world", "", ""},
  16612. };
  16613. auto res = cli.Post("/post", items);
  16614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16615. ASSERT_EQ(StatusCode::OK_200, res->status);
  16616. }
  16617. }
  16618. TEST(MultipartFormDataTest, DataProviderItems) {
  16619. std::random_device seed_gen;
  16620. std::mt19937 random(seed_gen());
  16621. std::string rand1;
  16622. rand1.resize(1000);
  16623. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16624. std::string rand2;
  16625. rand2.resize(3000);
  16626. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16628. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16629. const ContentReader &content_reader) {
  16630. ASSERT_FALSE(req.is_multipart_form_data());
  16631. std::string body;
  16632. content_reader([&](const char *data, size_t data_length) {
  16633. body.append(data, data_length);
  16634. return true;
  16635. });
  16636. EXPECT_EQ(body, "");
  16637. });
  16638. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16639. const ContentReader &content_reader) {
  16640. ASSERT_TRUE(req.is_multipart_form_data());
  16641. std::vector<FormData> items;
  16642. content_reader(
  16643. [&](const FormData &file) {
  16644. items.push_back(file);
  16645. return true;
  16646. },
  16647. [&](const char *data, size_t data_length) {
  16648. items.back().content.append(data, data_length);
  16649. return true;
  16650. });
  16651. ASSERT_TRUE(items.size() == 2);
  16652. EXPECT_EQ(std::string(items[0].name), "name1");
  16653. EXPECT_EQ(items[0].content, "Testing123");
  16654. EXPECT_EQ(items[0].filename, "filename1");
  16655. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16656. EXPECT_EQ(items[1].name, "name2");
  16657. EXPECT_EQ(items[1].content, "Testing456");
  16658. EXPECT_EQ(items[1].filename, "");
  16659. EXPECT_EQ(items[1].content_type, "");
  16660. });
  16661. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16662. const ContentReader &content_reader) {
  16663. ASSERT_TRUE(req.is_multipart_form_data());
  16664. std::vector<FormData> items;
  16665. content_reader(
  16666. [&](const FormData &file) {
  16667. items.push_back(file);
  16668. return true;
  16669. },
  16670. [&](const char *data, size_t data_length) {
  16671. items.back().content.append(data, data_length);
  16672. return true;
  16673. });
  16674. ASSERT_TRUE(items.size() == 2);
  16675. EXPECT_EQ(items[0].name, "name3");
  16676. EXPECT_EQ(items[0].content, rand1);
  16677. EXPECT_EQ(items[0].filename, "filename3");
  16678. EXPECT_EQ(items[0].content_type, "");
  16679. EXPECT_EQ(items[1].name, "name4");
  16680. EXPECT_EQ(items[1].content, rand2);
  16681. EXPECT_EQ(items[1].filename, "filename4");
  16682. EXPECT_EQ(items[1].content_type, "");
  16683. });
  16684. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16685. const ContentReader &content_reader) {
  16686. ASSERT_TRUE(req.is_multipart_form_data());
  16687. std::vector<FormData> items;
  16688. content_reader(
  16689. [&](const FormData &file) {
  16690. items.push_back(file);
  16691. return true;
  16692. },
  16693. [&](const char *data, size_t data_length) {
  16694. items.back().content.append(data, data_length);
  16695. return true;
  16696. });
  16697. ASSERT_TRUE(items.size() == 4);
  16698. EXPECT_EQ(std::string(items[0].name), "name1");
  16699. EXPECT_EQ(items[0].content, "Testing123");
  16700. EXPECT_EQ(items[0].filename, "filename1");
  16701. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16702. EXPECT_EQ(items[1].name, "name2");
  16703. EXPECT_EQ(items[1].content, "Testing456");
  16704. EXPECT_EQ(items[1].filename, "");
  16705. EXPECT_EQ(items[1].content_type, "");
  16706. EXPECT_EQ(items[2].name, "name3");
  16707. EXPECT_EQ(items[2].content, rand1);
  16708. EXPECT_EQ(items[2].filename, "filename3");
  16709. EXPECT_EQ(items[2].content_type, "");
  16710. EXPECT_EQ(items[3].name, "name4");
  16711. EXPECT_EQ(items[3].content, rand2);
  16712. EXPECT_EQ(items[3].filename, "filename4");
  16713. EXPECT_EQ(items[3].content_type, "");
  16714. });
  16715. auto port = svr.bind_to_any_port("localhost");
  16716. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. t.join();
  16720. ASSERT_FALSE(svr.is_running());
  16721. });
  16722. svr.wait_until_ready();
  16723. {
  16724. SSLClient cli("localhost", port);
  16725. cli.enable_server_certificate_verification(false);
  16726. UploadFormDataItems items{
  16727. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16728. {"name2", "Testing456", "", ""}, // not a file
  16729. };
  16730. {
  16731. auto res = cli.Post("/post-none", {}, {}, {});
  16732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16733. ASSERT_EQ(StatusCode::OK_200, res->status);
  16734. }
  16735. FormDataProviderItems providers;
  16736. {
  16737. auto res =
  16738. cli.Post("/post-items", {}, items, providers); // empty providers
  16739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16740. ASSERT_EQ(StatusCode::OK_200, res->status);
  16741. }
  16742. providers.push_back({"name3",
  16743. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16744. // test the offset is given correctly at each step
  16745. if (!offset)
  16746. sink.os.write(rand1.data(), 30);
  16747. else if (offset == 30)
  16748. sink.os.write(rand1.data() + 30, 300);
  16749. else if (offset == 330)
  16750. sink.os.write(rand1.data() + 330, 670);
  16751. else if (offset == rand1.size())
  16752. sink.done();
  16753. return true;
  16754. },
  16755. "filename3",
  16756. {}});
  16757. providers.push_back({"name4",
  16758. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16759. // test the offset is given correctly at each step
  16760. if (!offset)
  16761. sink.os.write(rand2.data(), 2000);
  16762. else if (offset == 2000)
  16763. sink.os.write(rand2.data() + 2000, 1);
  16764. else if (offset == 2001)
  16765. sink.os.write(rand2.data() + 2001, 999);
  16766. else if (offset == rand2.size())
  16767. sink.done();
  16768. return true;
  16769. },
  16770. "filename4",
  16771. {}});
  16772. {
  16773. auto res = cli.Post("/post-providers", {}, {}, providers);
  16774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16775. ASSERT_EQ(StatusCode::OK_200, res->status);
  16776. }
  16777. {
  16778. auto res = cli.Post("/post-both", {}, items, providers);
  16779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16780. ASSERT_EQ(StatusCode::OK_200, res->status);
  16781. }
  16782. }
  16783. }
  16784. TEST(MultipartFormDataTest, BadHeader) {
  16785. Server svr;
  16786. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16787. res.set_content("ok", "text/plain");
  16788. });
  16789. thread t = thread([&] { svr.listen(HOST, PORT); });
  16790. auto se = detail::scope_exit([&] {
  16791. svr.stop();
  16792. t.join();
  16793. ASSERT_FALSE(svr.is_running());
  16794. });
  16795. svr.wait_until_ready();
  16796. const std::string body =
  16797. "This is the preamble. It is to be ignored, though it\r\n"
  16798. "is a handy place for composition agents to include an\r\n"
  16799. "explanatory note to non-MIME conformant readers.\r\n"
  16800. "\r\n"
  16801. "\r\n"
  16802. "--simple boundary\r\n"
  16803. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16804. ": BAD...\r\n"
  16805. "\r\n"
  16806. "value1\r\n"
  16807. "--simple boundary\r\n"
  16808. "Content-Disposition: form-data; name=\"field2\"; "
  16809. "filename=\"example.txt\"\r\n"
  16810. "\r\n"
  16811. "value2\r\n"
  16812. "--simple boundary--\r\n"
  16813. "This is the epilogue. It is also to be ignored.\r\n";
  16814. std::string content_type =
  16815. R"(multipart/form-data; boundary="simple boundary")";
  16816. Client cli(HOST, PORT);
  16817. auto res = cli.Post("/post", body, content_type.c_str());
  16818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16819. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16820. }
  16821. TEST(MultipartFormDataTest, WithPreamble) {
  16822. Server svr;
  16823. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16824. res.set_content("ok", "text/plain");
  16825. });
  16826. thread t = thread([&] { svr.listen(HOST, PORT); });
  16827. auto se = detail::scope_exit([&] {
  16828. svr.stop();
  16829. t.join();
  16830. ASSERT_FALSE(svr.is_running());
  16831. });
  16832. svr.wait_until_ready();
  16833. const std::string body =
  16834. "This is the preamble. It is to be ignored, though it\r\n"
  16835. "is a handy place for composition agents to include an\r\n"
  16836. "explanatory note to non-MIME conformant readers.\r\n"
  16837. "\r\n"
  16838. "\r\n"
  16839. "--simple boundary\r\n"
  16840. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16841. "\r\n"
  16842. "value1\r\n"
  16843. "--simple boundary\r\n"
  16844. "Content-Disposition: form-data; name=\"field2\"; "
  16845. "filename=\"example.txt\"\r\n"
  16846. "\r\n"
  16847. "value2\r\n"
  16848. "--simple boundary--\r\n"
  16849. "This is the epilogue. It is also to be ignored.\r\n";
  16850. std::string content_type =
  16851. R"(multipart/form-data; boundary="simple boundary")";
  16852. Client cli(HOST, PORT);
  16853. auto res = cli.Post("/post", body, content_type.c_str());
  16854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16855. EXPECT_EQ(StatusCode::OK_200, res->status);
  16856. }
  16857. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16859. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16860. const ContentReader &content_reader) {
  16861. if (req.is_multipart_form_data()) {
  16862. std::vector<FormData> items;
  16863. content_reader(
  16864. [&](const FormData &file) {
  16865. items.push_back(file);
  16866. return true;
  16867. },
  16868. [&](const char *data, size_t data_length) {
  16869. items.back().content.append(data, data_length);
  16870. return true;
  16871. });
  16872. EXPECT_TRUE(std::string(items[0].name) == "document");
  16873. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16874. EXPECT_TRUE(items[0].filename == "2MB_data");
  16875. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16876. EXPECT_TRUE(items[1].name == "hello");
  16877. EXPECT_TRUE(items[1].content == "world");
  16878. EXPECT_TRUE(items[1].filename == "");
  16879. EXPECT_TRUE(items[1].content_type == "");
  16880. } else {
  16881. std::string body;
  16882. content_reader([&](const char *data, size_t data_length) {
  16883. body.append(data, data_length);
  16884. return true;
  16885. });
  16886. }
  16887. });
  16888. auto port = svr.bind_to_any_port("localhost");
  16889. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16890. auto se = detail::scope_exit([&] {
  16891. svr.stop();
  16892. t.join();
  16893. ASSERT_FALSE(svr.is_running());
  16894. });
  16895. svr.wait_until_ready();
  16896. {
  16897. std::string data(1024 * 1024 * 2, '.');
  16898. std::stringstream buffer;
  16899. buffer << data;
  16900. SSLClient cli("localhost", port);
  16901. cli.enable_server_certificate_verification(false);
  16902. UploadFormDataItems items{
  16903. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16904. {"hello", "world", "", ""},
  16905. };
  16906. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16908. ASSERT_EQ(StatusCode::OK_200, res->status);
  16909. }
  16910. }
  16911. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16912. std::string data(1024 * 1024 * 2, '&');
  16913. std::stringstream buffer;
  16914. buffer << data;
  16915. Client cli("https://localhost:8080");
  16916. UploadFormDataItems items{
  16917. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16918. {"hello", "world", "", ""},
  16919. };
  16920. for (const char &c : " \t\r\n") {
  16921. auto res =
  16922. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16923. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16924. ASSERT_FALSE(res);
  16925. }
  16926. }
  16927. TEST(MultipartFormDataTest, PutFormData) {
  16928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16929. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16930. const ContentReader &content_reader) {
  16931. if (req.is_multipart_form_data()) {
  16932. std::vector<FormData> items;
  16933. content_reader(
  16934. [&](const FormData &file) {
  16935. items.push_back(file);
  16936. return true;
  16937. },
  16938. [&](const char *data, size_t data_length) {
  16939. items.back().content.append(data, data_length);
  16940. return true;
  16941. });
  16942. EXPECT_TRUE(std::string(items[0].name) == "document");
  16943. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16944. EXPECT_TRUE(items[0].filename == "2MB_data");
  16945. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16946. EXPECT_TRUE(items[1].name == "hello");
  16947. EXPECT_TRUE(items[1].content == "world");
  16948. EXPECT_TRUE(items[1].filename == "");
  16949. EXPECT_TRUE(items[1].content_type == "");
  16950. } else {
  16951. std::string body;
  16952. content_reader([&](const char *data, size_t data_length) {
  16953. body.append(data, data_length);
  16954. return true;
  16955. });
  16956. }
  16957. });
  16958. auto port = svr.bind_to_any_port("localhost");
  16959. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16960. auto se = detail::scope_exit([&] {
  16961. svr.stop();
  16962. t.join();
  16963. ASSERT_FALSE(svr.is_running());
  16964. });
  16965. svr.wait_until_ready();
  16966. {
  16967. std::string data(1024 * 1024 * 2, '&');
  16968. std::stringstream buffer;
  16969. buffer << data;
  16970. SSLClient cli("localhost", port);
  16971. cli.enable_server_certificate_verification(false);
  16972. UploadFormDataItems items{
  16973. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16974. {"hello", "world", "", ""},
  16975. };
  16976. auto res = cli.Put("/put", items);
  16977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16978. ASSERT_EQ(StatusCode::OK_200, res->status);
  16979. }
  16980. }
  16981. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16983. svr.Put("/put_customboundary",
  16984. [&](const Request &req, const Response & /*res*/,
  16985. const ContentReader &content_reader) {
  16986. if (req.is_multipart_form_data()) {
  16987. std::vector<FormData> items;
  16988. content_reader(
  16989. [&](const FormData &file) {
  16990. items.push_back(file);
  16991. return true;
  16992. },
  16993. [&](const char *data, size_t data_length) {
  16994. items.back().content.append(data, data_length);
  16995. return true;
  16996. });
  16997. EXPECT_TRUE(std::string(items[0].name) == "document");
  16998. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16999. EXPECT_TRUE(items[0].filename == "2MB_data");
  17000. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17001. EXPECT_TRUE(items[1].name == "hello");
  17002. EXPECT_TRUE(items[1].content == "world");
  17003. EXPECT_TRUE(items[1].filename == "");
  17004. EXPECT_TRUE(items[1].content_type == "");
  17005. } else {
  17006. std::string body;
  17007. content_reader([&](const char *data, size_t data_length) {
  17008. body.append(data, data_length);
  17009. return true;
  17010. });
  17011. }
  17012. });
  17013. auto port = svr.bind_to_any_port("localhost");
  17014. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17015. auto se = detail::scope_exit([&] {
  17016. svr.stop();
  17017. t.join();
  17018. ASSERT_FALSE(svr.is_running());
  17019. });
  17020. svr.wait_until_ready();
  17021. {
  17022. std::string data(1024 * 1024 * 2, '&');
  17023. std::stringstream buffer;
  17024. buffer << data;
  17025. SSLClient cli("localhost", port);
  17026. cli.enable_server_certificate_verification(false);
  17027. UploadFormDataItems items{
  17028. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17029. {"hello", "world", "", ""},
  17030. };
  17031. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17033. ASSERT_EQ(StatusCode::OK_200, res->status);
  17034. }
  17035. }
  17036. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17037. std::string data(1024 * 1024 * 2, '&');
  17038. std::stringstream buffer;
  17039. buffer << data;
  17040. Client cli("https://localhost:8080");
  17041. cli.enable_server_certificate_verification(false);
  17042. UploadFormDataItems items{
  17043. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17044. {"hello", "world", "", ""},
  17045. };
  17046. for (const char &c : " \t\r\n") {
  17047. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17048. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17049. ASSERT_FALSE(res);
  17050. }
  17051. }
  17052. TEST(MultipartFormDataTest, AlternateFilename) {
  17053. auto handled = false;
  17054. Server svr;
  17055. svr.Post("/test", [&](const Request &req, Response &res) {
  17056. ASSERT_EQ(2u, req.form.files.size());
  17057. ASSERT_EQ(1u, req.form.fields.size());
  17058. // Test files
  17059. const auto &file1 = req.form.get_file("file1");
  17060. ASSERT_EQ("file1", file1.name);
  17061. ASSERT_EQ("A.txt", file1.filename);
  17062. ASSERT_EQ("text/plain", file1.content_type);
  17063. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17064. const auto &file2 = req.form.get_file("file2");
  17065. ASSERT_EQ("file2", file2.name);
  17066. ASSERT_EQ("a.html", file2.filename);
  17067. ASSERT_EQ("text/html", file2.content_type);
  17068. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17069. file2.content);
  17070. // Test text field
  17071. const auto &text = req.form.get_field("text");
  17072. ASSERT_EQ("text default", text);
  17073. res.set_content("ok", "text/plain");
  17074. handled = true;
  17075. });
  17076. thread t = thread([&] { svr.listen(HOST, PORT); });
  17077. auto se = detail::scope_exit([&] {
  17078. svr.stop();
  17079. t.join();
  17080. ASSERT_FALSE(svr.is_running());
  17081. ASSERT_TRUE(handled);
  17082. });
  17083. svr.wait_until_ready();
  17084. auto req = "POST /test HTTP/1.1\r\n"
  17085. "Host: localhost\r\n"
  17086. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17087. "Content-Length: 399\r\n"
  17088. "\r\n"
  17089. "----------\r\n"
  17090. "Content-Disposition: form-data; name=\"text\"\r\n"
  17091. "\r\n"
  17092. "text default\r\n"
  17093. "----------\r\n"
  17094. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17095. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17096. "Content-Type: text/plain\r\n"
  17097. "\r\n"
  17098. "Content of a.txt.\r\n"
  17099. "\r\n"
  17100. "----------\r\n"
  17101. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17102. "\"a.html\"\r\n"
  17103. "Content-Type: text/html\r\n"
  17104. "\r\n"
  17105. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17106. "\r\n"
  17107. "------------\r\n";
  17108. ASSERT_TRUE(send_request(1, req));
  17109. }
  17110. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17111. auto handled = false;
  17112. Server svr;
  17113. svr.Post("/test", [&](const Request &req, Response &res) {
  17114. // Case-insensitive "utf-8''" prefix with a long value
  17115. const auto &file = req.form.get_file("file1");
  17116. ASSERT_EQ("file1", file.name);
  17117. // 8000 chars exercises both the Content-Disposition parser and the
  17118. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17119. // Prior to the fix, std::regex_match on this header would cause O(N)
  17120. // stack recursion in libstdc++, leading to SIGSEGV.
  17121. std::string expected_filename(8000, 'A');
  17122. ASSERT_EQ(expected_filename, file.filename);
  17123. res.set_content("ok", "text/plain");
  17124. handled = true;
  17125. });
  17126. thread t = thread([&] { svr.listen(HOST, PORT); });
  17127. auto se = detail::scope_exit([&] {
  17128. svr.stop();
  17129. t.join();
  17130. ASSERT_FALSE(svr.is_running());
  17131. ASSERT_TRUE(handled);
  17132. });
  17133. svr.wait_until_ready();
  17134. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17135. // Regression test for GHSA-qq6v-r583-3h69
  17136. std::string long_filename(8000, 'A');
  17137. std::string body = "----------\r\n"
  17138. "Content-Disposition: form-data; name=\"file1\"; "
  17139. "filename*=\"Utf-8''" +
  17140. long_filename +
  17141. "\"\r\n"
  17142. "\r\n"
  17143. "hello\r\n"
  17144. "------------\r\n";
  17145. auto req = "POST /test HTTP/1.1\r\n"
  17146. "Host: localhost\r\n"
  17147. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17148. "Content-Length: " +
  17149. std::to_string(body.size()) + "\r\n\r\n" + body;
  17150. ASSERT_TRUE(send_request(1, req));
  17151. }
  17152. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17153. auto handled = false;
  17154. Server svr;
  17155. svr.Post("/test", [&](const Request &req, Response &) {
  17156. ASSERT_EQ(2u, req.form.fields.size());
  17157. const auto &text1 = req.form.get_field("text1");
  17158. ASSERT_EQ("text1", text1);
  17159. const auto &text2 = req.form.get_field("text2");
  17160. ASSERT_EQ("text2", text2);
  17161. handled = true;
  17162. });
  17163. thread t = thread([&] { svr.listen(HOST, PORT); });
  17164. auto se = detail::scope_exit([&] {
  17165. svr.stop();
  17166. t.join();
  17167. ASSERT_FALSE(svr.is_running());
  17168. ASSERT_TRUE(handled);
  17169. });
  17170. svr.wait_until_ready();
  17171. auto req = "POST /test HTTP/1.1\r\n"
  17172. "Host: localhost\r\n"
  17173. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17174. "Content-Length: 146\r\n"
  17175. "\r\n----------\r\n"
  17176. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17177. "\r\n"
  17178. "text1"
  17179. "\r\n----------\r\n"
  17180. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17181. "\r\n"
  17182. "text2"
  17183. "\r\n------------";
  17184. std::string response;
  17185. ASSERT_TRUE(send_request(1, req, &response));
  17186. ASSERT_EQ("200", response.substr(9, 3));
  17187. }
  17188. TEST(MultipartFormDataTest, ContentLength) {
  17189. auto handled = false;
  17190. Server svr;
  17191. svr.Post("/test", [&](const Request &req, Response &) {
  17192. ASSERT_EQ(2u, req.form.fields.size());
  17193. const auto &text1 = req.form.get_field("text1");
  17194. ASSERT_EQ("text1", text1);
  17195. const auto &text2 = req.form.get_field("text2");
  17196. ASSERT_EQ("text2", text2);
  17197. handled = true;
  17198. });
  17199. thread t = thread([&] { svr.listen(HOST, PORT); });
  17200. auto se = detail::scope_exit([&] {
  17201. svr.stop();
  17202. t.join();
  17203. ASSERT_FALSE(svr.is_running());
  17204. ASSERT_TRUE(handled);
  17205. });
  17206. svr.wait_until_ready();
  17207. auto req = "POST /test HTTP/1.1\r\n"
  17208. "Host: localhost\r\n"
  17209. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17210. "Content-Length: 167\r\n"
  17211. "\r\n----------\r\n"
  17212. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17213. "Content-Length: 5\r\n"
  17214. "\r\n"
  17215. "text1"
  17216. "\r\n----------\r\n"
  17217. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17218. "\r\n"
  17219. "text2"
  17220. "\r\n------------\r\n";
  17221. std::string response;
  17222. ASSERT_TRUE(send_request(1, req, &response));
  17223. ASSERT_EQ("200", response.substr(9, 3));
  17224. }
  17225. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17226. auto handled = false;
  17227. Server svr;
  17228. svr.Post("/test", [&](const Request &req, Response &) {
  17229. ASSERT_EQ(2u, req.form.fields.size());
  17230. const auto &text1 = req.form.get_field("text1");
  17231. ASSERT_EQ("text1", text1);
  17232. // TODO: Add header access for text fields if needed
  17233. const auto &text2 = req.form.get_field("text2");
  17234. ASSERT_EQ("text2", text2);
  17235. // TODO: Header access for text fields needs to be implemented
  17236. // auto &headers = it->second.headers;
  17237. // ASSERT_EQ(3U, headers.size());
  17238. // auto custom_header = headers.find("x-whatever");
  17239. // ASSERT_TRUE(custom_header != headers.end());
  17240. // ASSERT_NE("customvalue", custom_header->second);
  17241. // ASSERT_EQ("CustomValue", custom_header->second);
  17242. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17243. handled = true;
  17244. });
  17245. thread t = thread([&] { svr.listen(HOST, PORT); });
  17246. auto se = detail::scope_exit([&] {
  17247. svr.stop();
  17248. t.join();
  17249. ASSERT_FALSE(svr.is_running());
  17250. ASSERT_TRUE(handled);
  17251. });
  17252. svr.wait_until_ready();
  17253. auto req = "POST /test HTTP/1.1\r\n"
  17254. "Host: localhost\r\n"
  17255. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17256. "Content-Length: 232\r\n"
  17257. "\r\n----------\r\n"
  17258. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17259. "Content-Length: 5\r\n"
  17260. "X-Test: 1\r\n"
  17261. "\r\n"
  17262. "text1"
  17263. "\r\n----------\r\n"
  17264. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17265. "Content-Type: text/plain\r\n"
  17266. "X-Whatever: CustomValue\r\n"
  17267. "\r\n"
  17268. "text2"
  17269. "\r\n------------\r\n"
  17270. "That should be disregarded. Not even read";
  17271. std::string response;
  17272. ASSERT_TRUE(send_request(1, req, &response));
  17273. ASSERT_EQ("200", response.substr(9, 3));
  17274. }
  17275. TEST(MultipartFormDataTest, LargeHeader) {
  17276. auto handled = false;
  17277. Server svr;
  17278. svr.Post("/test", [&](const Request &req, Response &) {
  17279. ASSERT_EQ(1u, req.form.fields.size());
  17280. const auto &text = req.form.get_field("name1");
  17281. ASSERT_EQ("text1", text);
  17282. handled = true;
  17283. });
  17284. thread t = thread([&] { svr.listen(HOST, PORT); });
  17285. auto se = detail::scope_exit([&] {
  17286. svr.stop();
  17287. t.join();
  17288. ASSERT_FALSE(svr.is_running());
  17289. ASSERT_TRUE(handled);
  17290. });
  17291. svr.wait_until_ready();
  17292. auto boundary = std::string("cpp-httplib-multipart-data");
  17293. std::string content = "--" + boundary +
  17294. "\r\n"
  17295. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17296. "\r\n"
  17297. "text1\r\n"
  17298. "--" +
  17299. boundary + "--\r\n";
  17300. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17301. "Host: localhost\r\n"
  17302. "Content-Type: multipart/form-data;boundary=" +
  17303. boundary +
  17304. "\r\n"
  17305. "Content-Length: " +
  17306. std::to_string(content.size()) +
  17307. "\r\n"
  17308. "Dummy-Header: ";
  17309. std::string header_suffix = "\r\n"
  17310. "\r\n";
  17311. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17312. size_t header_dummy_size =
  17313. read_buff_size -
  17314. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17315. auto header_dummy = std::string(header_dummy_size, '@');
  17316. auto req = header_prefix + header_dummy + header_suffix + content;
  17317. std::string response;
  17318. ASSERT_TRUE(send_request(1, req, &response));
  17319. ASSERT_EQ("200", response.substr(9, 3));
  17320. }
  17321. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17322. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17323. // (not chunked Transfer-Encoding) after the streaming refactor.
  17324. auto handled = false;
  17325. Server svr;
  17326. svr.Post("/upload", [&](const Request &req, Response &res) {
  17327. auto cl_it = req.headers.find("Content-Length");
  17328. EXPECT_TRUE(cl_it != req.headers.end());
  17329. auto te_it = req.headers.find("Transfer-Encoding");
  17330. EXPECT_TRUE(te_it == req.headers.end());
  17331. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17332. res.set_content("ok", "text/plain");
  17333. handled = true;
  17334. });
  17335. auto port = svr.bind_to_any_port(HOST);
  17336. auto t = thread([&] { svr.listen_after_bind(); });
  17337. auto se = detail::scope_exit([&] {
  17338. svr.stop();
  17339. t.join();
  17340. ASSERT_FALSE(svr.is_running());
  17341. ASSERT_TRUE(handled);
  17342. });
  17343. svr.wait_until_ready();
  17344. UploadFormDataItems items = {
  17345. {"field1", "hello", "", "text/plain"},
  17346. {"file1", "world", "test.txt", "application/octet-stream"},
  17347. };
  17348. Client cli(HOST, port);
  17349. auto res = cli.Post("/upload", {}, items);
  17350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17351. EXPECT_EQ(StatusCode::OK_200, res->status);
  17352. }
  17353. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17354. // Verify that make_multipart_content_provider coalesces many small segments
  17355. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17356. constexpr size_t kItemCount = 1000;
  17357. UploadFormDataItems items;
  17358. items.reserve(kItemCount);
  17359. for (size_t i = 0; i < kItemCount; i++) {
  17360. items.push_back(
  17361. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17362. }
  17363. const std::string boundary = "----test-boundary";
  17364. auto content_length = detail::get_multipart_content_length(items, boundary);
  17365. auto provider = detail::make_multipart_content_provider(items, boundary);
  17366. // Drive the provider the same way write_content_with_progress does
  17367. size_t write_count = 0;
  17368. size_t total_bytes = 0;
  17369. DataSink sink;
  17370. size_t offset = 0;
  17371. sink.write = [&](const char *d, size_t l) -> bool {
  17372. (void)d;
  17373. write_count++;
  17374. total_bytes += l;
  17375. offset += l;
  17376. return true;
  17377. };
  17378. sink.is_writable = []() -> bool { return true; };
  17379. while (offset < content_length) {
  17380. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17381. }
  17382. EXPECT_EQ(content_length, total_bytes);
  17383. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17384. // With buffering into 64KB blocks, write_count should be much smaller.
  17385. auto segment_count = 3 * kItemCount + 1;
  17386. EXPECT_LT(write_count, segment_count / 10);
  17387. }
  17388. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17389. // Integration test: send many UploadFormDataItems and verify the server
  17390. // receives all of them correctly (#2410).
  17391. constexpr size_t kItemCount = 500;
  17392. auto handled = false;
  17393. Server svr;
  17394. svr.Post("/upload", [&](const Request &req, Response &res) {
  17395. EXPECT_EQ(kItemCount, req.form.fields.size());
  17396. for (size_t i = 0; i < kItemCount; i++) {
  17397. auto key = "field" + std::to_string(i);
  17398. auto val = "value" + std::to_string(i);
  17399. auto it = req.form.fields.find(key);
  17400. if (it != req.form.fields.end()) {
  17401. EXPECT_EQ(val, it->second.content);
  17402. } else {
  17403. ADD_FAILURE() << "Missing field: " << key;
  17404. }
  17405. }
  17406. res.set_content("ok", "text/plain");
  17407. handled = true;
  17408. });
  17409. auto port = svr.bind_to_any_port(HOST);
  17410. auto t = thread([&] { svr.listen_after_bind(); });
  17411. auto se = detail::scope_exit([&] {
  17412. svr.stop();
  17413. t.join();
  17414. ASSERT_FALSE(svr.is_running());
  17415. ASSERT_TRUE(handled);
  17416. });
  17417. svr.wait_until_ready();
  17418. UploadFormDataItems items;
  17419. items.reserve(kItemCount);
  17420. for (size_t i = 0; i < kItemCount; i++) {
  17421. items.push_back(
  17422. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17423. }
  17424. Client cli(HOST, port);
  17425. auto res = cli.Post("/upload", items);
  17426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17427. EXPECT_EQ(StatusCode::OK_200, res->status);
  17428. }
  17429. TEST(MultipartFormDataTest, MakeFileProvider) {
  17430. // Verify make_file_provider sends a file's contents correctly.
  17431. const std::string file_content(4096, 'Z');
  17432. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17433. {
  17434. std::ofstream ofs(tmp_path, std::ios::binary);
  17435. ofs.write(file_content.data(),
  17436. static_cast<std::streamsize>(file_content.size()));
  17437. }
  17438. auto handled = false;
  17439. Server svr;
  17440. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17441. const ContentReader &content_reader) {
  17442. ASSERT_TRUE(req.is_multipart_form_data());
  17443. std::vector<FormData> items;
  17444. content_reader(
  17445. [&](const FormData &file) {
  17446. items.push_back(file);
  17447. return true;
  17448. },
  17449. [&](const char *data, size_t data_length) {
  17450. items.back().content.append(data, data_length);
  17451. return true;
  17452. });
  17453. ASSERT_EQ(1u, items.size());
  17454. EXPECT_EQ("myfile", items[0].name);
  17455. EXPECT_EQ("data.bin", items[0].filename);
  17456. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17457. EXPECT_EQ(file_content, items[0].content);
  17458. handled = true;
  17459. });
  17460. auto port = svr.bind_to_any_port(HOST);
  17461. auto t = thread([&] { svr.listen_after_bind(); });
  17462. auto se = detail::scope_exit([&] {
  17463. svr.stop();
  17464. t.join();
  17465. ASSERT_FALSE(svr.is_running());
  17466. ASSERT_TRUE(handled);
  17467. std::remove(tmp_path.c_str());
  17468. });
  17469. svr.wait_until_ready();
  17470. FormDataProviderItems providers;
  17471. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17472. "application/octet-stream"));
  17473. Client cli(HOST, port);
  17474. auto res = cli.Post("/upload", {}, {}, providers);
  17475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17476. EXPECT_EQ(StatusCode::OK_200, res->status);
  17477. }
  17478. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17479. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17480. // (100) headers is rejected with a 400 Bad Request response.
  17481. Server svr;
  17482. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17483. res.set_content("ok", "text/plain");
  17484. });
  17485. thread t = thread([&] { svr.listen(HOST, PORT); });
  17486. auto se = detail::scope_exit([&] {
  17487. svr.stop();
  17488. t.join();
  17489. ASSERT_FALSE(svr.is_running());
  17490. });
  17491. svr.wait_until_ready();
  17492. // Build a multipart part with 101 custom headers (exceeding
  17493. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17494. std::stringstream body;
  17495. body << "--simpleboundary\r\n"
  17496. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17497. for (int i = 0; i < 101; i++) {
  17498. body << "X-Custom-Header-" << i << ": value\r\n";
  17499. }
  17500. body << "\r\n"
  17501. << "value1\r\n"
  17502. << "--simpleboundary--\r\n";
  17503. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17504. Client cli(HOST, PORT);
  17505. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17507. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17508. }
  17509. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17510. // A body that never contains the declared boundary must not be accumulated
  17511. // while the parser waits for it. Buffering it would also make every read
  17512. // rescan everything seen so far, which is quadratic in the body size.
  17513. Server svr;
  17514. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17515. res.set_content("ok", "text/plain");
  17516. });
  17517. auto port = svr.bind_to_any_port(HOST);
  17518. thread t = thread([&] { svr.listen_after_bind(); });
  17519. auto se = detail::scope_exit([&] {
  17520. svr.stop();
  17521. t.join();
  17522. ASSERT_FALSE(svr.is_running());
  17523. });
  17524. svr.wait_until_ready();
  17525. Client cli(HOST, port);
  17526. cli.set_read_timeout(60, 0);
  17527. cli.set_write_timeout(60, 0);
  17528. // '-' is the worst case: it matches the first character of the boundary, so
  17529. // every position has to be checked against it.
  17530. auto post_dashes = [&](size_t size) {
  17531. const std::string body(size, '-');
  17532. auto start = std::chrono::steady_clock::now();
  17533. auto res =
  17534. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17535. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17536. std::chrono::steady_clock::now() - start)
  17537. .count();
  17538. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17539. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17540. return ms;
  17541. };
  17542. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17543. // Windows.
  17544. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17545. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17546. // Comparing the two sizes rather than checking an absolute duration keeps
  17547. // this meaningful across build types and CI load, both of which move the
  17548. // absolute numbers by more than an order of magnitude. Four times the bytes
  17549. // costs about four times the time when parsing is linear, and about sixteen
  17550. // times when the body is buffered and rescanned.
  17551. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17552. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17553. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17554. << "ms, which suggests the body is being buffered and rescanned";
  17555. }
  17556. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17557. // A boundary can only be followed by CRLF or by "--", so anything else is
  17558. // malformed no matter what comes next. The parser must say so right away
  17559. // instead of buffering the rest of the declared body.
  17560. Server svr;
  17561. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17562. res.set_content("ok", "text/plain");
  17563. });
  17564. auto port = svr.bind_to_any_port(HOST);
  17565. thread t = thread([&] { svr.listen_after_bind(); });
  17566. auto se = detail::scope_exit([&] {
  17567. svr.stop();
  17568. t.join();
  17569. ASSERT_FALSE(svr.is_running());
  17570. });
  17571. svr.wait_until_ready();
  17572. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17573. // buffers instead of failing would still be waiting for the remaining bytes.
  17574. const std::string body = "--zzzz\r\n"
  17575. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17576. "\r\n"
  17577. "text1"
  17578. "\r\n--zzzzXX";
  17579. const std::string req = "POST /post HTTP/1.1\r\n"
  17580. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17581. "Content-Length: 1048576\r\n"
  17582. "\r\n" +
  17583. body;
  17584. std::string response;
  17585. ASSERT_TRUE(send_request(3, req, &response, port));
  17586. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17587. EXPECT_EQ("400", response.substr(9, 3));
  17588. }
  17589. // Posts a multipart body split into two writes, so that the server sees the
  17590. // split at whatever offset the caller chose, and expects the single "text1"
  17591. // field to come through.
  17592. static void expect_split_multipart_ok(const std::string &body1,
  17593. const std::string &body2) {
  17594. auto handled = false;
  17595. Server svr;
  17596. svr.Post("/post", [&](const Request &req, Response &) {
  17597. EXPECT_EQ(1u, req.form.fields.size());
  17598. EXPECT_EQ("text1", req.form.get_field("text1"));
  17599. handled = true;
  17600. });
  17601. auto port = svr.bind_to_any_port(HOST);
  17602. thread t = thread([&] { svr.listen_after_bind(); });
  17603. auto se = detail::scope_exit([&] {
  17604. svr.stop();
  17605. t.join();
  17606. ASSERT_FALSE(svr.is_running());
  17607. ASSERT_TRUE(handled);
  17608. });
  17609. svr.wait_until_ready();
  17610. // "Connection: close" makes the server close once it has answered, so the
  17611. // response drain ends immediately instead of idling until the read timeout.
  17612. const std::string head =
  17613. "POST /post HTTP/1.1\r\n"
  17614. "Host: localhost\r\n"
  17615. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17616. "Connection: close\r\n"
  17617. "Content-Length: " +
  17618. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17619. std::string response;
  17620. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17621. ASSERT_GE(response.size(), 12u) << "no response";
  17622. EXPECT_EQ("200", response.substr(9, 3));
  17623. }
  17624. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17625. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17626. // ignored, including when it does not arrive in the same read as the
  17627. // close-delimiter itself.
  17628. expect_split_multipart_ok("--zzzz\r\n"
  17629. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17630. "\r\n"
  17631. "text1"
  17632. "\r\n--zzzz--",
  17633. "\r\nthis epilogue must be ignored\r\n");
  17634. }
  17635. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17636. // The initial boundary may be preceded by a preamble of any length and may
  17637. // straddle a read boundary. Discarding data while waiting for it must not
  17638. // throw away a partial boundary sitting at the end of the buffer.
  17639. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17640. "zz\r\n"
  17641. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17642. "\r\n"
  17643. "text1"
  17644. "\r\n--zzzz--\r\n");
  17645. }
  17646. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17647. // The received boundary was only checked for being non-empty, so it could be
  17648. // as long as a header is allowed to be. The parser scans the body for
  17649. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17650. // costs a nearly full comparison at nearly every position, making the
  17651. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17652. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17653. Server svr;
  17654. svr.Post("/post", [](const Request &req, Response &res) {
  17655. EXPECT_EQ(1u, req.form.fields.size());
  17656. EXPECT_EQ("text1", req.form.get_field("text1"));
  17657. res.set_content("ok", "text/plain");
  17658. });
  17659. auto port = svr.bind_to_any_port(HOST);
  17660. thread t = thread([&] { svr.listen_after_bind(); });
  17661. auto se = detail::scope_exit([&] {
  17662. svr.stop();
  17663. t.join();
  17664. ASSERT_FALSE(svr.is_running());
  17665. });
  17666. svr.wait_until_ready();
  17667. Client cli(HOST, port);
  17668. auto post_with_boundary_of_length = [&](size_t len) {
  17669. const std::string boundary(len, 'a');
  17670. const std::string body =
  17671. "--" + boundary +
  17672. "\r\n"
  17673. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17674. "\r\n"
  17675. "text1"
  17676. "\r\n--" +
  17677. boundary + "--\r\n";
  17678. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17679. };
  17680. auto res = post_with_boundary_of_length(70);
  17681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17682. EXPECT_EQ(StatusCode::OK_200, res->status);
  17683. res = post_with_boundary_of_length(71);
  17684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17685. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17686. }
  17687. TEST(MakeFileBodyTest, Basic) {
  17688. const std::string file_content(4096, 'Z');
  17689. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17690. {
  17691. std::ofstream ofs(tmp_path, std::ios::binary);
  17692. ofs.write(file_content.data(),
  17693. static_cast<std::streamsize>(file_content.size()));
  17694. }
  17695. auto handled = false;
  17696. Server svr;
  17697. svr.Post("/upload", [&](const Request &req, Response &res) {
  17698. EXPECT_EQ(file_content, req.body);
  17699. handled = true;
  17700. res.status = StatusCode::OK_200;
  17701. });
  17702. auto port = svr.bind_to_any_port(HOST);
  17703. auto t = thread([&] { svr.listen_after_bind(); });
  17704. auto se = detail::scope_exit([&] {
  17705. svr.stop();
  17706. t.join();
  17707. ASSERT_FALSE(svr.is_running());
  17708. ASSERT_TRUE(handled);
  17709. std::remove(tmp_path.c_str());
  17710. });
  17711. svr.wait_until_ready();
  17712. auto fb = make_file_body(tmp_path);
  17713. ASSERT_GT(fb.first, 0u);
  17714. Client cli(HOST, port);
  17715. auto res =
  17716. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17718. EXPECT_EQ(StatusCode::OK_200, res->status);
  17719. }
  17720. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17721. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17722. {
  17723. std::ofstream ofs(path, std::ios::binary);
  17724. const std::string content(100, 'A');
  17725. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17726. }
  17727. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17728. auto body = make_file_body(path);
  17729. ASSERT_EQ(100u, body.first);
  17730. ASSERT_TRUE(static_cast<bool>(body.second));
  17731. // Rewritten shorter after its length was measured - and, on a server, after
  17732. // that length has already gone out as Content-Length.
  17733. {
  17734. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17735. const std::string content(10, 'A');
  17736. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17737. }
  17738. std::string written;
  17739. DataSink sink;
  17740. sink.write = [&](const char *d, size_t l) {
  17741. written.append(d, l);
  17742. return true;
  17743. };
  17744. // The provider has to report failure. write_content_with_progress() advances
  17745. // its offset only by what was written, so a provider that returns true
  17746. // without completing the length it promised is called again straight away,
  17747. // and again.
  17748. EXPECT_FALSE(body.second(0, body.first, sink));
  17749. EXPECT_EQ(std::string(10, 'A'), written);
  17750. }
  17751. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17752. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17753. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17754. {
  17755. std::ofstream ofs(path, std::ios::binary);
  17756. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17757. }
  17758. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17759. auto body = make_file_body(path);
  17760. ASSERT_EQ(content.size(), body.first);
  17761. ASSERT_TRUE(static_cast<bool>(body.second));
  17762. std::string written;
  17763. DataSink sink;
  17764. sink.write = [&](const char *d, size_t l) {
  17765. written.append(d, l);
  17766. return true;
  17767. };
  17768. EXPECT_TRUE(body.second(0, body.first, sink));
  17769. EXPECT_EQ(content, written);
  17770. }
  17771. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17772. static constexpr unsigned int number_of_tasks{1000000};
  17773. std::atomic_uint count{0};
  17774. std::unique_ptr<TaskQueue> task_queue{
  17775. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17776. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17777. auto queued = task_queue->enqueue(
  17778. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17779. EXPECT_TRUE(queued);
  17780. }
  17781. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17782. task_queue->shutdown();
  17783. #else
  17784. EXPECT_NO_THROW(task_queue->shutdown());
  17785. #endif
  17786. EXPECT_EQ(number_of_tasks, count.load());
  17787. }
  17788. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17789. static constexpr unsigned int number_of_tasks{1000000};
  17790. static constexpr unsigned int qlimit{2};
  17791. unsigned int queued_count{0};
  17792. std::atomic_uint count{0};
  17793. std::unique_ptr<TaskQueue> task_queue{
  17794. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17795. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17796. if (task_queue->enqueue(
  17797. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17798. queued_count++;
  17799. }
  17800. }
  17801. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17802. task_queue->shutdown();
  17803. #else
  17804. EXPECT_NO_THROW(task_queue->shutdown());
  17805. #endif
  17806. EXPECT_EQ(queued_count, count.load());
  17807. EXPECT_TRUE(queued_count <= number_of_tasks);
  17808. EXPECT_TRUE(queued_count >= qlimit);
  17809. }
  17810. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17811. // Use a short idle timeout so a dynamic thread spawns, times out and
  17812. // exits during the test, and the pool keeps working afterwards.
  17813. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17814. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17815. /*idle_timeout_sec=*/1}};
  17816. std::atomic_uint count{0};
  17817. std::condition_variable cv;
  17818. std::mutex mtx;
  17819. bool release = false;
  17820. // Block the base thread so the second task spawns a dynamic thread.
  17821. EXPECT_TRUE(task_queue->enqueue([&] {
  17822. std::unique_lock<std::mutex> lock(mtx);
  17823. while (!release) {
  17824. cv.wait(lock);
  17825. }
  17826. count++;
  17827. }));
  17828. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17829. // Let the dynamic thread finish its task and exceed the idle timeout.
  17830. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17831. {
  17832. std::unique_lock<std::mutex> lock(mtx);
  17833. release = true;
  17834. }
  17835. cv.notify_all();
  17836. // The pool must still accept and run tasks after the dynamic thread exited.
  17837. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17838. task_queue->shutdown();
  17839. EXPECT_EQ(3u, count.load());
  17840. }
  17841. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17842. static constexpr size_t number_of_tasks{32};
  17843. std::unique_ptr<TaskQueue> task_queue{
  17844. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17845. // Let the base threads go idle so the burst below finds them waiting.
  17846. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17847. std::mutex mtx;
  17848. std::condition_variable cv;
  17849. size_t running = 0;
  17850. bool release = false;
  17851. for (size_t i = 0; i < number_of_tasks; i++) {
  17852. EXPECT_TRUE(task_queue->enqueue([&] {
  17853. std::unique_lock<std::mutex> lock(mtx);
  17854. running++;
  17855. cv.notify_all();
  17856. cv.wait(lock, [&] { return release; });
  17857. }));
  17858. }
  17859. {
  17860. std::unique_lock<std::mutex> lock(mtx);
  17861. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17862. [&] { return running == number_of_tasks; }));
  17863. release = true;
  17864. }
  17865. cv.notify_all();
  17866. task_queue->shutdown();
  17867. }
  17868. TEST(TaskQueueTest, MaxQueuedRequests) {
  17869. static constexpr unsigned int qlimit{3};
  17870. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17871. std::condition_variable sem_cv;
  17872. std::mutex sem_mtx;
  17873. int credits = 0;
  17874. bool queued;
  17875. /* Fill up the queue with tasks that will block until we give them credits to
  17876. * complete. */
  17877. for (unsigned int n = 0; n <= qlimit;) {
  17878. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17879. std::unique_lock<std::mutex> lock(sem_mtx);
  17880. while (credits <= 0) {
  17881. sem_cv.wait(lock);
  17882. }
  17883. /* Consume the credit and signal the test code if they are all gone. */
  17884. if (--credits == 0) { sem_cv.notify_one(); }
  17885. });
  17886. if (n < qlimit) {
  17887. /* The first qlimit enqueues must succeed. */
  17888. EXPECT_TRUE(queued);
  17889. } else {
  17890. /* The last one will succeed only when the worker thread
  17891. * starts and dequeues the first blocking task. Although
  17892. * not necessary for the correctness of this test, we sleep for
  17893. * a short while to avoid busy waiting. */
  17894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17895. }
  17896. if (queued) { n++; }
  17897. }
  17898. /* Further enqueues must fail since the queue is full. */
  17899. for (auto i = 0; i < 4; i++) {
  17900. queued = task_queue->enqueue([] {});
  17901. EXPECT_FALSE(queued);
  17902. }
  17903. /* Give the credits to allow the previous tasks to complete. */
  17904. {
  17905. std::unique_lock<std::mutex> lock(sem_mtx);
  17906. credits += qlimit + 1;
  17907. }
  17908. sem_cv.notify_all();
  17909. /* Wait for all the credits to be consumed. */
  17910. {
  17911. std::unique_lock<std::mutex> lock(sem_mtx);
  17912. while (credits > 0) {
  17913. sem_cv.wait(lock);
  17914. }
  17915. }
  17916. /* Check that we are able again to enqueue at least qlimit tasks. */
  17917. for (unsigned int i = 0; i < qlimit; i++) {
  17918. queued = task_queue->enqueue([] {});
  17919. EXPECT_TRUE(queued);
  17920. }
  17921. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17922. task_queue->shutdown();
  17923. #else
  17924. EXPECT_NO_THROW(task_queue->shutdown());
  17925. #endif
  17926. }
  17927. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17928. Server svr;
  17929. std::string method;
  17930. std::string body;
  17931. auto has_content_length = false;
  17932. auto has_transfer_encoding = false;
  17933. std::atomic<int> bad_requests{0};
  17934. // Leftover body bytes get parsed as a malformed request and answered with
  17935. // 400
  17936. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17937. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17938. });
  17939. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17940. res.set_redirect("/down", StatusCode::SeeOther_303);
  17941. });
  17942. svr.Get("/down", [&](const Request &req, Response &res) {
  17943. method = req.method;
  17944. body = req.body;
  17945. has_content_length = req.has_header("Content-Length");
  17946. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17947. res.set_content("ok", "text/plain");
  17948. });
  17949. auto port = svr.bind_to_any_port(HOST);
  17950. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17951. auto se = detail::scope_exit([&] {
  17952. svr.stop();
  17953. thread.join();
  17954. ASSERT_FALSE(svr.is_running());
  17955. });
  17956. svr.wait_until_ready();
  17957. const std::string payload = "SECRET-BODY";
  17958. auto check = [&](Client &cli, const Result &res) {
  17959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17960. EXPECT_EQ(StatusCode::OK_200, res->status);
  17961. EXPECT_EQ("ok", res->body);
  17962. EXPECT_EQ("GET", method);
  17963. EXPECT_TRUE(body.empty());
  17964. EXPECT_FALSE(has_content_length);
  17965. EXPECT_FALSE(has_transfer_encoding);
  17966. // Nothing of the original body may be left on the connection
  17967. auto res2 = cli.Get("/down");
  17968. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17969. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17970. EXPECT_EQ("ok", res2->body);
  17971. EXPECT_EQ(0, bad_requests);
  17972. };
  17973. // With content length
  17974. {
  17975. Client cli(HOST, port);
  17976. cli.set_keep_alive(true);
  17977. cli.set_follow_location(true);
  17978. auto res = cli.Post(
  17979. "/up", payload.size(),
  17980. [&](size_t offset, size_t length, DataSink &sink) {
  17981. return sink.write(payload.data() + offset, length);
  17982. },
  17983. "text/plain");
  17984. check(cli, res);
  17985. }
  17986. // Without content length (chunked)
  17987. {
  17988. Client cli(HOST, port);
  17989. cli.set_keep_alive(true);
  17990. cli.set_follow_location(true);
  17991. auto res = cli.Post(
  17992. "/up",
  17993. [&](size_t /*offset*/, DataSink &sink) {
  17994. sink.write(payload.data(), payload.size());
  17995. sink.done();
  17996. return true;
  17997. },
  17998. "text/plain");
  17999. check(cli, res);
  18000. }
  18001. }
  18002. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18003. Server svr;
  18004. std::string target;
  18005. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18006. // Echo the still-encoded name back in the Location
  18007. const std::string prefix = "/start/";
  18008. res.status = StatusCode::Found_302;
  18009. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18010. });
  18011. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18012. target = req.target;
  18013. res.set_content("ok", "text/plain");
  18014. });
  18015. auto port = svr.bind_to_any_port(HOST);
  18016. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18017. auto se = detail::scope_exit([&] {
  18018. svr.stop();
  18019. thread.join();
  18020. ASSERT_FALSE(svr.is_running());
  18021. });
  18022. svr.wait_until_ready();
  18023. // Decoding the Location path would turn the first four into a path
  18024. // separator, a query delimiter, a fragment delimiter and a different
  18025. // percent-encoded octet. The rest must keep reaching the server as they are.
  18026. const std::vector<std::string> names = {
  18027. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18028. };
  18029. for (auto path_encode : {true, false}) {
  18030. Client cli(HOST, port);
  18031. cli.set_follow_location(true);
  18032. cli.set_path_encode(path_encode);
  18033. for (const auto &name : names) {
  18034. target.clear();
  18035. auto res = cli.Get("/start/" + name);
  18036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18037. EXPECT_EQ(StatusCode::OK_200, res->status);
  18038. EXPECT_EQ("/dest/" + name, target);
  18039. }
  18040. }
  18041. }
  18042. TEST(RedirectTest, NotModifiedIsReturned) {
  18043. Server svr;
  18044. svr.Get("/cached", [](const Request &, Response &res) {
  18045. res.status = StatusCode::NotModified_304;
  18046. });
  18047. auto port = svr.bind_to_any_port(HOST);
  18048. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18049. auto se = detail::scope_exit([&] {
  18050. svr.stop();
  18051. thread.join();
  18052. ASSERT_FALSE(svr.is_running());
  18053. });
  18054. svr.wait_until_ready();
  18055. Client cli(HOST, port);
  18056. cli.set_follow_location(true);
  18057. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18059. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18060. }
  18061. TEST(RedirectTest, NoLocationIsReturned) {
  18062. Server svr;
  18063. svr.Get("/no-location", [](const Request &, Response &res) {
  18064. res.status = StatusCode::Found_302;
  18065. res.set_content("no location", "text/plain");
  18066. });
  18067. auto port = svr.bind_to_any_port(HOST);
  18068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18069. auto se = detail::scope_exit([&] {
  18070. svr.stop();
  18071. thread.join();
  18072. ASSERT_FALSE(svr.is_running());
  18073. });
  18074. svr.wait_until_ready();
  18075. Client cli(HOST, port);
  18076. cli.set_follow_location(true);
  18077. auto res = cli.Get("/no-location");
  18078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18079. EXPECT_EQ(StatusCode::Found_302, res->status);
  18080. EXPECT_EQ("no location", res->body);
  18081. // The callbacks see the body of the response that is returned
  18082. auto handler_called = false;
  18083. auto progress_called = false;
  18084. std::string body;
  18085. auto res2 = cli.Get(
  18086. "/no-location",
  18087. [&](const Response &) {
  18088. handler_called = true;
  18089. return true;
  18090. },
  18091. [&](const char *data, size_t data_length) {
  18092. body.append(data, data_length);
  18093. return true;
  18094. },
  18095. [&](size_t, size_t) {
  18096. progress_called = true;
  18097. return true;
  18098. });
  18099. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18100. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18101. EXPECT_TRUE(handler_called);
  18102. EXPECT_TRUE(progress_called);
  18103. EXPECT_EQ("no location", body);
  18104. }
  18105. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18106. Server svr;
  18107. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18108. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18109. });
  18110. svr.Get("/hello", [](const Request &req, Response &res) {
  18111. res.set_content(req.get_param_value("key"), "text/plain");
  18112. });
  18113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18114. auto se = detail::scope_exit([&] {
  18115. svr.stop();
  18116. thread.join();
  18117. ASSERT_FALSE(svr.is_running());
  18118. });
  18119. svr.wait_until_ready();
  18120. {
  18121. Client cli(HOST, PORT);
  18122. cli.set_follow_location(true);
  18123. auto res = cli.Get("/");
  18124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18125. EXPECT_EQ(StatusCode::OK_200, res->status);
  18126. EXPECT_EQ("val&key2=val2", res->body);
  18127. }
  18128. }
  18129. #endif
  18130. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18131. Server svr;
  18132. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18133. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18134. });
  18135. svr.Get("/hello", [](const Request &req, Response &res) {
  18136. res.set_content(req.get_param_value("key"), "text/plain");
  18137. });
  18138. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18139. auto se = detail::scope_exit([&] {
  18140. svr.stop();
  18141. thread.join();
  18142. ASSERT_FALSE(svr.is_running());
  18143. });
  18144. svr.wait_until_ready();
  18145. {
  18146. Client cli(HOST, PORT);
  18147. cli.set_follow_location(true);
  18148. auto res = cli.Get("/");
  18149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18150. EXPECT_EQ(StatusCode::OK_200, res->status);
  18151. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18152. }
  18153. }
  18154. TEST(RedirectTest, RedirectWithPlusInPath) {
  18155. Server svr;
  18156. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18157. res.set_redirect("/a+b");
  18158. });
  18159. // Route pattern uses regex; escape + as \\+
  18160. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18161. res.set_content(req.path, "text/plain");
  18162. });
  18163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18164. auto se = detail::scope_exit([&] {
  18165. svr.stop();
  18166. thread.join();
  18167. ASSERT_FALSE(svr.is_running());
  18168. });
  18169. svr.wait_until_ready();
  18170. {
  18171. Client cli(HOST, PORT);
  18172. cli.set_follow_location(true);
  18173. auto res = cli.Get("/");
  18174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18175. EXPECT_EQ(StatusCode::OK_200, res->status);
  18176. EXPECT_EQ("/a+b", res->body);
  18177. }
  18178. }
  18179. TEST(RedirectTest, ResolveRelativeLocation) {
  18180. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18181. const std::vector<std::pair<std::string, std::string>> cases = {
  18182. {"g", "/b/c/g"},
  18183. {"./g", "/b/c/g"},
  18184. {"g/", "/b/c/g/"},
  18185. {"?y", "/b/c/d;p?y"},
  18186. {"g?y", "/b/c/g?y"},
  18187. {"#s", "/b/c/d;p?q#s"},
  18188. {"g#s", "/b/c/g#s"},
  18189. {"g?y#s", "/b/c/g?y#s"},
  18190. {";x", "/b/c/;x"},
  18191. {"g;x", "/b/c/g;x"},
  18192. {".", "/b/c/"},
  18193. {"./", "/b/c/"},
  18194. {"..", "/b/"},
  18195. {"../", "/b/"},
  18196. {"../g", "/b/g"},
  18197. {"../..", "/"},
  18198. {"../../", "/"},
  18199. {"../../g", "/g"},
  18200. {"../../../g", "/g"},
  18201. {"g.", "/b/c/g."},
  18202. {".g", "/b/c/.g"},
  18203. {"g..", "/b/c/g.."},
  18204. {"..g", "/b/c/..g"},
  18205. {"./../g", "/b/g"},
  18206. {"./g/.", "/b/c/g/"},
  18207. {"g/./h", "/b/c/g/h"},
  18208. {"g/../h", "/b/c/h"},
  18209. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18210. {"g;x=1/../y", "/b/c/y"},
  18211. {"g?y/./x", "/b/c/g?y/./x"},
  18212. {"g#s/../x", "/b/c/g#s/../x"},
  18213. // Not relative-path references, so left for parse_url.
  18214. {"/g", "/g"},
  18215. {"//g", "//g"},
  18216. {"http://g/x", "http://g/x"},
  18217. {"g:h", "g:h"},
  18218. };
  18219. for (const auto &c : cases) {
  18220. EXPECT_EQ(c.second,
  18221. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18222. << c.first;
  18223. }
  18224. // A result starting with "//" is still a path, not a network-path reference
  18225. EXPECT_EQ("/.//g",
  18226. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18227. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18228. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18229. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18230. }
  18231. TEST(RedirectTest, RemoveDotSegments) {
  18232. // RFC 3986 section 5.2.4
  18233. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18234. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18235. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18236. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18237. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18238. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18239. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18240. }
  18241. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18242. Server svr;
  18243. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18244. res.set_redirect("/dir/../target?x=1");
  18245. });
  18246. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18247. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18248. "/dir/./../target");
  18249. });
  18250. svr.Get("/target", [](const Request &req, Response &res) {
  18251. res.set_content(req.path, "text/plain");
  18252. });
  18253. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18254. auto se = detail::scope_exit([&] {
  18255. svr.stop();
  18256. th.join();
  18257. ASSERT_FALSE(svr.is_running());
  18258. });
  18259. svr.wait_until_ready();
  18260. Client cli("localhost", PORT);
  18261. cli.set_follow_location(true);
  18262. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18263. auto res = cli.Get(path);
  18264. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18265. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18266. EXPECT_EQ("/target", res->body) << path;
  18267. }
  18268. }
  18269. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18270. Server svr;
  18271. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18272. res.set_redirect(req.get_param_value("to"));
  18273. });
  18274. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18275. res.set_content(req.target, "text/plain");
  18276. });
  18277. svr.Get("/other", [](const Request &req, Response &res) {
  18278. res.set_content(req.target, "text/plain");
  18279. });
  18280. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18281. auto se = detail::scope_exit([&] {
  18282. svr.stop();
  18283. thread.join();
  18284. ASSERT_FALSE(svr.is_running());
  18285. });
  18286. svr.wait_until_ready();
  18287. const std::vector<std::pair<std::string, std::string>> cases = {
  18288. {"next", "/dir/next"},
  18289. {"./next?x=1", "/dir/next?x=1"},
  18290. {"../other", "/other"},
  18291. };
  18292. for (const auto &c : cases) {
  18293. Client cli(HOST, PORT);
  18294. cli.set_follow_location(true);
  18295. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18296. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18297. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18298. EXPECT_EQ(c.second, res->body) << c.first;
  18299. }
  18300. }
  18301. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18302. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18303. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18304. Server other;
  18305. std::atomic<int> other_hits{0};
  18306. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18307. other_hits++;
  18308. res.set_content("other", "text/plain");
  18309. });
  18310. auto other_port = other.bind_to_any_port("127.0.0.1");
  18311. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18312. Server svr;
  18313. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18314. res.set_redirect(req.get_param_value("to"));
  18315. });
  18316. svr.Get(".*", [](const Request &req, Response &res) {
  18317. res.set_content(req.path, "text/plain");
  18318. });
  18319. auto port = svr.bind_to_any_port(HOST);
  18320. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18321. auto se = detail::scope_exit([&] {
  18322. svr.stop();
  18323. thread.join();
  18324. other.stop();
  18325. other_thread.join();
  18326. ASSERT_FALSE(svr.is_running());
  18327. ASSERT_FALSE(other.is_running());
  18328. });
  18329. svr.wait_until_ready();
  18330. other.wait_until_ready();
  18331. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18332. for (const auto &to :
  18333. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18334. Client cli(HOST, port);
  18335. cli.set_follow_location(true);
  18336. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18337. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18338. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18339. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18340. }
  18341. EXPECT_EQ(0, other_hits.load());
  18342. }
  18343. #ifdef CPPHTTPLIB_SSL_ENABLED
  18344. TEST(RedirectTest, Issue2185_Online) {
  18345. SSLClient client("github.com");
  18346. client.set_follow_location(true);
  18347. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18348. "Coollab-Windows.zip");
  18349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18350. EXPECT_EQ(StatusCode::OK_200, res->status);
  18351. EXPECT_EQ(9920427U, res->body.size());
  18352. }
  18353. #endif
  18354. TEST(VulnerabilityTest, CRLFInjection) {
  18355. Server svr;
  18356. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18357. res.set_content("Hello 1", "text/plain");
  18358. });
  18359. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18360. res.set_content("Hello 2", "text/plain");
  18361. });
  18362. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18363. res.set_content("Hello 3", "text/plain");
  18364. });
  18365. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18366. res.set_content("Hello 4", "text/plain");
  18367. });
  18368. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18369. for (const auto &x : req.headers) {
  18370. auto key = x.first;
  18371. EXPECT_STRNE("evil", key.c_str());
  18372. }
  18373. });
  18374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18375. auto se = detail::scope_exit([&] {
  18376. svr.stop();
  18377. thread.join();
  18378. ASSERT_FALSE(svr.is_running());
  18379. });
  18380. svr.wait_until_ready();
  18381. {
  18382. Client cli(HOST, PORT);
  18383. cli.Post("/test1", "A=B",
  18384. "application/x-www-form-urlencoded\r\nevil: hello1");
  18385. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18386. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18387. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18388. }
  18389. }
  18390. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18391. auto server_thread = std::thread([] {
  18392. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18393. default_socket_options(srv);
  18394. sockaddr_in addr{};
  18395. addr.sin_family = AF_INET;
  18396. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18398. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18399. ::listen(srv, 1);
  18400. sockaddr_in cli_addr{};
  18401. socklen_t cli_len = sizeof(cli_addr);
  18402. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18403. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18404. std::string buf_all;
  18405. char buf[2048];
  18406. ssize_t n;
  18407. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18408. buf_all.append(buf, static_cast<size_t>(n));
  18409. size_t pos;
  18410. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18411. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18412. auto e = request_block.find("\r\n");
  18413. if (e != std::string::npos) {
  18414. auto request_line = request_block.substr(0, e);
  18415. std::string msg =
  18416. "CRLF injection detected in request line: '" + request_line + "'";
  18417. EXPECT_FALSE(true) << msg;
  18418. }
  18419. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18420. ::send(cli,
  18421. #ifdef _WIN32
  18422. static_cast<const char *>(resp.c_str()),
  18423. static_cast<int>(resp.size()),
  18424. #else
  18425. resp.c_str(), resp.size(),
  18426. #endif
  18427. 0);
  18428. buf_all.erase(0, pos + 4);
  18429. }
  18430. }
  18431. detail::close_socket(cli);
  18432. detail::close_socket(srv);
  18433. });
  18434. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18435. auto cli = Client("127.0.0.1", PORT + 1);
  18436. auto headers = Headers{
  18437. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18438. {"Connection", "keep-alive"}};
  18439. auto res = cli.Get("/hi", headers);
  18440. EXPECT_FALSE(res);
  18441. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18442. server_thread.join();
  18443. }
  18444. // A request rejected before any byte reaches the socket must fail right away
  18445. // instead of waiting for a response the server will never send.
  18446. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18447. // The kernel completes the TCP handshake from the listen backlog, so the
  18448. // client connects, but nothing ever reads, responds or closes.
  18449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18450. default_socket_options(srv);
  18451. sockaddr_in addr{};
  18452. addr.sin_family = AF_INET;
  18453. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18454. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18455. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18456. ASSERT_EQ(0, ::listen(srv, 8));
  18457. auto cli = Client("127.0.0.1", PORT + 1);
  18458. cli.set_read_timeout(10, 0);
  18459. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18460. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18461. std::chrono::steady_clock::now() - start)
  18462. .count();
  18463. };
  18464. {
  18465. Request req;
  18466. req.method = "GE T";
  18467. req.path = "/";
  18468. auto start = std::chrono::steady_clock::now();
  18469. auto res = cli.send(req);
  18470. EXPECT_FALSE(res);
  18471. EXPECT_EQ(Error::Write, res.error());
  18472. EXPECT_LT(elapsed_ms(start), 1000);
  18473. }
  18474. {
  18475. auto start = std::chrono::steady_clock::now();
  18476. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18477. EXPECT_FALSE(res);
  18478. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18479. EXPECT_LT(elapsed_ms(start), 1000);
  18480. }
  18481. EXPECT_FALSE(cli.is_socket_open());
  18482. detail::close_socket(srv);
  18483. }
  18484. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18485. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18486. default_socket_options(srv);
  18487. sockaddr_in addr{};
  18488. addr.sin_family = AF_INET;
  18489. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18491. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18492. ASSERT_EQ(0, ::listen(srv, 1));
  18493. std::string received;
  18494. auto server_thread = std::thread([&] {
  18495. auto sock = ::accept(srv, nullptr, nullptr);
  18496. if (sock == INVALID_SOCKET) { return; }
  18497. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18498. char buf[2048];
  18499. ssize_t n;
  18500. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18501. received.append(buf, static_cast<size_t>(n));
  18502. }
  18503. detail::close_socket(sock);
  18504. });
  18505. {
  18506. auto cli = Client("127.0.0.1", PORT + 1);
  18507. // "Z" sorts after the default headers, so writing straight to the socket
  18508. // would have sent the request line and those headers before the rejection.
  18509. auto handle =
  18510. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18511. EXPECT_FALSE(handle.is_valid());
  18512. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18513. }
  18514. server_thread.join();
  18515. detail::close_socket(srv);
  18516. EXPECT_TRUE(received.empty()) << received;
  18517. }
  18518. TEST(PathParamsTest, StaticMatch) {
  18519. const auto pattern = "/users/all";
  18520. detail::PathParamsMatcher matcher(pattern);
  18521. Request request;
  18522. request.path = "/users/all";
  18523. ASSERT_TRUE(matcher.match(request));
  18524. std::unordered_map<std::string, std::string> expected_params = {};
  18525. EXPECT_EQ(request.path_params, expected_params);
  18526. }
  18527. TEST(PathParamsTest, StaticMismatch) {
  18528. const auto pattern = "/users/all";
  18529. detail::PathParamsMatcher matcher(pattern);
  18530. Request request;
  18531. request.path = "/users/1";
  18532. ASSERT_FALSE(matcher.match(request));
  18533. }
  18534. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18535. const auto pattern = "/users/:id/subscriptions";
  18536. detail::PathParamsMatcher matcher(pattern);
  18537. Request request;
  18538. request.path = "/users/42/subscriptions";
  18539. ASSERT_TRUE(matcher.match(request));
  18540. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18541. EXPECT_EQ(request.path_params, expected_params);
  18542. }
  18543. TEST(PathParamsTest, SingleParamInTheEnd) {
  18544. const auto pattern = "/users/:id";
  18545. detail::PathParamsMatcher matcher(pattern);
  18546. Request request;
  18547. request.path = "/users/24";
  18548. ASSERT_TRUE(matcher.match(request));
  18549. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18550. EXPECT_EQ(request.path_params, expected_params);
  18551. }
  18552. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18553. const auto pattern = "/users/:id/";
  18554. detail::PathParamsMatcher matcher(pattern);
  18555. Request request;
  18556. request.path = "/users/42/";
  18557. ASSERT_TRUE(matcher.match(request));
  18558. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18559. EXPECT_EQ(request.path_params, expected_params);
  18560. }
  18561. TEST(PathParamsTest, EmptyParam) {
  18562. const auto pattern = "/users/:id/";
  18563. detail::PathParamsMatcher matcher(pattern);
  18564. Request request;
  18565. request.path = "/users//";
  18566. ASSERT_TRUE(matcher.match(request));
  18567. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18568. EXPECT_EQ(request.path_params, expected_params);
  18569. }
  18570. TEST(PathParamsTest, FragmentMismatch) {
  18571. const auto pattern = "/users/:id/";
  18572. detail::PathParamsMatcher matcher(pattern);
  18573. Request request;
  18574. request.path = "/admins/24/";
  18575. ASSERT_FALSE(matcher.match(request));
  18576. }
  18577. TEST(PathParamsTest, ExtraFragments) {
  18578. const auto pattern = "/users/:id";
  18579. detail::PathParamsMatcher matcher(pattern);
  18580. Request request;
  18581. request.path = "/users/42/subscriptions";
  18582. ASSERT_FALSE(matcher.match(request));
  18583. }
  18584. TEST(PathParamsTest, MissingTrailingParam) {
  18585. const auto pattern = "/users/:id";
  18586. detail::PathParamsMatcher matcher(pattern);
  18587. Request request;
  18588. request.path = "/users";
  18589. ASSERT_FALSE(matcher.match(request));
  18590. }
  18591. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18592. const auto pattern = "/users/:id/subscriptions";
  18593. detail::PathParamsMatcher matcher(pattern);
  18594. Request request;
  18595. request.path = "/users/subscriptions";
  18596. ASSERT_FALSE(matcher.match(request));
  18597. }
  18598. TEST(PathParamsTest, MultipleParams) {
  18599. const auto pattern = "/users/:userid/subscriptions/:subid";
  18600. detail::PathParamsMatcher matcher(pattern);
  18601. Request request;
  18602. request.path = "/users/42/subscriptions/2";
  18603. ASSERT_TRUE(matcher.match(request));
  18604. std::unordered_map<std::string, std::string> expected_params = {
  18605. {"userid", "42"}, {"subid", "2"}};
  18606. EXPECT_EQ(request.path_params, expected_params);
  18607. }
  18608. TEST(PathParamsTest, SequenceOfParams) {
  18609. const auto pattern = "/values/:x/:y/:z";
  18610. detail::PathParamsMatcher matcher(pattern);
  18611. Request request;
  18612. request.path = "/values/1/2/3";
  18613. ASSERT_TRUE(matcher.match(request));
  18614. std::unordered_map<std::string, std::string> expected_params = {
  18615. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18616. EXPECT_EQ(request.path_params, expected_params);
  18617. }
  18618. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18619. const auto pattern = "/prefix:suffix";
  18620. detail::PathParamsMatcher matcher(pattern);
  18621. Request request;
  18622. request.path = "/prefix:suffix";
  18623. ASSERT_TRUE(matcher.match(request));
  18624. const std::unordered_map<std::string, std::string> expected_params = {};
  18625. EXPECT_EQ(request.path_params, expected_params);
  18626. }
  18627. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18628. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18629. // calling thread's stack on a long enough path for a quantified pattern;
  18630. // RegexMatcher must refuse to run regex matching on paths beyond
  18631. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18632. detail::RegexMatcher matcher("/files/(.*)");
  18633. Request within_limit;
  18634. within_limit.path = "/files/" + std::string(10, 'A');
  18635. EXPECT_TRUE(matcher.match(within_limit));
  18636. Request over_limit;
  18637. over_limit.path =
  18638. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18639. EXPECT_FALSE(matcher.match(over_limit));
  18640. }
  18641. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18642. Server svr;
  18643. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18644. res.set_content("ok", "text/plain");
  18645. });
  18646. auto port = svr.bind_to_any_port(HOST);
  18647. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18648. auto se = detail::scope_exit([&] {
  18649. svr.stop();
  18650. thread.join();
  18651. ASSERT_FALSE(svr.is_running());
  18652. });
  18653. svr.wait_until_ready();
  18654. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18655. // request URI limit; this used to be able to crash the process.
  18656. std::string path =
  18657. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18658. std::string req = "GET " + path +
  18659. " HTTP/1.1\r\n"
  18660. "Host: " +
  18661. std::string(HOST) + ":" + std::to_string(port) +
  18662. "\r\n"
  18663. "Connection: close\r\n"
  18664. "\r\n";
  18665. std::string response;
  18666. ASSERT_TRUE(send_request(5, req, &response, port));
  18667. EXPECT_NE(std::string::npos, response.find("404"));
  18668. }
  18669. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18670. Server svr;
  18671. auto handler = [](const Request & /*req*/, Response &res) {
  18672. res.set_content("hit", "text/plain");
  18673. };
  18674. // No regex metacharacter, so this one is compared literally
  18675. svr.Get("/literal/route", handler);
  18676. // '.' is a regex metacharacter, so this one must keep regex semantics
  18677. svr.Get("/a.c", handler);
  18678. auto port = svr.bind_to_any_port(HOST);
  18679. std::thread t([&]() { svr.listen_after_bind(); });
  18680. auto se = detail::scope_exit([&] {
  18681. svr.stop();
  18682. t.join();
  18683. ASSERT_FALSE(svr.is_running());
  18684. });
  18685. svr.wait_until_ready();
  18686. Client cli(HOST, port);
  18687. struct {
  18688. const char *path;
  18689. int status;
  18690. } cases[] = {
  18691. {"/literal/route", StatusCode::OK_200},
  18692. {"/literal/routes", StatusCode::NotFound_404},
  18693. {"/literal/rout", StatusCode::NotFound_404},
  18694. {"/abc", StatusCode::OK_200},
  18695. {"/a.c", StatusCode::OK_200},
  18696. };
  18697. for (const auto &x : cases) {
  18698. auto res = cli.Get(x.path);
  18699. ASSERT_TRUE(res) << x.path;
  18700. EXPECT_EQ(x.status, res->status) << x.path;
  18701. }
  18702. }
  18703. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18704. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18705. // from exhausting the stack, so it must only constrain routes that actually
  18706. // run a regular expression. A literal route is matched by comparison and
  18707. // stays usable at any length.
  18708. Server svr;
  18709. const std::string pattern =
  18710. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18711. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18712. res.set_content("hit", "text/plain");
  18713. });
  18714. auto port = svr.bind_to_any_port(HOST);
  18715. std::thread t([&]() { svr.listen_after_bind(); });
  18716. auto se = detail::scope_exit([&] {
  18717. svr.stop();
  18718. t.join();
  18719. ASSERT_FALSE(svr.is_running());
  18720. });
  18721. svr.wait_until_ready();
  18722. Client cli(HOST, port);
  18723. auto res = cli.Get(pattern);
  18724. ASSERT_TRUE(res);
  18725. EXPECT_EQ(StatusCode::OK_200, res->status);
  18726. }
  18727. TEST(ParseUrlTest, VariousPatterns) {
  18728. {
  18729. detail::UrlComponents uc;
  18730. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18731. EXPECT_EQ("http", uc.scheme);
  18732. EXPECT_EQ("example.com", uc.host);
  18733. EXPECT_EQ("8080", uc.port);
  18734. EXPECT_EQ("/path", uc.path);
  18735. EXPECT_EQ("?q=1", uc.query);
  18736. }
  18737. {
  18738. detail::UrlComponents uc;
  18739. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18740. EXPECT_EQ("https", uc.scheme);
  18741. EXPECT_EQ("example.com", uc.host);
  18742. EXPECT_TRUE(uc.port.empty());
  18743. EXPECT_EQ("/path", uc.path);
  18744. }
  18745. {
  18746. detail::UrlComponents uc;
  18747. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18748. EXPECT_EQ("::1", uc.host);
  18749. EXPECT_EQ("8080", uc.port);
  18750. EXPECT_EQ("/path", uc.path);
  18751. }
  18752. {
  18753. detail::UrlComponents uc;
  18754. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18755. }
  18756. {
  18757. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18758. // the path while the connection still targets the bracketed host.
  18759. detail::UrlComponents uc;
  18760. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18761. }
  18762. {
  18763. detail::UrlComponents uc;
  18764. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18765. }
  18766. {
  18767. detail::UrlComponents uc;
  18768. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18769. EXPECT_EQ("::1", uc.host);
  18770. EXPECT_TRUE(uc.port.empty());
  18771. EXPECT_EQ("/path", uc.path);
  18772. }
  18773. {
  18774. detail::UrlComponents uc;
  18775. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18776. EXPECT_TRUE(uc.scheme.empty());
  18777. EXPECT_EQ("example.com", uc.host);
  18778. EXPECT_EQ("/path", uc.path);
  18779. EXPECT_EQ("?q=1", uc.query);
  18780. }
  18781. {
  18782. detail::UrlComponents uc;
  18783. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18784. EXPECT_TRUE(uc.host.empty());
  18785. EXPECT_EQ("/path", uc.path);
  18786. EXPECT_EQ("?q=1", uc.query);
  18787. }
  18788. {
  18789. detail::UrlComponents uc;
  18790. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18791. EXPECT_EQ("example.com", uc.host);
  18792. EXPECT_EQ("8080", uc.port);
  18793. }
  18794. {
  18795. // Unix socket path — must not be parsed as host
  18796. detail::UrlComponents uc;
  18797. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18798. EXPECT_TRUE(uc.host.empty());
  18799. }
  18800. {
  18801. detail::UrlComponents uc;
  18802. ASSERT_TRUE(detail::parse_url("", uc));
  18803. EXPECT_TRUE(uc.host.empty());
  18804. EXPECT_TRUE(uc.path.empty());
  18805. }
  18806. {
  18807. detail::UrlComponents uc;
  18808. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18809. EXPECT_EQ("http", uc.scheme);
  18810. }
  18811. {
  18812. detail::UrlComponents uc;
  18813. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18814. }
  18815. {
  18816. // Accepted by parse_url; callers restrict to http/https
  18817. detail::UrlComponents uc;
  18818. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18819. EXPECT_EQ("ftp", uc.scheme);
  18820. }
  18821. {
  18822. detail::UrlComponents uc;
  18823. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18824. }
  18825. {
  18826. detail::UrlComponents uc;
  18827. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18828. }
  18829. }
  18830. TEST(ParseUrlTest, FragmentHandling) {
  18831. {
  18832. detail::UrlComponents uc;
  18833. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18834. EXPECT_EQ("/path", uc.path);
  18835. EXPECT_TRUE(uc.query.empty());
  18836. }
  18837. {
  18838. detail::UrlComponents uc;
  18839. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18840. EXPECT_TRUE(uc.path.empty());
  18841. EXPECT_TRUE(uc.query.empty());
  18842. }
  18843. }
  18844. TEST(ParseUrlTest, UserinfoHandling) {
  18845. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18846. // parsers would see evil.com as the host.
  18847. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18848. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18849. for (auto url : urls) {
  18850. detail::UrlComponents uc;
  18851. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18852. }
  18853. }
  18854. TEST(ParseUrlTest, IPv6EdgeCases) {
  18855. {
  18856. detail::UrlComponents uc;
  18857. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18858. EXPECT_TRUE(uc.scheme.empty());
  18859. EXPECT_EQ("::1", uc.host);
  18860. EXPECT_EQ("8080", uc.port);
  18861. }
  18862. {
  18863. // Zone ID '%25' is not in [a-fA-F0-9:]
  18864. detail::UrlComponents uc;
  18865. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18866. }
  18867. }
  18868. TEST(ParseUrlTest, SchemeEdgeCases) {
  18869. {
  18870. detail::UrlComponents uc;
  18871. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18872. }
  18873. {
  18874. detail::UrlComponents uc;
  18875. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18876. }
  18877. {
  18878. detail::UrlComponents uc;
  18879. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18880. }
  18881. {
  18882. detail::UrlComponents uc;
  18883. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18884. EXPECT_EQ("https", uc.scheme);
  18885. }
  18886. }
  18887. TEST(ParseUrlTest, PortEdgeCases) {
  18888. {
  18889. detail::UrlComponents uc;
  18890. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18891. EXPECT_TRUE(uc.port.empty());
  18892. EXPECT_EQ("/path", uc.path);
  18893. }
  18894. {
  18895. // parse_url accepts any port string; validation is done by parse_port
  18896. detail::UrlComponents uc;
  18897. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18898. EXPECT_EQ("abc", uc.port);
  18899. }
  18900. }
  18901. TEST(ParseUrlTest, WebSocketPatterns) {
  18902. {
  18903. detail::UrlComponents uc;
  18904. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18905. EXPECT_EQ("ws", uc.scheme);
  18906. EXPECT_EQ("echo.example.com", uc.host);
  18907. EXPECT_EQ("8080", uc.port);
  18908. EXPECT_EQ("/ws", uc.path);
  18909. }
  18910. {
  18911. detail::UrlComponents uc;
  18912. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18913. EXPECT_EQ("wss", uc.scheme);
  18914. EXPECT_EQ("echo.example.com", uc.host);
  18915. EXPECT_TRUE(uc.port.empty());
  18916. EXPECT_EQ("/ws", uc.path);
  18917. }
  18918. }
  18919. TEST(ParseUrlTest, QueryOnly) {
  18920. detail::UrlComponents uc;
  18921. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18922. EXPECT_TRUE(uc.host.empty());
  18923. EXPECT_TRUE(uc.path.empty());
  18924. EXPECT_EQ("?q=1&r=2", uc.query);
  18925. }
  18926. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18927. detail::UrlComponents uc;
  18928. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18929. EXPECT_TRUE(uc.scheme.empty());
  18930. EXPECT_EQ("example.com", uc.host);
  18931. EXPECT_EQ("443", uc.port);
  18932. EXPECT_EQ("/path", uc.path);
  18933. }
  18934. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18935. // If ipv6 regex working, regex match codepath is taken.
  18936. // else port will default to 80 in Client impl
  18937. int clientImplMagicPort = 80;
  18938. int port = 4321;
  18939. // above ports must be different to avoid false negative
  18940. EXPECT_NE(clientImplMagicPort, port);
  18941. std::string ipV6TestURL = "http://[ff06::c3]";
  18942. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18943. CLIENT_PRIVATE_KEY_FILE);
  18944. EXPECT_EQ(cli.port(), port);
  18945. }
  18946. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18947. auto file_path = "./www/dir/index.html";
  18948. auto dir_path = "./www/dir";
  18949. detail::FileStat stat_file(file_path);
  18950. EXPECT_TRUE(stat_file.is_file());
  18951. EXPECT_FALSE(stat_file.is_dir());
  18952. detail::FileStat stat_dir(dir_path);
  18953. EXPECT_FALSE(stat_dir.is_file());
  18954. EXPECT_TRUE(stat_dir.is_dir());
  18955. }
  18956. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18957. // IPv4 with default HTTP port (80)
  18958. EXPECT_EQ("example.com",
  18959. detail::make_host_and_port_string("example.com", 80, false));
  18960. // IPv4 with default HTTPS port (443)
  18961. EXPECT_EQ("example.com",
  18962. detail::make_host_and_port_string("example.com", 443, true));
  18963. // IPv4 with non-default HTTP port
  18964. EXPECT_EQ("example.com:8080",
  18965. detail::make_host_and_port_string("example.com", 8080, false));
  18966. // IPv4 with non-default HTTPS port
  18967. EXPECT_EQ("example.com:8443",
  18968. detail::make_host_and_port_string("example.com", 8443, true));
  18969. // IPv6 with default HTTP port (80)
  18970. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18971. // IPv6 with default HTTPS port (443)
  18972. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18973. // IPv6 with non-default HTTP port
  18974. EXPECT_EQ("[::1]:8080",
  18975. detail::make_host_and_port_string("::1", 8080, false));
  18976. // IPv6 with non-default HTTPS port
  18977. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18978. // IPv6 full address with default port
  18979. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18980. detail::make_host_and_port_string(
  18981. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18982. // IPv6 full address with non-default port
  18983. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18984. detail::make_host_and_port_string(
  18985. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18986. // IPv6 localhost with non-default port
  18987. EXPECT_EQ("[::1]:3000",
  18988. detail::make_host_and_port_string("::1", 3000, false));
  18989. // IPv6 with zone ID (link-local address) with default port
  18990. EXPECT_EQ("[fe80::1%eth0]",
  18991. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18992. // IPv6 with zone ID (link-local address) with non-default port
  18993. EXPECT_EQ("[fe80::1%eth0]:8080",
  18994. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18995. // Edge case: Port 443 with is_ssl=false (should add port)
  18996. EXPECT_EQ("example.com:443",
  18997. detail::make_host_and_port_string("example.com", 443, false));
  18998. // Edge case: Port 80 with is_ssl=true (should add port)
  18999. EXPECT_EQ("example.com:80",
  19000. detail::make_host_and_port_string("example.com", 80, true));
  19001. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19002. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19003. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19004. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19005. // Security fix: Already bracketed IPv6 should not get double brackets
  19006. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19007. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19008. EXPECT_EQ("[::1]:8080",
  19009. detail::make_host_and_port_string("[::1]", 8080, false));
  19010. EXPECT_EQ("[2001:db8::1]:8080",
  19011. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19012. EXPECT_EQ("[fe80::1%eth0]",
  19013. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19014. EXPECT_EQ("[fe80::1%eth0]:8080",
  19015. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19016. // Edge case: Empty host (should return as-is)
  19017. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19018. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19019. // This is a known limitation but shouldn't crash
  19020. EXPECT_EQ("[host:name]",
  19021. detail::make_host_and_port_string("host:name", 80, false));
  19022. // Port number edge cases (no validation, but should not crash)
  19023. EXPECT_EQ("example.com:0",
  19024. detail::make_host_and_port_string("example.com", 0, false));
  19025. EXPECT_EQ("example.com:-1",
  19026. detail::make_host_and_port_string("example.com", -1, false));
  19027. EXPECT_EQ("example.com:65535",
  19028. detail::make_host_and_port_string("example.com", 65535, false));
  19029. EXPECT_EQ("example.com:65536",
  19030. detail::make_host_and_port_string("example.com", 65536, false));
  19031. }
  19032. namespace httplib {
  19033. namespace detail {
  19034. std::string
  19035. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19036. const std::string &host, int port);
  19037. } // namespace detail
  19038. } // namespace httplib
  19039. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19040. std::map<std::string, std::string> addr_map = {
  19041. {"ipv4.example", "192.0.2.10"},
  19042. {"ipv6.example", "2001:db8::1"},
  19043. {"name.example", "internal.example.lan"},
  19044. {"empty.example", ""}};
  19045. EXPECT_EQ("192.0.2.10:443",
  19046. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19047. EXPECT_EQ("[2001:db8::1]:443",
  19048. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19049. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19050. addr_map, "name.example", 8443));
  19051. // An empty or absent mapping keeps the hostname as the target
  19052. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19053. addr_map, "empty.example", 443));
  19054. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19055. addr_map, "other.example", 443));
  19056. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19057. }
  19058. #ifdef CPPHTTPLIB_SSL_ENABLED
  19059. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19060. httplib::SSLClient cli("roblox.com", 443);
  19061. cli.set_follow_location(true);
  19062. auto res = cli.Get("/");
  19063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19064. EXPECT_EQ(StatusCode::OK_200, res->status);
  19065. }
  19066. #endif
  19067. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19068. Server svr;
  19069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19070. EXPECT_EQ(res.status, 400);
  19071. });
  19072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19073. auto se = detail::scope_exit([&] {
  19074. svr.stop();
  19075. thread.join();
  19076. ASSERT_FALSE(svr.is_running());
  19077. });
  19078. svr.wait_until_ready();
  19079. Client cli(HOST, PORT);
  19080. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19081. }
  19082. TEST(InvalidHeaderCharsTest, is_field_name) {
  19083. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19084. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19085. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19086. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19087. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19088. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19089. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19090. EXPECT_FALSE(detail::fields::is_field_name(""));
  19091. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19092. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19093. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19094. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19095. }
  19096. TEST(InvalidHeaderCharsTest, is_field_value) {
  19097. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19098. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19099. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19100. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19101. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19102. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19103. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19104. EXPECT_TRUE(detail::fields::is_field_value(""));
  19105. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19106. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19107. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19108. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19109. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19110. }
  19111. TEST(InvalidHeaderCharsTest, OnServer) {
  19112. Server svr;
  19113. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19114. std::string header = "Not Set";
  19115. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19116. res.set_header(header, "value");
  19117. res.set_content("Page Content Page Content", "text/plain");
  19118. });
  19119. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19120. std::string header = "Not Set";
  19121. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19122. res.set_header("X-Test", header);
  19123. res.set_content("Page Content Page Content", "text/plain");
  19124. });
  19125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19126. auto se = detail::scope_exit([&] {
  19127. svr.stop();
  19128. thread.join();
  19129. ASSERT_FALSE(svr.is_running());
  19130. });
  19131. svr.wait_until_ready();
  19132. Client cli(HOST, PORT);
  19133. {
  19134. auto res = cli.Get(
  19135. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19137. EXPECT_EQ("Page Content Page Content", res->body);
  19138. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19139. }
  19140. {
  19141. auto res = cli.Get(
  19142. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19144. EXPECT_EQ("Page Content Page Content", res->body);
  19145. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19146. }
  19147. }
  19148. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19149. auto handled = false;
  19150. Server svr;
  19151. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19152. thread t = thread([&] { svr.listen(HOST, PORT); });
  19153. auto se = detail::scope_exit([&] {
  19154. svr.stop();
  19155. t.join();
  19156. ASSERT_FALSE(svr.is_running());
  19157. ASSERT_FALSE(handled);
  19158. });
  19159. svr.wait_until_ready();
  19160. auto req = "POST /test HTTP/1.1\r\n"
  19161. "Content-Length: x\r\n"
  19162. "\r\n";
  19163. std::string response;
  19164. ASSERT_TRUE(send_request(1, req, &response));
  19165. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19166. response.substr(0, response.find("\r\n")));
  19167. }
  19168. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19169. // case-insensitive, and a server that receives a 100-continue expectation in
  19170. // an HTTP/1.0 request MUST ignore it.
  19171. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19172. std::string response;
  19173. ASSERT_TRUE(send_request(1, req, &response, port));
  19174. *got_100 = response.find("100 Continue") != std::string::npos;
  19175. }
  19176. class ExpectTokenTest : public ::testing::Test {
  19177. protected:
  19178. void SetUp() override {
  19179. svr_.Post("/p", [](const Request &, Response &res) {
  19180. res.set_content("ok", "text/plain");
  19181. });
  19182. port_ = svr_.bind_to_any_port(HOST);
  19183. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19184. svr_.wait_until_ready();
  19185. }
  19186. void TearDown() override {
  19187. svr_.stop();
  19188. if (thread_.joinable()) { thread_.join(); }
  19189. }
  19190. std::string request(const char *version, const char *expect_value) const {
  19191. return std::string("POST /p ") + version +
  19192. "\r\n"
  19193. "Host: localhost\r\n"
  19194. "Content-Length: 2\r\n"
  19195. "Connection: close\r\n"
  19196. "Expect: " +
  19197. expect_value +
  19198. "\r\n"
  19199. "\r\n"
  19200. "hi";
  19201. }
  19202. Server svr_;
  19203. int port_ = 0;
  19204. thread thread_;
  19205. };
  19206. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19207. bool got_100 = false;
  19208. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19209. EXPECT_TRUE(got_100);
  19210. }
  19211. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19212. bool got_100 = true;
  19213. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19214. EXPECT_FALSE(got_100);
  19215. }
  19216. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19217. bool got_100 = false;
  19218. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19219. EXPECT_TRUE(got_100);
  19220. }
  19221. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19222. bool got_100 = false;
  19223. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19224. EXPECT_TRUE(got_100);
  19225. }
  19226. // `100 Continue` is sent only when the server starts reading the body, so a
  19227. // request rejected before that never invites the client to send it. The
  19228. // requests below carry the expectation but withhold the body, as a client
  19229. // waiting for `100 Continue` would.
  19230. // A POST that expects `100 Continue` and withholds its two-byte body.
  19231. static std::string expect_headers_only(const std::string &path) {
  19232. return "POST " + path +
  19233. " HTTP/1.1\r\n"
  19234. "Host: localhost\r\n"
  19235. "Content-Length: 2\r\n"
  19236. "Expect: 100-continue\r\n"
  19237. "\r\n";
  19238. }
  19239. class ExpectLazyContinueTest : public ::testing::Test {
  19240. protected:
  19241. void SetUp() override {
  19242. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19243. if (req.path == "/pre-routing") {
  19244. res.status = StatusCode::Unauthorized_401;
  19245. return Server::HandlerResponse::Handled;
  19246. }
  19247. return Server::HandlerResponse::Unhandled;
  19248. });
  19249. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19250. if (req.matched_route == "/pre-request") {
  19251. res.status = StatusCode::Forbidden_403;
  19252. return Server::HandlerResponse::Handled;
  19253. }
  19254. return Server::HandlerResponse::Unhandled;
  19255. });
  19256. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19257. res.set_content("ok", "text/plain");
  19258. });
  19259. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19260. res.set_content("ok", "text/plain");
  19261. });
  19262. svr_.Post("/reader-used", [](const Request &, Response &res,
  19263. const ContentReader &content_reader) {
  19264. std::string body;
  19265. content_reader([&](const char *data, size_t len) {
  19266. body.append(data, len);
  19267. return true;
  19268. });
  19269. res.set_content(body, "text/plain");
  19270. });
  19271. svr_.Post("/reader-unused",
  19272. [](const Request &, Response &res, const ContentReader &) {
  19273. res.set_content("ignored", "text/plain");
  19274. });
  19275. port_ = svr_.bind_to_any_port(HOST);
  19276. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19277. svr_.wait_until_ready();
  19278. }
  19279. void TearDown() override {
  19280. svr_.stop();
  19281. if (thread_.joinable()) { thread_.join(); }
  19282. }
  19283. // Sends `req` and reads until the server closes the connection. Returns
  19284. // false if the read had to wait for the client-side timeout instead.
  19285. bool send_until_closed(const std::string &req, std::string *resp) const {
  19286. auto start = std::chrono::steady_clock::now();
  19287. if (!send_request(3, req, resp, port_)) { return false; }
  19288. auto elapsed = std::chrono::steady_clock::now() - start;
  19289. return elapsed < std::chrono::seconds(2);
  19290. }
  19291. // The final response comes without `100 Continue`, and the server closes
  19292. // the connection since the body may or may not follow.
  19293. void expect_final_without_interim(const std::string &path,
  19294. const char *status_line) const {
  19295. std::string resp;
  19296. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19297. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19298. EXPECT_EQ(0u, resp.find(status_line));
  19299. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19300. }
  19301. Server svr_;
  19302. int port_ = 0;
  19303. thread thread_;
  19304. };
  19305. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19306. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19307. }
  19308. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19309. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19310. }
  19311. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19312. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19313. }
  19314. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19315. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19316. }
  19317. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19318. // The body follows once `100 Continue` has had time to arrive.
  19319. auto req = expect_headers_only("/reader-used");
  19320. req.insert(req.size() - 2, "Connection: close\r\n");
  19321. std::string resp;
  19322. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19323. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19324. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19325. EXPECT_NE(std::string::npos, resp.find("hi"));
  19326. }
  19327. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19328. // Large enough for the client to add `Expect: 100-continue` itself.
  19329. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19330. std::atomic<bool> body_sent{false};
  19331. Client cli(HOST, port_);
  19332. auto res = cli.Post(
  19333. "/pre-request", length,
  19334. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19335. body_sent = true;
  19336. std::string chunk(len, 'x');
  19337. sink.write(chunk.data(), chunk.size());
  19338. return true;
  19339. },
  19340. "application/octet-stream");
  19341. ASSERT_TRUE(res);
  19342. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19343. EXPECT_FALSE(body_sent);
  19344. }
  19345. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19346. Server svr;
  19347. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19348. return StatusCode::ExpectationFailed_417;
  19349. });
  19350. svr.Post("/p", [](const Request &, Response &res) {
  19351. res.set_content("ok", "text/plain");
  19352. });
  19353. auto port = svr.bind_to_any_port(HOST);
  19354. thread t = thread([&] { svr.listen_after_bind(); });
  19355. auto se = detail::scope_exit([&] {
  19356. svr.stop();
  19357. t.join();
  19358. });
  19359. svr.wait_until_ready();
  19360. std::string resp;
  19361. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19362. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19363. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19364. // Exactly one response: the route handler must not run after the 417.
  19365. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19366. }
  19367. #ifndef _WIN32
  19368. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19369. static constexpr char reject[] = "Unauthorized";
  19370. static constexpr char accept[] = "Upload accepted";
  19371. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19372. Server svr;
  19373. svr.set_expect_100_continue_handler(
  19374. [](const Request & /*req*/, Response &res) {
  19375. res.status = StatusCode::Unauthorized_401;
  19376. res.set_content(reject, "text/plain");
  19377. return res.status;
  19378. });
  19379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19380. res.set_content(accept, "text/plain");
  19381. });
  19382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19383. auto se = detail::scope_exit([&] {
  19384. svr.stop();
  19385. thread.join();
  19386. ASSERT_FALSE(svr.is_running());
  19387. });
  19388. svr.wait_until_ready();
  19389. {
  19390. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19391. curl_easy_init(), &curl_easy_cleanup};
  19392. ASSERT_NE(curl, nullptr);
  19393. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19394. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19395. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19396. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19397. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19398. &curl_slist_free_all};
  19399. ASSERT_NE(list, nullptr);
  19400. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19401. struct read_data {
  19402. uint64_t read_size;
  19403. uint64_t total_size;
  19404. } data = {0, total_size};
  19405. using read_callback_t =
  19406. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19407. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19408. void *userdata) -> size_t {
  19409. read_data *d = (read_data *)userdata;
  19410. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19411. std::fill_n(ptr, size * nmemb, 'A');
  19412. d->read_size += size * nmemb;
  19413. return size * nmemb;
  19414. };
  19415. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19416. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19417. std::vector<char> buffer;
  19418. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19419. using write_callback_t =
  19420. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19421. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19422. void *userdata) -> size_t {
  19423. std::vector<char> *buf = (std::vector<char> *)userdata;
  19424. buf->reserve(buf->size() + size * nmemb + 1);
  19425. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19426. return size * nmemb;
  19427. };
  19428. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19429. {
  19430. const auto res = curl_easy_perform(curl.get());
  19431. ASSERT_EQ(res, CURLE_OK);
  19432. }
  19433. {
  19434. auto response_code = long{};
  19435. const auto res =
  19436. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19437. ASSERT_EQ(res, CURLE_OK);
  19438. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19439. }
  19440. {
  19441. auto dl = curl_off_t{};
  19442. const auto res =
  19443. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19444. ASSERT_EQ(res, CURLE_OK);
  19445. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19446. }
  19447. {
  19448. buffer.push_back('\0');
  19449. ASSERT_STRCASEEQ(buffer.data(), reject);
  19450. }
  19451. }
  19452. }
  19453. #endif
  19454. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19455. // Regression test for #2458.
  19456. //
  19457. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19458. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19459. // ticket can make the client socket spuriously readable during the
  19460. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19461. // the client withholds the body and then blocks reading a response that never
  19462. // comes, failing with `Failed to read connection`.
  19463. //
  19464. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19465. // within the timeout. This raw OpenSSL server deliberately never sends
  19466. // `100 Continue`; the client must still deliver the body and receive 200.
  19467. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19468. signal(SIGPIPE, SIG_IGN);
  19469. const auto port = PORT + 4;
  19470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19471. ASSERT_NE(srv, INVALID_SOCKET);
  19472. int opt = 1;
  19473. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19474. sockaddr_in addr{};
  19475. addr.sin_family = AF_INET;
  19476. addr.sin_port = htons(static_cast<uint16_t>(port));
  19477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19478. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19479. ASSERT_EQ(0, ::listen(srv, 1));
  19480. std::atomic<size_t> server_body_bytes{0};
  19481. auto server_thread = std::thread([&] {
  19482. sockaddr_in cli_addr{};
  19483. socklen_t cli_len = sizeof(cli_addr);
  19484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19485. if (cli == INVALID_SOCKET) { return; }
  19486. // Bound the lifetime of the server side so a buggy client (which never
  19487. // sends the body) cannot make this thread block forever on join.
  19488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19489. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19490. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19491. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19492. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19493. SSL *ssl = SSL_new(ctx);
  19494. SSL_set_fd(ssl, static_cast<int>(cli));
  19495. if (SSL_accept(ssl) > 0) {
  19496. // Read the request headers. Reading here also flushes the TLS 1.3
  19497. // session tickets to the client. Deliberately do NOT send
  19498. // `100 Continue`.
  19499. std::string buf;
  19500. char tmp[1024];
  19501. while (buf.find("\r\n\r\n") == std::string::npos) {
  19502. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19503. if (n <= 0) { break; }
  19504. buf.append(tmp, static_cast<size_t>(n));
  19505. }
  19506. // A correct client sends the body now; count what arrives.
  19507. auto pos = buf.find("\r\n\r\n");
  19508. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19509. while (body < 4096) {
  19510. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19511. if (n <= 0) { break; }
  19512. body += static_cast<size_t>(n);
  19513. }
  19514. server_body_bytes = body;
  19515. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19516. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19517. SSL_shutdown(ssl);
  19518. }
  19519. SSL_free(ssl);
  19520. detail::close_socket(cli);
  19521. SSL_CTX_free(ctx);
  19522. });
  19523. auto se = detail::scope_exit([&] {
  19524. server_thread.join();
  19525. detail::close_socket(srv);
  19526. });
  19527. SSLClient cli("127.0.0.1", port);
  19528. cli.enable_server_certificate_verification(false);
  19529. cli.set_connection_timeout(5, 0);
  19530. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19531. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19532. std::string body(4096, 'A');
  19533. auto res = cli.Put("/api/test", body, "application/json");
  19534. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19535. EXPECT_EQ(StatusCode::OK_200, res->status);
  19536. EXPECT_EQ(body.size(), server_body_bytes.load());
  19537. }
  19538. #endif
  19539. template <typename S, typename C>
  19540. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19541. svr.Get("/stream", [&](const Request &, Response &res) {
  19542. auto data = new std::string("01234567890123456789");
  19543. res.set_content_provider(
  19544. data->size(), "text/plain",
  19545. [&, data](size_t offset, size_t length, DataSink &sink) {
  19546. const size_t DATA_CHUNK_SIZE = 4;
  19547. const auto &d = *data;
  19548. std::this_thread::sleep_for(std::chrono::seconds(1));
  19549. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19550. return true;
  19551. },
  19552. [data](bool success) {
  19553. EXPECT_FALSE(success);
  19554. delete data;
  19555. });
  19556. });
  19557. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19558. auto i = new size_t(0);
  19559. res.set_content_provider(
  19560. "text/plain",
  19561. [i](size_t, DataSink &sink) {
  19562. if (*i < 5) {
  19563. std::this_thread::sleep_for(std::chrono::seconds(1));
  19564. sink.write("abcd", 4);
  19565. (*i)++;
  19566. } else {
  19567. sink.done();
  19568. }
  19569. return true;
  19570. },
  19571. [i](bool success) {
  19572. EXPECT_FALSE(success);
  19573. delete i;
  19574. });
  19575. });
  19576. svr.Get("/chunked", [&](const Request &, Response &res) {
  19577. auto i = new size_t(0);
  19578. res.set_chunked_content_provider(
  19579. "text/plain",
  19580. [i](size_t, DataSink &sink) {
  19581. if (*i < 5) {
  19582. std::this_thread::sleep_for(std::chrono::seconds(1));
  19583. sink.os << "abcd";
  19584. (*i)++;
  19585. } else {
  19586. sink.done();
  19587. }
  19588. return true;
  19589. },
  19590. [i](bool success) {
  19591. EXPECT_FALSE(success);
  19592. delete i;
  19593. });
  19594. });
  19595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19596. auto se = detail::scope_exit([&] {
  19597. svr.stop();
  19598. listen_thread.join();
  19599. ASSERT_FALSE(svr.is_running());
  19600. });
  19601. svr.wait_until_ready();
  19602. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19603. {
  19604. auto start = std::chrono::steady_clock::now();
  19605. auto res = cli.Get("/stream");
  19606. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19607. std::chrono::steady_clock::now() - start)
  19608. .count();
  19609. ASSERT_FALSE(res);
  19610. EXPECT_EQ(Error::Read, res.error());
  19611. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19612. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19613. }
  19614. {
  19615. auto start = std::chrono::steady_clock::now();
  19616. auto res = cli.Get("/stream_without_length");
  19617. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19618. std::chrono::steady_clock::now() - start)
  19619. .count();
  19620. ASSERT_FALSE(res);
  19621. EXPECT_EQ(Error::Read, res.error());
  19622. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19623. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19624. }
  19625. {
  19626. auto start = std::chrono::steady_clock::now();
  19627. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19628. EXPECT_EQ("abcd", string(data, data_length));
  19629. return true;
  19630. });
  19631. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19632. std::chrono::steady_clock::now() - start)
  19633. .count();
  19634. ASSERT_FALSE(res);
  19635. EXPECT_EQ(Error::Read, res.error());
  19636. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19637. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19638. }
  19639. }
  19640. TEST(MaxTimeoutTest, ContentStream) {
  19641. time_t timeout = 2000;
  19642. time_t threshold = 200;
  19643. Server svr;
  19644. Client cli("localhost", PORT);
  19645. max_timeout_test(svr, cli, timeout, threshold);
  19646. }
  19647. #ifdef CPPHTTPLIB_SSL_ENABLED
  19648. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19649. time_t timeout = 2000;
  19650. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19652. SSLClient cli("localhost", PORT);
  19653. cli.enable_server_certificate_verification(false);
  19654. max_timeout_test(svr, cli, timeout, threshold);
  19655. }
  19656. #endif
  19657. class EventDispatcher {
  19658. public:
  19659. EventDispatcher() {}
  19660. bool wait_event(DataSink *sink) {
  19661. unique_lock<mutex> lk(m_);
  19662. int id = id_;
  19663. // Wait with timeout to prevent hanging if client disconnects
  19664. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19665. [&] { return cid_ == id; })) {
  19666. return false; // Timeout occurred
  19667. }
  19668. sink->write(message_.data(), message_.size());
  19669. return true;
  19670. }
  19671. void send_event(const string &message) {
  19672. lock_guard<mutex> lk(m_);
  19673. cid_ = id_++;
  19674. message_ = message;
  19675. cv_.notify_all();
  19676. }
  19677. private:
  19678. mutex m_;
  19679. condition_variable cv_;
  19680. atomic_int id_{0};
  19681. atomic_int cid_{-1};
  19682. string message_;
  19683. };
  19684. TEST(ClientInThreadTest, Issue2068) {
  19685. EventDispatcher ed;
  19686. Server svr;
  19687. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19688. res.set_chunked_content_provider("text/event-stream",
  19689. [&](size_t /*offset*/, DataSink &sink) {
  19690. return ed.wait_event(&sink);
  19691. });
  19692. });
  19693. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19694. svr.wait_until_ready();
  19695. thread event_thread([&] {
  19696. int id = 0;
  19697. while (svr.is_running()) {
  19698. this_thread::sleep_for(chrono::milliseconds(500));
  19699. std::stringstream ss;
  19700. ss << "data: " << id << "\n\n";
  19701. ed.send_event(ss.str());
  19702. id++;
  19703. }
  19704. });
  19705. auto se = detail::scope_exit([&] {
  19706. svr.stop();
  19707. listen_thread.join();
  19708. event_thread.join();
  19709. ASSERT_FALSE(svr.is_running());
  19710. });
  19711. {
  19712. auto client = detail::make_unique<Client>(HOST, PORT);
  19713. client->set_read_timeout(std::chrono::minutes(10));
  19714. std::atomic<bool> stop{false};
  19715. std::thread t([&] {
  19716. client->Get("/event1",
  19717. [&](const char *, size_t) -> bool { return !stop; });
  19718. });
  19719. std::this_thread::sleep_for(std::chrono::seconds(2));
  19720. stop = true;
  19721. client->stop();
  19722. t.join();
  19723. // Reset client after thread has finished
  19724. client.reset();
  19725. }
  19726. }
  19727. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19728. auto handled = false;
  19729. Server svr;
  19730. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19731. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19732. auto se = detail::scope_exit([&] {
  19733. svr.stop();
  19734. t.join();
  19735. ASSERT_FALSE(svr.is_running());
  19736. ASSERT_FALSE(handled);
  19737. });
  19738. svr.wait_until_ready();
  19739. // Two Content-Length headers with different values — must be rejected
  19740. auto req = "POST /test HTTP/1.1\r\n"
  19741. "Content-Length: 5\r\n"
  19742. "Content-Length: 10\r\n"
  19743. "\r\n"
  19744. "hello";
  19745. std::string response;
  19746. ASSERT_TRUE(send_request(1, req, &response));
  19747. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19748. response.substr(0, response.find("\r\n")));
  19749. }
  19750. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19751. auto handled = false;
  19752. Server svr;
  19753. svr.Post("/test", [&](const Request &, Response &res) {
  19754. handled = true;
  19755. res.set_content("ok", "text/plain");
  19756. });
  19757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19758. auto se = detail::scope_exit([&] {
  19759. svr.stop();
  19760. t.join();
  19761. ASSERT_FALSE(svr.is_running());
  19762. ASSERT_TRUE(handled);
  19763. });
  19764. svr.wait_until_ready();
  19765. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19766. auto req = "POST /test HTTP/1.1\r\n"
  19767. "Host: localhost\r\n"
  19768. "Content-Length: 5\r\n"
  19769. "Content-Length: 5\r\n"
  19770. "\r\n"
  19771. "hello";
  19772. std::string response;
  19773. ASSERT_TRUE(send_request(1, req, &response));
  19774. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19775. }
  19776. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19777. Server svr;
  19778. svr.Get("/test", [](const Request &, Response &res) {
  19779. res.set_content("ok", "text/plain");
  19780. });
  19781. auto port = svr.bind_to_any_port(HOST);
  19782. thread t = thread([&] { svr.listen_after_bind(); });
  19783. auto se = detail::scope_exit([&] {
  19784. svr.stop();
  19785. t.join();
  19786. ASSERT_FALSE(svr.is_running());
  19787. });
  19788. svr.wait_until_ready();
  19789. auto status_line = [&](const std::string &host_lines) {
  19790. std::string res;
  19791. send_request(
  19792. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19793. &res, port);
  19794. return res.substr(0, res.find("\r\n"));
  19795. };
  19796. const char *accepted[] = {
  19797. "Host: localhost\r\n",
  19798. "Host: a.example:8080\r\n",
  19799. "Host: my_service\r\n",
  19800. "Host: [::1]:8080\r\n",
  19801. "Host: [fe80::1%25eth0]\r\n",
  19802. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19803. };
  19804. for (auto host_lines : accepted) {
  19805. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19806. }
  19807. const char *rejected[] = {
  19808. "Host: a.example\r\nHost: b.example\r\n",
  19809. "Host: a.example\r\nHost: a.example\r\n",
  19810. "Host: a@b.example\r\n",
  19811. "Host: a.example/b\r\n",
  19812. "Host: a.example\\b\r\n",
  19813. "Host: a.example?b\r\n",
  19814. "Host: a.example#b\r\n",
  19815. "Host: a.example b.example\r\n",
  19816. };
  19817. for (auto host_lines : rejected) {
  19818. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19819. << host_lines;
  19820. }
  19821. }
  19822. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19823. Server svr;
  19824. svr.Get("/", [](const Request &req, Response &res) {
  19825. EXPECT_EQ(2U, req.trailers.size());
  19826. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19827. // Denied
  19828. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19829. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19830. // Accepted
  19831. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19832. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19833. EXPECT_TRUE(req.has_trailer("X-World"));
  19834. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19835. res.set_content("ok", "text/plain");
  19836. });
  19837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19838. auto se = detail::scope_exit([&] {
  19839. svr.stop();
  19840. t.join();
  19841. ASSERT_FALSE(svr.is_running());
  19842. });
  19843. svr.wait_until_ready();
  19844. const std::string req = "GET / HTTP/1.1\r\n"
  19845. "Transfer-Encoding: chunked\r\n"
  19846. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19847. "\r\n"
  19848. "0\r\n"
  19849. "Content-Length: 10\r\n"
  19850. "Host: internal.local\r\n"
  19851. "Content-Type: malicious/content\r\n"
  19852. "Cookie: any\r\n"
  19853. "Set-Cookie: any\r\n"
  19854. "X-Forwarded-For: attacker.com\r\n"
  19855. "X-Real-Ip: 1.1.1.1\r\n"
  19856. "X-Hello: hello\r\n"
  19857. "X-World: world\r\n"
  19858. "\r\n";
  19859. std::string res;
  19860. ASSERT_TRUE(send_request(1, req, &res));
  19861. }
  19862. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19863. // several field lines, and the combined value is what has to be parsed. A
  19864. // Trailer field split across lines therefore declares every name it lists;
  19865. // reading only the first line silently drops the trailers the later lines
  19866. // declare. The prohibited-trailer filter still applies to every line.
  19867. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19868. Server svr;
  19869. size_t observed_trailer_count = 0;
  19870. std::string observed_hello;
  19871. std::string observed_world;
  19872. bool observed_content_length = true;
  19873. svr.Get("/", [&](const Request &req, Response &res) {
  19874. observed_trailer_count = req.trailers.size();
  19875. observed_hello = req.get_trailer_value("X-Hello");
  19876. observed_world = req.get_trailer_value("X-World");
  19877. observed_content_length = req.has_trailer("Content-Length");
  19878. res.set_content("ok", "text/plain");
  19879. });
  19880. auto port = svr.bind_to_any_port(HOST);
  19881. thread t = thread([&]() { svr.listen_after_bind(); });
  19882. auto se = detail::scope_exit([&] {
  19883. svr.stop();
  19884. t.join();
  19885. ASSERT_FALSE(svr.is_running());
  19886. });
  19887. svr.wait_until_ready();
  19888. const std::string req = "GET / HTTP/1.1\r\n"
  19889. "Host: localhost\r\n"
  19890. "Transfer-Encoding: chunked\r\n"
  19891. "Trailer: X-Hello\r\n"
  19892. "Trailer: X-World, Content-Length\r\n"
  19893. "\r\n"
  19894. "0\r\n"
  19895. "X-Hello: hello\r\n"
  19896. "X-World: world\r\n"
  19897. "Content-Length: 10\r\n"
  19898. "\r\n";
  19899. std::string res;
  19900. ASSERT_TRUE(send_request(1, req, &res, port));
  19901. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19902. // Accepted: both field lines contribute to the declared set
  19903. EXPECT_EQ(2U, observed_trailer_count);
  19904. EXPECT_EQ(observed_hello, "hello");
  19905. EXPECT_EQ(observed_world, "world");
  19906. // Denied: a prohibited name stays prohibited on a later field line
  19907. EXPECT_FALSE(observed_content_length);
  19908. }
  19909. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19910. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19911. // unbounded run of fields that are never declared, because the counter would
  19912. // only advance for declared fields.
  19913. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19914. Server svr;
  19915. bool handler_called = false;
  19916. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19917. handler_called = true;
  19918. res.set_content("ok", "text/plain");
  19919. });
  19920. auto port = svr.bind_to_any_port(HOST);
  19921. thread t = thread([&]() { svr.listen_after_bind(); });
  19922. auto se = detail::scope_exit([&] {
  19923. svr.stop();
  19924. t.join();
  19925. ASSERT_FALSE(svr.is_running());
  19926. });
  19927. svr.wait_until_ready();
  19928. // Declare nothing, then send far more undeclared trailer fields than the
  19929. // header-count limit. Parsing must stop and reject the request rather than
  19930. // read every line.
  19931. std::string req = "GET / HTTP/1.1\r\n"
  19932. "Transfer-Encoding: chunked\r\n"
  19933. "\r\n"
  19934. "0\r\n";
  19935. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19936. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19937. }
  19938. req += "\r\n";
  19939. std::string res;
  19940. ASSERT_TRUE(send_request(1, req, &res, port));
  19941. // The request is rejected before the handler runs.
  19942. EXPECT_FALSE(handler_called);
  19943. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19944. }
  19945. // The set of declared trailer names is capped so a peer cannot grow it without
  19946. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19947. // declared past the cap is not honored, even if the field is actually sent.
  19948. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19949. Server svr;
  19950. // One name inside the cap and one past it, so the test tracks the cap rather
  19951. // than a fixed count.
  19952. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19953. const std::string within_cap_name = "X-T-0";
  19954. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19955. bool observed_within_cap = false;
  19956. bool observed_past_cap = false;
  19957. svr.Get("/", [&](const Request &req, Response &res) {
  19958. observed_within_cap = req.has_trailer(within_cap_name);
  19959. observed_past_cap = req.has_trailer(past_cap_name);
  19960. res.set_content("ok", "text/plain");
  19961. });
  19962. auto port = svr.bind_to_any_port(HOST);
  19963. thread t = thread([&]() { svr.listen_after_bind(); });
  19964. auto se = detail::scope_exit([&] {
  19965. svr.stop();
  19966. t.join();
  19967. ASSERT_FALSE(svr.is_running());
  19968. });
  19969. svr.wait_until_ready();
  19970. // Declare more trailer names than the cap in a single Trailer field, then
  19971. // actually send the first (within the cap) and the last (past it).
  19972. std::string trailer_decl = "Trailer: ";
  19973. for (int i = 0; i < declared_count; i++) {
  19974. if (i != 0) { trailer_decl += ", "; }
  19975. trailer_decl += "X-T-" + std::to_string(i);
  19976. }
  19977. trailer_decl += "\r\n";
  19978. const std::string req = "GET / HTTP/1.1\r\n"
  19979. "Host: localhost\r\n"
  19980. "Transfer-Encoding: chunked\r\n" +
  19981. trailer_decl +
  19982. "\r\n"
  19983. "0\r\n" +
  19984. within_cap_name + ": a\r\n" + past_cap_name +
  19985. ": b\r\n"
  19986. "\r\n";
  19987. std::string res;
  19988. ASSERT_TRUE(send_request(1, req, &res, port));
  19989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19990. // A name within the cap is honored; one declared past the cap is dropped.
  19991. EXPECT_TRUE(observed_within_cap);
  19992. EXPECT_FALSE(observed_past_cap);
  19993. }
  19994. // A direct client that is not listed in trusted_proxies must not be able to
  19995. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19996. // the peer address on the actual TCP connection determines whether the
  19997. // header is honored.
  19998. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19999. Server svr;
  20000. // Deliberately does NOT include the loopback address the test client
  20001. // actually connects from, so the direct connection is not a trusted proxy.
  20002. svr.set_trusted_proxies({"203.0.113.66"});
  20003. std::string observed_remote_addr;
  20004. svr.Get("/ip", [&](const Request &req, Response &res) {
  20005. observed_remote_addr = req.remote_addr;
  20006. res.set_content("ok", "text/plain");
  20007. });
  20008. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20009. auto se = detail::scope_exit([&] {
  20010. svr.stop();
  20011. t.join();
  20012. ASSERT_FALSE(svr.is_running());
  20013. });
  20014. svr.wait_until_ready();
  20015. Client cli(HOST, PORT);
  20016. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20018. EXPECT_EQ(StatusCode::OK_200, res->status);
  20019. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20020. // ignored entirely and the real connection-level address retained.
  20021. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20022. observed_remote_addr == "127.0.0.1");
  20023. }
  20024. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20025. Server svr;
  20026. std::string observed_remote_addr;
  20027. std::string observed_xff;
  20028. svr.Get("/ip", [&](const Request &req, Response &res) {
  20029. observed_remote_addr = req.remote_addr;
  20030. observed_xff = req.get_header_value("X-Forwarded-For");
  20031. res.set_content("ok", "text/plain");
  20032. });
  20033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20034. auto se = detail::scope_exit([&] {
  20035. svr.stop();
  20036. t.join();
  20037. ASSERT_FALSE(svr.is_running());
  20038. });
  20039. svr.wait_until_ready();
  20040. Client cli(HOST, PORT);
  20041. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20043. EXPECT_EQ(StatusCode::OK_200, res->status);
  20044. EXPECT_EQ(observed_xff, "203.0.113.66");
  20045. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20046. observed_remote_addr == "127.0.0.1");
  20047. }
  20048. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20049. Server svr;
  20050. svr.set_trusted_proxies({"203.0.113.66"});
  20051. std::string observed_remote_addr;
  20052. std::string observed_xff;
  20053. svr.Get("/ip", [&](const Request &req, Response &res) {
  20054. observed_remote_addr = req.remote_addr;
  20055. observed_xff = req.get_header_value("X-Forwarded-For");
  20056. res.set_content("ok", "text/plain");
  20057. });
  20058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20059. auto se = detail::scope_exit([&] {
  20060. svr.stop();
  20061. t.join();
  20062. ASSERT_FALSE(svr.is_running());
  20063. });
  20064. svr.wait_until_ready();
  20065. Client cli(HOST, PORT);
  20066. auto res = cli.Get("/ip");
  20067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20068. EXPECT_EQ(StatusCode::OK_200, res->status);
  20069. EXPECT_EQ(observed_xff, "");
  20070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20071. observed_remote_addr == "127.0.0.1");
  20072. }
  20073. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20074. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20075. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20076. Server svr;
  20077. svr.set_trusted_proxies({"127.0.0.1"});
  20078. svr.Get("/ip", [](const Request &req, Response &res) {
  20079. res.set_content(req.remote_addr, "text/plain");
  20080. });
  20081. auto port = svr.bind_to_any_port("::");
  20082. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20083. thread t = thread([&] { svr.listen_after_bind(); });
  20084. auto se = detail::scope_exit([&] {
  20085. svr.stop();
  20086. t.join();
  20087. ASSERT_FALSE(svr.is_running());
  20088. });
  20089. svr.wait_until_ready();
  20090. Client cli("127.0.0.1", port);
  20091. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20093. EXPECT_EQ("198.51.100.23", res->body);
  20094. }
  20095. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20096. Server svr;
  20097. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20098. svr.Get("/ip", [](const Request &req, Response &res) {
  20099. res.set_content(req.remote_addr, "text/plain");
  20100. });
  20101. auto port = svr.bind_to_any_port(HOST);
  20102. ASSERT_GT(port, 0);
  20103. thread t = thread([&] { svr.listen_after_bind(); });
  20104. auto se = detail::scope_exit([&] {
  20105. svr.stop();
  20106. t.join();
  20107. ASSERT_FALSE(svr.is_running());
  20108. });
  20109. svr.wait_until_ready();
  20110. Client cli(HOST, port);
  20111. auto res = cli.Get(
  20112. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20114. EXPECT_EQ("198.51.100.23", res->body);
  20115. }
  20116. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20117. Server svr;
  20118. // Include the loopback address the test client actually connects from, so
  20119. // the direct connection itself is recognized as the trusted proxy hop.
  20120. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20121. std::string observed_remote_addr;
  20122. std::string observed_xff;
  20123. svr.Get("/ip", [&](const Request &req, Response &res) {
  20124. observed_remote_addr = req.remote_addr;
  20125. observed_xff = req.get_header_value("X-Forwarded-For");
  20126. res.set_content("ok", "text/plain");
  20127. });
  20128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20129. auto se = detail::scope_exit([&] {
  20130. svr.stop();
  20131. t.join();
  20132. ASSERT_FALSE(svr.is_running());
  20133. });
  20134. svr.wait_until_ready();
  20135. Client cli(HOST, PORT);
  20136. auto res = cli.Get(
  20137. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20139. EXPECT_EQ(StatusCode::OK_200, res->status);
  20140. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20141. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20142. }
  20143. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20144. Server svr;
  20145. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20146. std::string observed_remote_addr;
  20147. std::string observed_xff;
  20148. svr.Get("/ip", [&](const Request &req, Response &res) {
  20149. observed_remote_addr = req.remote_addr;
  20150. observed_xff = req.get_header_value("X-Forwarded-For");
  20151. res.set_content("ok", "text/plain");
  20152. });
  20153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20154. auto se = detail::scope_exit([&] {
  20155. svr.stop();
  20156. t.join();
  20157. ASSERT_FALSE(svr.is_running());
  20158. });
  20159. svr.wait_until_ready();
  20160. Client cli(HOST, PORT);
  20161. auto res = cli.Get(
  20162. "/ip",
  20163. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20165. EXPECT_EQ(StatusCode::OK_200, res->status);
  20166. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20167. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20168. }
  20169. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20170. Server svr;
  20171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20172. std::string observed_remote_addr;
  20173. std::string observed_xff;
  20174. svr.Get("/ip", [&](const Request &req, Response &res) {
  20175. observed_remote_addr = req.remote_addr;
  20176. observed_xff = req.get_header_value("X-Forwarded-For");
  20177. res.set_content("ok", "text/plain");
  20178. });
  20179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20180. auto se = detail::scope_exit([&] {
  20181. svr.stop();
  20182. t.join();
  20183. ASSERT_FALSE(svr.is_running());
  20184. });
  20185. svr.wait_until_ready();
  20186. Client cli(HOST, PORT);
  20187. auto res = cli.Get(
  20188. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20190. EXPECT_EQ(StatusCode::OK_200, res->status);
  20191. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20192. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20193. // and must not be selected.
  20194. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20195. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20196. }
  20197. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20198. Server svr;
  20199. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20200. std::string observed_remote_addr;
  20201. svr.Get("/ip", [&](const Request &req, Response &res) {
  20202. observed_remote_addr = req.remote_addr;
  20203. res.set_content("ok", "text/plain");
  20204. });
  20205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20206. auto se = detail::scope_exit([&] {
  20207. svr.stop();
  20208. t.join();
  20209. ASSERT_FALSE(svr.is_running());
  20210. });
  20211. svr.wait_until_ready();
  20212. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20213. // a forged address and the trusted proxy's own address; the forged value must
  20214. // not win over the address the trusted proxy actually recorded.
  20215. Client cli(HOST, PORT);
  20216. auto res = cli.Get(
  20217. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20219. EXPECT_EQ(StatusCode::OK_200, res->status);
  20220. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20221. }
  20222. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20223. Server svr;
  20224. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20225. std::string observed_remote_addr;
  20226. std::string observed_xff;
  20227. svr.Get("/ip", [&](const Request &req, Response &res) {
  20228. observed_remote_addr = req.remote_addr;
  20229. observed_xff = req.get_header_value("X-Forwarded-For");
  20230. res.set_content("ok", "text/plain");
  20231. });
  20232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20233. auto se = detail::scope_exit([&] {
  20234. svr.stop();
  20235. t.join();
  20236. ASSERT_FALSE(svr.is_running());
  20237. });
  20238. svr.wait_until_ready();
  20239. Client cli(HOST, PORT);
  20240. auto res = cli.Get(
  20241. "/ip",
  20242. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20244. EXPECT_EQ(StatusCode::OK_200, res->status);
  20245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20246. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20247. }
  20248. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20249. Server svr;
  20250. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20251. std::string observed_remote_addr;
  20252. std::string observed_xff;
  20253. svr.Get("/ip", [&](const Request &req, Response &res) {
  20254. observed_remote_addr = req.remote_addr;
  20255. observed_xff = req.get_header_value("X-Forwarded-For");
  20256. res.set_content("ok", "text/plain");
  20257. });
  20258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20259. auto se = detail::scope_exit([&] {
  20260. svr.stop();
  20261. t.join();
  20262. ASSERT_FALSE(svr.is_running());
  20263. });
  20264. svr.wait_until_ready();
  20265. std::string raw_req =
  20266. "GET /ip HTTP/1.1\r\n"
  20267. "Host: localhost\r\n"
  20268. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20269. "Connection: close\r\n"
  20270. "\r\n";
  20271. std::string out;
  20272. ASSERT_TRUE(send_request(5, raw_req, &out));
  20273. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20274. // Header parser trims surrounding whitespace of the header value
  20275. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20276. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20277. }
  20278. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20279. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20280. // their own X-Forwarded-For as a separate field line rather than extending the
  20281. // one the client sent, so every occurrence has to be taken into account.
  20282. // Reading only the first one hands back the address the client chose.
  20283. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20284. Server svr;
  20285. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20286. std::string observed_remote_addr;
  20287. size_t observed_xff_count = 0;
  20288. svr.Get("/ip", [&](const Request &req, Response &res) {
  20289. observed_remote_addr = req.remote_addr;
  20290. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20291. res.set_content("ok", "text/plain");
  20292. });
  20293. auto port = svr.bind_to_any_port(HOST);
  20294. thread t = thread([&]() { svr.listen_after_bind(); });
  20295. auto se = detail::scope_exit([&] {
  20296. svr.stop();
  20297. t.join();
  20298. ASSERT_FALSE(svr.is_running());
  20299. });
  20300. svr.wait_until_ready();
  20301. // The client supplies the first field line; the trusted proxy appends the
  20302. // address it observed as a second one.
  20303. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20304. "Host: localhost\r\n"
  20305. "X-Forwarded-For: 1.2.3.4\r\n"
  20306. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20307. "Connection: close\r\n"
  20308. "\r\n";
  20309. std::string out;
  20310. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20312. EXPECT_EQ(observed_xff_count, 2U);
  20313. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20314. // The same chain spread over one field line per hop derives the same client
  20315. // address, i.e. the split and the comma-joined representations agree.
  20316. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20317. "Host: localhost\r\n"
  20318. "X-Forwarded-For: 1.2.3.4\r\n"
  20319. "X-Forwarded-For: 198.51.100.23\r\n"
  20320. "X-Forwarded-For: 192.0.2.45\r\n"
  20321. "Connection: close\r\n"
  20322. "\r\n";
  20323. out.clear();
  20324. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20325. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20326. EXPECT_EQ(observed_xff_count, 3U);
  20327. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20328. }
  20329. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20330. // crash the server (it used to call front() on an empty vector inside
  20331. // get_client_ip). The connection-level remote address must be retained instead.
  20332. static void run_malformed_xff_test(const std::string &xff_value) {
  20333. Server svr;
  20334. svr.set_trusted_proxies({"192.0.2.45"});
  20335. std::string observed_remote_addr;
  20336. svr.Get("/ip", [&](const Request &req, Response &res) {
  20337. observed_remote_addr = req.remote_addr;
  20338. res.set_content("ok", "text/plain");
  20339. });
  20340. int port = 0;
  20341. thread t = thread([&]() {
  20342. port = svr.bind_to_any_port(HOST);
  20343. svr.listen_after_bind();
  20344. });
  20345. auto se = detail::scope_exit([&] {
  20346. svr.stop();
  20347. t.join();
  20348. ASSERT_FALSE(svr.is_running());
  20349. });
  20350. svr.wait_until_ready();
  20351. Client cli(HOST, port);
  20352. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20354. EXPECT_EQ(StatusCode::OK_200, res->status);
  20355. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20356. observed_remote_addr == "127.0.0.1");
  20357. }
  20358. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20359. run_malformed_xff_test("");
  20360. }
  20361. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20362. run_malformed_xff_test(",");
  20363. }
  20364. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20365. run_malformed_xff_test(", , ,");
  20366. }
  20367. // The same rule applies to Accept: a request whose acceptable types are spread
  20368. // over several field lines must be negotiated against all of them.
  20369. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20370. // case-insensitive connection options. Comparing the whole field value against
  20371. // one option misses a client that sends several of them, and misses every
  20372. // casing but the one written in the comparison.
  20373. //
  20374. // Sends req, reads the response, then reuses the same socket for a second
  20375. // request to find out whether the server kept the connection.
  20376. static void probe_connection_reuse(int port, const std::string &req,
  20377. bool *announced_close, bool *reusable) {
  20378. auto error = Error::Success;
  20379. auto sock = detail::create_client_socket(
  20380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20381. /*connection_timeout_sec=*/5, 0,
  20382. /*read_timeout_sec=*/1, 0,
  20383. /*write_timeout_sec=*/5, 0, std::string(), error);
  20384. ASSERT_NE(sock, INVALID_SOCKET);
  20385. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20386. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20387. "Host: localhost\r\n"
  20388. "Connection: close\r\n"
  20389. "\r\n";
  20390. std::string first_response;
  20391. std::string second_response;
  20392. detail::process_client_socket(
  20393. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20394. [&](Stream &strm) {
  20395. if (strm.write(req.data(), req.size()) !=
  20396. static_cast<ssize_t>(req.size())) {
  20397. return false;
  20398. }
  20399. char buf[512];
  20400. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20401. // Headers plus the two-byte body of the handler below
  20402. while (reader.getline()) {
  20403. first_response += reader.ptr();
  20404. if (first_response.find("ok") != std::string::npos) { break; }
  20405. }
  20406. if (strm.write(second.data(), second.size()) !=
  20407. static_cast<ssize_t>(second.size())) {
  20408. return true;
  20409. }
  20410. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20411. while (reader2.getline()) {
  20412. second_response += reader2.ptr();
  20413. if (second_response.find("ok") != std::string::npos) { break; }
  20414. }
  20415. return true;
  20416. });
  20417. *announced_close =
  20418. first_response.find("Connection: close") != std::string::npos;
  20419. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20420. }
  20421. class ConnectionTokenTest : public ::testing::Test {
  20422. protected:
  20423. void SetUp() override {
  20424. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20425. res.set_content("ok", "text/plain");
  20426. });
  20427. port_ = svr_.bind_to_any_port(HOST);
  20428. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20429. svr_.wait_until_ready();
  20430. }
  20431. void TearDown() override {
  20432. svr_.stop();
  20433. if (thread_.joinable()) { thread_.join(); }
  20434. }
  20435. Server svr_;
  20436. int port_ = 0;
  20437. thread thread_;
  20438. };
  20439. // "close" alongside another option still closes the connection, and the
  20440. // response says so rather than leaving the peer to discover it.
  20441. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20442. bool announced_close = false;
  20443. bool reusable = true;
  20444. probe_connection_reuse(port_,
  20445. "GET /keepalive HTTP/1.1\r\n"
  20446. "Host: localhost\r\n"
  20447. "Connection: keep-alive, close\r\n"
  20448. "\r\n",
  20449. &announced_close, &reusable);
  20450. EXPECT_TRUE(announced_close);
  20451. EXPECT_FALSE(reusable);
  20452. }
  20453. // "close" split over two field lines is the same list, so it is honored too.
  20454. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20455. bool announced_close = false;
  20456. bool reusable = true;
  20457. probe_connection_reuse(port_,
  20458. "GET /keepalive HTTP/1.1\r\n"
  20459. "Host: localhost\r\n"
  20460. "Connection: keep-alive\r\n"
  20461. "Connection: close\r\n"
  20462. "\r\n",
  20463. &announced_close, &reusable);
  20464. EXPECT_TRUE(announced_close);
  20465. EXPECT_FALSE(reusable);
  20466. }
  20467. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20468. // keep-alive in the spelling everyone actually sends keeps its connection.
  20469. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20470. bool announced_close = false;
  20471. bool reusable = false;
  20472. probe_connection_reuse(port_,
  20473. "GET /keepalive HTTP/1.0\r\n"
  20474. "Host: localhost\r\n"
  20475. "Connection: keep-alive\r\n"
  20476. "\r\n",
  20477. &announced_close, &reusable);
  20478. EXPECT_FALSE(announced_close);
  20479. EXPECT_TRUE(reusable);
  20480. }
  20481. // A token the value merely contains is not the token itself.
  20482. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20483. bool announced_close = false;
  20484. bool reusable = false;
  20485. probe_connection_reuse(port_,
  20486. "GET /keepalive HTTP/1.1\r\n"
  20487. "Host: localhost\r\n"
  20488. "Connection: notclose\r\n"
  20489. "\r\n",
  20490. &announced_close, &reusable);
  20491. EXPECT_FALSE(announced_close);
  20492. EXPECT_TRUE(reusable);
  20493. }
  20494. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20495. Server svr;
  20496. std::vector<std::string> observed_types;
  20497. svr.Get("/", [&](const Request &req, Response &res) {
  20498. observed_types = req.accept_content_types;
  20499. res.set_content("ok", "text/plain");
  20500. });
  20501. auto port = svr.bind_to_any_port(HOST);
  20502. thread t = thread([&]() { svr.listen_after_bind(); });
  20503. auto se = detail::scope_exit([&] {
  20504. svr.stop();
  20505. t.join();
  20506. ASSERT_FALSE(svr.is_running());
  20507. });
  20508. svr.wait_until_ready();
  20509. Client cli(HOST, port);
  20510. Headers headers;
  20511. headers.emplace("Accept", "text/plain;q=0.5");
  20512. headers.emplace("Accept", "application/json");
  20513. auto res = cli.Get("/", headers);
  20514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20515. EXPECT_EQ(StatusCode::OK_200, res->status);
  20516. // Sorted by q-value, so the second field line's type comes first
  20517. ASSERT_EQ(2U, observed_types.size());
  20518. EXPECT_EQ("application/json", observed_types[0]);
  20519. EXPECT_EQ("text/plain", observed_types[1]);
  20520. }
  20521. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20522. // empty field line must not contribute a bare comma to the combined value.
  20523. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20524. Server svr;
  20525. std::vector<std::string> observed_types;
  20526. svr.Get("/", [&](const Request &req, Response &res) {
  20527. observed_types = req.accept_content_types;
  20528. res.set_content("ok", "text/plain");
  20529. });
  20530. auto port = svr.bind_to_any_port(HOST);
  20531. thread t = thread([&]() { svr.listen_after_bind(); });
  20532. auto se = detail::scope_exit([&] {
  20533. svr.stop();
  20534. t.join();
  20535. ASSERT_FALSE(svr.is_running());
  20536. });
  20537. svr.wait_until_ready();
  20538. // Empty first field line, then a real one
  20539. std::string raw_req = "GET / HTTP/1.1\r\n"
  20540. "Host: localhost\r\n"
  20541. "Accept:\r\n"
  20542. "Accept: application/json\r\n"
  20543. "Connection: close\r\n"
  20544. "\r\n";
  20545. std::string out;
  20546. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20548. ASSERT_EQ(1U, observed_types.size());
  20549. EXPECT_EQ("application/json", observed_types[0]);
  20550. }
  20551. // The skip in get_combined_header_value() is what keeps an empty field line
  20552. // from contributing a bare comma. Only a trailing empty field line exercises
  20553. // it: a leading one is already covered by the "combined is still empty" check,
  20554. // and parse_accept_header() now ignores the empty element either way, so the
  20555. // request-level test above can no longer tell the two apart.
  20556. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20557. Headers headers;
  20558. headers.emplace("Accept", "text/html");
  20559. headers.emplace("Accept", "");
  20560. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20561. headers.clear();
  20562. headers.emplace("Accept", "");
  20563. headers.emplace("Accept", "application/json");
  20564. EXPECT_EQ("application/json",
  20565. detail::get_combined_header_value(headers, "Accept"));
  20566. }
  20567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20568. // An encoding offered on a later Accept-Encoding field line is still offered.
  20569. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20570. Server svr;
  20571. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20572. res.set_content(std::string(1024, 'x'), "text/plain");
  20573. });
  20574. auto port = svr.bind_to_any_port(HOST);
  20575. thread t = thread([&]() { svr.listen_after_bind(); });
  20576. auto se = detail::scope_exit([&] {
  20577. svr.stop();
  20578. t.join();
  20579. ASSERT_FALSE(svr.is_running());
  20580. });
  20581. svr.wait_until_ready();
  20582. Client cli(HOST, port);
  20583. cli.set_decompress(false);
  20584. Headers headers;
  20585. headers.emplace("Accept-Encoding", "identity");
  20586. headers.emplace("Accept-Encoding", "gzip");
  20587. auto res = cli.Get("/", headers);
  20588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20589. EXPECT_EQ(StatusCode::OK_200, res->status);
  20590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20591. }
  20592. #endif
  20593. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20594. // Transfer-Encoding is not its body.
  20595. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20596. Server svr;
  20597. svr.set_payload_max_length(8);
  20598. svr.Post("/test", [](const Request &, Response &res) {
  20599. res.set_content("ok", "text/plain");
  20600. });
  20601. auto port = svr.bind_to_any_port(HOST);
  20602. ASSERT_GT(port, 0);
  20603. thread t = thread([&] { svr.listen_after_bind(); });
  20604. auto se = detail::scope_exit([&] {
  20605. svr.stop();
  20606. t.join();
  20607. ASSERT_FALSE(svr.is_running());
  20608. });
  20609. svr.wait_until_ready();
  20610. std::string resp;
  20611. ASSERT_TRUE(send_request(1,
  20612. "POST /test HTTP/1.1\r\n"
  20613. "Host: localhost\r\n"
  20614. "Connection: close\r\n"
  20615. "\r\n" +
  20616. std::string(16, 'X'),
  20617. &resp, port));
  20618. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20619. }
  20620. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20621. Server svr;
  20622. svr.Post("/post", [&](const Request &req, Response &res) {
  20623. res.set_content(req.body, "text/plain");
  20624. });
  20625. svr.Put("/put", [&](const Request &req, Response &res) {
  20626. res.set_content(req.body, "text/plain");
  20627. });
  20628. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20629. res.set_content(req.body, "text/plain");
  20630. });
  20631. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20632. res.set_content(req.body, "text/plain");
  20633. });
  20634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20635. auto se = detail::scope_exit([&] {
  20636. svr.stop();
  20637. t.join();
  20638. ASSERT_FALSE(svr.is_running());
  20639. });
  20640. svr.wait_until_ready();
  20641. std::string resp;
  20642. // POST without Content-Length
  20643. ASSERT_TRUE(send_request(5,
  20644. "POST /post HTTP/1.1\r\n"
  20645. "Host: localhost\r\n"
  20646. "Connection: close\r\n"
  20647. "\r\n",
  20648. &resp));
  20649. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20650. // PUT without Content-Length
  20651. resp.clear();
  20652. ASSERT_TRUE(send_request(5,
  20653. "PUT /put HTTP/1.1\r\n"
  20654. "Host: localhost\r\n"
  20655. "Connection: close\r\n"
  20656. "\r\n",
  20657. &resp));
  20658. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20659. // PATCH without Content-Length
  20660. resp.clear();
  20661. ASSERT_TRUE(send_request(5,
  20662. "PATCH /patch HTTP/1.1\r\n"
  20663. "Host: localhost\r\n"
  20664. "Connection: close\r\n"
  20665. "\r\n",
  20666. &resp));
  20667. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20668. // DELETE without Content-Length
  20669. resp.clear();
  20670. ASSERT_TRUE(send_request(5,
  20671. "DELETE /delete HTTP/1.1\r\n"
  20672. "Host: localhost\r\n"
  20673. "Connection: close\r\n"
  20674. "\r\n",
  20675. &resp));
  20676. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20677. }
  20678. //==============================================================================
  20679. // open_stream() Tests
  20680. //==============================================================================
  20681. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20682. std::string result;
  20683. char buf[8192];
  20684. ssize_t n;
  20685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20686. result.append(buf, static_cast<size_t>(n));
  20687. }
  20688. return result;
  20689. }
  20690. // Mock stream for unit tests
  20691. class MockStream : public Stream {
  20692. public:
  20693. std::string data;
  20694. size_t pos = 0;
  20695. ssize_t error_after = -1; // -1 = no error
  20696. explicit MockStream(const std::string &d, ssize_t err = -1)
  20697. : data(d), error_after(err) {}
  20698. bool is_readable() const override { return true; }
  20699. bool wait_readable() const override { return true; }
  20700. bool wait_writable() const override { return true; }
  20701. ssize_t read(char *ptr, size_t size) override {
  20702. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20703. if (pos >= data.size()) return 0;
  20704. size_t limit =
  20705. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20706. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20707. std::memcpy(ptr, data.data() + pos, to_read);
  20708. pos += to_read;
  20709. return static_cast<ssize_t>(to_read);
  20710. }
  20711. ssize_t write(const char *, size_t) override { return -1; }
  20712. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20713. ip = "127.0.0.1";
  20714. port = 0;
  20715. }
  20716. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20717. ip = "127.0.0.1";
  20718. port = 0;
  20719. }
  20720. socket_t socket() const override { return INVALID_SOCKET; }
  20721. time_t duration() const override { return 0; }
  20722. };
  20723. TEST(StreamHandleTest, Basic) {
  20724. ClientImpl::StreamHandle handle;
  20725. EXPECT_FALSE(handle.is_valid());
  20726. handle.response = detail::make_unique<Response>();
  20727. handle.error = Error::Connection;
  20728. EXPECT_FALSE(handle.is_valid());
  20729. handle.error = Error::Success;
  20730. EXPECT_TRUE(handle.is_valid());
  20731. }
  20732. TEST(BodyReaderTest, Basic) {
  20733. MockStream stream("Hello, World!");
  20734. detail::BodyReader reader;
  20735. reader.stream = &stream;
  20736. reader.content_length = 13;
  20737. char buf[32];
  20738. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20739. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20740. EXPECT_TRUE(reader.eof);
  20741. }
  20742. TEST(BodyReaderTest, NoStream) {
  20743. detail::BodyReader reader;
  20744. char buf[32];
  20745. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20746. EXPECT_EQ(Error::Connection, reader.last_error);
  20747. }
  20748. TEST(BodyReaderTest, Error) {
  20749. MockStream stream("Hello, World!", 5);
  20750. detail::BodyReader reader;
  20751. reader.stream = &stream;
  20752. reader.content_length = 13;
  20753. char buf[32];
  20754. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20755. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20756. EXPECT_EQ(Error::Read, reader.last_error);
  20757. }
  20758. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20759. // Mock-based StreamHandle tests relying on private internals are removed.
  20760. class OpenStreamTest : public ::testing::Test {
  20761. protected:
  20762. void SetUp() override {
  20763. svr_.Get("/hello", [](const Request &, Response &res) {
  20764. res.set_content("Hello World!", "text/plain");
  20765. });
  20766. svr_.Get("/large", [](const Request &, Response &res) {
  20767. res.set_content(std::string(10000, 'X'), "text/plain");
  20768. });
  20769. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20770. res.set_content("Hello World!", "image/jpeg");
  20771. res.set_header("Content-Encoding", "UTF-8");
  20772. });
  20773. svr_.Get("/chunked", [](const Request &, Response &res) {
  20774. res.set_chunked_content_provider("text/plain",
  20775. [](size_t offset, DataSink &sink) {
  20776. if (offset < 15) {
  20777. sink.write("chunk", 5);
  20778. return true;
  20779. }
  20780. sink.done();
  20781. return true;
  20782. });
  20783. });
  20784. svr_.Get("/compressible", [](const Request &, Response &res) {
  20785. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20786. DataSink &sink) {
  20787. if (offset < 100 * 1024) {
  20788. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20789. sink.write(chunk.data(), chunk.size());
  20790. return true;
  20791. }
  20792. sink.done();
  20793. return true;
  20794. });
  20795. });
  20796. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20797. [](const Request & /*req*/, Response &res) {
  20798. auto i = new int(0);
  20799. res.set_header("Trailer", "Content-Length, X-Allowed");
  20800. res.set_chunked_content_provider(
  20801. "text/plain",
  20802. [i](size_t /*offset*/, DataSink &sink) {
  20803. switch (*i) {
  20804. case 0: sink.os << "123"; break;
  20805. case 1: sink.os << "456"; break;
  20806. case 2: sink.os << "789"; break;
  20807. case 3: {
  20808. sink.done_with_trailer(
  20809. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20810. } break;
  20811. }
  20812. (*i)++;
  20813. return true;
  20814. },
  20815. [i](bool success) {
  20816. EXPECT_TRUE(success);
  20817. delete i;
  20818. });
  20819. });
  20820. // Echo headers endpoint for header-related tests
  20821. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20822. std::string body;
  20823. for (const auto &h : req.headers) {
  20824. body.append(h.first);
  20825. body.push_back(':');
  20826. body.append(h.second);
  20827. body.push_back('\n');
  20828. }
  20829. res.set_content(body, "text/plain");
  20830. });
  20831. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20832. std::string body;
  20833. for (const auto &h : req.headers) {
  20834. body.append(h.first);
  20835. body.push_back(':');
  20836. body.append(h.second);
  20837. body.push_back('\n');
  20838. }
  20839. res.set_content(body, "text/plain");
  20840. });
  20841. port_ = svr_.bind_to_any_port("127.0.0.1");
  20842. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20843. svr_.wait_until_ready();
  20844. }
  20845. void TearDown() override {
  20846. svr_.stop();
  20847. if (thread_.joinable()) thread_.join();
  20848. }
  20849. Server svr_;
  20850. std::thread thread_;
  20851. int port_ = 0;
  20852. };
  20853. TEST_F(OpenStreamTest, Basic) {
  20854. Client cli("127.0.0.1", port_);
  20855. auto handle = cli.open_stream("GET", "/hello");
  20856. EXPECT_TRUE(handle.is_valid());
  20857. EXPECT_EQ("Hello World!", read_all(handle));
  20858. }
  20859. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20860. Client cli("127.0.0.1", port_);
  20861. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20862. ASSERT_TRUE(handle.is_valid());
  20863. EXPECT_EQ("Hello World!", read_all(handle));
  20864. }
  20865. TEST_F(OpenStreamTest, SmallBuffer) {
  20866. Client cli("127.0.0.1", port_);
  20867. auto handle = cli.open_stream("GET", "/hello");
  20868. std::string result;
  20869. char buf[4];
  20870. ssize_t n;
  20871. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20872. result.append(buf, static_cast<size_t>(n));
  20873. EXPECT_EQ("Hello World!", result);
  20874. }
  20875. TEST_F(OpenStreamTest, DefaultHeaders) {
  20876. Client cli("127.0.0.1", port_);
  20877. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20878. {
  20879. auto handle = cli.open_stream("GET", "/echo-headers");
  20880. ASSERT_TRUE(handle.is_valid());
  20881. auto body = read_all(handle);
  20882. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20883. std::string::npos);
  20884. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20885. std::string::npos);
  20886. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20887. }
  20888. // open_stream POST with body and no explicit content_type should NOT add
  20889. // text/plain Content-Type (behavior differs from non-streaming path), but
  20890. // should include Content-Length
  20891. {
  20892. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20893. ASSERT_TRUE(handle.is_valid());
  20894. auto body = read_all(handle);
  20895. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20896. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20897. }
  20898. // open_stream POST with explicit Content-Type should preserve it
  20899. {
  20900. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20901. {{"Content-Type", "application/custom"}},
  20902. "{}", "application/custom");
  20903. ASSERT_TRUE(handle.is_valid());
  20904. auto body = read_all(handle);
  20905. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20906. }
  20907. // User-specified User-Agent must not be overwritten for stream API
  20908. {
  20909. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20910. {{"User-Agent", "MyAgent/1.2"}});
  20911. ASSERT_TRUE(handle.is_valid());
  20912. auto body = read_all(handle);
  20913. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20914. }
  20915. }
  20916. TEST_F(OpenStreamTest, Large) {
  20917. Client cli("127.0.0.1", port_);
  20918. auto handle = cli.open_stream("GET", "/large");
  20919. EXPECT_EQ(10000u, read_all(handle).size());
  20920. }
  20921. TEST_F(OpenStreamTest, ConnectionError) {
  20922. Client cli("127.0.0.1", 9999);
  20923. auto handle = cli.open_stream("GET", "/hello");
  20924. EXPECT_FALSE(handle.is_valid());
  20925. }
  20926. TEST_F(OpenStreamTest, Chunked) {
  20927. Client cli("127.0.0.1", port_);
  20928. auto handle = cli.open_stream("GET", "/chunked");
  20929. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20930. "Transfer-Encoding") == "chunked");
  20931. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20932. }
  20933. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20934. Client cli("127.0.0.1", port_);
  20935. auto handle =
  20936. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20937. ASSERT_TRUE(handle.is_valid());
  20938. // Consume body to allow trailers to be received/parsed
  20939. auto body = read_all(handle);
  20940. // Explicitly parse trailers (ensure trailers are available for assertion)
  20941. handle.parse_trailers_if_needed();
  20942. EXPECT_EQ(std::string("123456789"), body);
  20943. // The response should include a Trailer header declaring both names
  20944. ASSERT_TRUE(handle.response);
  20945. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20946. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20947. handle.response->get_header_value("Trailer"));
  20948. // Prohibited trailer must not be present
  20949. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20950. // Allowed trailer should be present
  20951. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20952. EXPECT_EQ(std::string("yes"),
  20953. handle.response->get_trailer_value("X-Allowed"));
  20954. // Verify trailers are NOT present as regular headers
  20955. EXPECT_EQ(std::string(""),
  20956. handle.response->get_header_value("Content-Length"));
  20957. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20958. }
  20959. // Accepts one connection on an OS-assigned port, which it hands over through
  20960. // port_promise, reads the request head and sends back response. after_send,
  20961. // if given, runs on the connection before it is closed.
  20962. static std::thread
  20963. serve_single_response(std::promise<int> &port_promise,
  20964. const std::string &response,
  20965. std::function<void(socket_t)> after_send = nullptr) {
  20966. return std::thread([&port_promise, response, after_send] {
  20967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20968. default_socket_options(srv);
  20969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20971. sockaddr_in addr{};
  20972. addr.sin_family = AF_INET;
  20973. addr.sin_port = htons(0); // Let OS assign a free port
  20974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20975. int opt = 1;
  20976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20977. #ifdef _WIN32
  20978. reinterpret_cast<const char *>(&opt),
  20979. #else
  20980. &opt,
  20981. #endif
  20982. sizeof(opt));
  20983. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20984. ::listen(srv, 1) != 0) {
  20985. port_promise.set_value(-1);
  20986. detail::close_socket(srv);
  20987. return;
  20988. }
  20989. socklen_t addr_len = sizeof(addr);
  20990. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20991. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20992. sockaddr_in cli_addr{};
  20993. socklen_t cli_len = sizeof(cli_addr);
  20994. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20995. if (cli != INVALID_SOCKET) {
  20996. // Read the complete HTTP request (until the blank line that terminates
  20997. // headers) before sending the response. If the server closes the socket
  20998. // while the client's request data is still unread in the kernel receive
  20999. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21000. // connection on both sides: it discards the client's receive buffer
  21001. // (which already holds our response) and causes any in-progress write on
  21002. // the client to fail with ECONNRESET. Reading all request data first
  21003. // ensures close() emits a graceful FIN.
  21004. {
  21005. char rbuf[256];
  21006. std::string req;
  21007. while (req.find("\r\n\r\n") == std::string::npos) {
  21008. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21009. if (n <= 0) { break; }
  21010. req.append(rbuf, static_cast<size_t>(n));
  21011. }
  21012. }
  21013. ::send(cli,
  21014. #ifdef _WIN32
  21015. static_cast<const char *>(response.c_str()),
  21016. static_cast<int>(response.size()),
  21017. #else
  21018. response.c_str(), response.size(),
  21019. #endif
  21020. 0);
  21021. if (after_send) { after_send(cli); }
  21022. detail::close_socket(cli);
  21023. }
  21024. detail::close_socket(srv);
  21025. });
  21026. }
  21027. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21028. #ifndef _WIN32
  21029. signal(SIGPIPE, SIG_IGN);
  21030. #endif
  21031. std::promise<int> port_promise;
  21032. auto port_future = port_promise.get_future();
  21033. auto server_thread =
  21034. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21035. "Content-Type: text/plain\r\n"
  21036. "Content-Length: not-a-number\r\n"
  21037. "Connection: close\r\n"
  21038. "\r\n"
  21039. "hello");
  21040. auto port = port_future.get();
  21041. ASSERT_GT(port, 0);
  21042. Client cli("127.0.0.1", port);
  21043. auto handle = cli.open_stream("GET", "/");
  21044. EXPECT_FALSE(handle.is_valid());
  21045. server_thread.join();
  21046. }
  21047. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21048. #ifndef _WIN32
  21049. signal(SIGPIPE, SIG_IGN);
  21050. #endif
  21051. std::promise<int> port_promise;
  21052. auto port_future = port_promise.get_future();
  21053. auto server_thread = serve_single_response(
  21054. port_promise, "HTTP/1.1 200 OK\r\n"
  21055. "Content-Type: text/plain\r\n"
  21056. "Content-Length: 99999999999999999999999999\r\n"
  21057. "Connection: close\r\n"
  21058. "\r\n"
  21059. "hello");
  21060. auto port = port_future.get();
  21061. ASSERT_GT(port, 0);
  21062. // Historically std::stoull would throw std::out_of_range here and crash
  21063. // the process, then parsing silently clamped to a bogus framing length and
  21064. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21065. // so the stream fails to open, matching the not-a-number case above. The
  21066. // process still must NOT terminate.
  21067. Client cli("127.0.0.1", port);
  21068. auto handle = cli.open_stream("GET", "/");
  21069. EXPECT_FALSE(handle.is_valid());
  21070. server_thread.join();
  21071. }
  21072. #ifndef _WIN32
  21073. // As above for the body of a streamed request: a send() cut short by the write
  21074. // timeout must not leave the rest of the body unsent.
  21075. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21076. signal(SIGPIPE, SIG_IGN);
  21077. Server svr;
  21078. svr.set_socket_options([](socket_t sock) {
  21079. int size = 8192;
  21080. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21081. reinterpret_cast<const char *>(&size), sizeof(size));
  21082. });
  21083. svr.Post("/size", [](const Request &, Response &res,
  21084. const ContentReader &content_reader) {
  21085. // Outlast the client's write timeout before reading the body.
  21086. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21087. size_t received = 0;
  21088. content_reader([&](const char *, size_t len) {
  21089. received += len;
  21090. return true;
  21091. });
  21092. res.set_content(std::to_string(received), "text/plain");
  21093. });
  21094. auto port = svr.bind_to_any_port(HOST);
  21095. std::thread t([&]() { svr.listen_after_bind(); });
  21096. auto se = detail::scope_exit([&] {
  21097. svr.stop();
  21098. t.join();
  21099. });
  21100. svr.wait_until_ready();
  21101. Client cli(HOST, port);
  21102. cli.set_write_timeout(0, 500000);
  21103. cli.set_socket_options([](socket_t sock) {
  21104. int size = 8192;
  21105. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21106. reinterpret_cast<const char *>(&size), sizeof(size));
  21107. });
  21108. const std::string body(4 * 1024 * 1024, 'A');
  21109. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21110. "application/octet-stream");
  21111. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21112. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21113. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21114. }
  21115. #endif
  21116. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21117. std::promise<void> slow_started;
  21118. auto slow_started_future = slow_started.get_future();
  21119. Server svr;
  21120. svr.Get("/slow", [&](const Request &, Response &res) {
  21121. slow_started.set_value();
  21122. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21123. res.set_content("slow", "text/plain");
  21124. });
  21125. svr.Get("/fast", [](const Request &, Response &res) {
  21126. res.set_content("fast", "text/plain");
  21127. });
  21128. auto port = svr.bind_to_any_port(HOST);
  21129. std::thread t([&]() { svr.listen_after_bind(); });
  21130. auto se = detail::scope_exit([&] {
  21131. svr.stop();
  21132. t.join();
  21133. });
  21134. svr.wait_until_ready();
  21135. Client cli(HOST, port);
  21136. std::string slow_body;
  21137. std::thread slow_thread([&] {
  21138. auto res = cli.Get("/slow");
  21139. if (res) { slow_body = res->body; }
  21140. });
  21141. slow_started_future.wait();
  21142. auto result = stream::Get(cli, "/fast");
  21143. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21144. slow_thread.join();
  21145. EXPECT_EQ("slow", slow_body);
  21146. EXPECT_EQ("fast", fast_body);
  21147. }
  21148. // Serves `response` to the single request `fn` makes with a fresh client.
  21149. template <typename Fn>
  21150. static void with_single_response(const std::string &response, Fn fn) {
  21151. #ifndef _WIN32
  21152. signal(SIGPIPE, SIG_IGN);
  21153. #endif
  21154. std::promise<int> port_promise;
  21155. auto port_future = port_promise.get_future();
  21156. auto server_thread = serve_single_response(port_promise, response);
  21157. auto se = detail::scope_exit([&] { server_thread.join(); });
  21158. auto port = port_future.get();
  21159. ASSERT_GT(port, 0);
  21160. Client cli("127.0.0.1", port);
  21161. fn(cli);
  21162. }
  21163. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21164. // too, also in a build without the decoder for the advertised coding.
  21165. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21166. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21167. const auto response = "HTTP/1.1 200 OK\r\n"
  21168. "Content-Encoding: gzip\r\n"
  21169. "Content-Length: " +
  21170. std::to_string(gzipped.size()) +
  21171. "\r\n"
  21172. "Connection: close\r\n\r\n" +
  21173. gzipped;
  21174. with_single_response(response, [&](Client &cli) {
  21175. cli.set_decompress(false);
  21176. auto handle = cli.open_stream("GET", "/");
  21177. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21178. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21179. EXPECT_EQ(gzipped, read_all(handle));
  21180. EXPECT_FALSE(handle.has_read_error());
  21181. });
  21182. with_single_response(response, [&](Client &cli) {
  21183. cli.set_decompress(false);
  21184. auto res = stream::Get(cli, "/", 7);
  21185. ASSERT_TRUE(res) << to_string(res.error());
  21186. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21187. EXPECT_EQ(gzipped, res.read_all());
  21188. EXPECT_FALSE(res.has_read_error());
  21189. });
  21190. }
  21191. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21192. // Neither Content-Length nor chunked: the body ends at the close
  21193. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21194. "Connection: close\r\n"
  21195. "\r\n"
  21196. "hello";
  21197. with_single_response(close_delimited, [](Client &cli) {
  21198. auto handle = cli.open_stream("GET", "/");
  21199. ASSERT_TRUE(handle.is_valid());
  21200. EXPECT_EQ("hello", read_all(handle));
  21201. EXPECT_FALSE(handle.has_read_error());
  21202. });
  21203. // A close before the end of the Content-Length is still an error
  21204. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21205. "Content-Length: 10\r\n"
  21206. "\r\n"
  21207. "hello";
  21208. with_single_response(short_content_length, [](Client &cli) {
  21209. auto handle = cli.open_stream("GET", "/");
  21210. ASSERT_TRUE(handle.is_valid());
  21211. read_all(handle);
  21212. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21213. });
  21214. // So is a close before the last chunk
  21215. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21216. "Transfer-Encoding: chunked\r\n"
  21217. "\r\n"
  21218. "5\r\nhello\r\n";
  21219. with_single_response(short_chunked, [](Client &cli) {
  21220. auto handle = cli.open_stream("GET", "/");
  21221. ASSERT_TRUE(handle.is_valid());
  21222. read_all(handle);
  21223. EXPECT_TRUE(handle.has_read_error());
  21224. });
  21225. }
  21226. #ifdef CPPHTTPLIB_SSL_ENABLED
  21227. // Serves `response` to one request, then closes with or without a close_notify
  21228. template <typename Fn>
  21229. static void with_single_tls_response(const std::string &response,
  21230. bool close_notify, Fn fn) {
  21231. #ifndef _WIN32
  21232. signal(SIGPIPE, SIG_IGN);
  21233. #endif
  21234. std::promise<int> port_promise;
  21235. auto port_future = port_promise.get_future();
  21236. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21237. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21238. default_socket_options(srv);
  21239. sockaddr_in addr{};
  21240. addr.sin_family = AF_INET;
  21241. addr.sin_port = htons(0);
  21242. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21243. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21244. ::listen(srv, 1) != 0) {
  21245. port_promise.set_value(-1);
  21246. detail::close_socket(srv);
  21247. return;
  21248. }
  21249. socklen_t addr_len = sizeof(addr);
  21250. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21251. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21252. auto cli = ::accept(srv, nullptr, nullptr);
  21253. if (cli != INVALID_SOCKET) {
  21254. auto ctx = tls::create_server_context();
  21255. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21256. nullptr);
  21257. auto session = tls::create_session(ctx, cli);
  21258. tls::TlsError err;
  21259. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21260. // The request head first, so that closing the socket sends a FIN
  21261. // rather than an RST for the unread bytes.
  21262. std::string req;
  21263. char buf[256];
  21264. while (req.find("\r\n\r\n") == std::string::npos) {
  21265. auto n = tls::read(session, buf, sizeof(buf), err);
  21266. if (n <= 0) { break; }
  21267. req.append(buf, static_cast<size_t>(n));
  21268. }
  21269. size_t sent = 0;
  21270. while (sent < response.size()) {
  21271. auto n = tls::write(session, response.data() + sent,
  21272. response.size() - sent, err);
  21273. if (n <= 0) { break; }
  21274. sent += static_cast<size_t>(n);
  21275. }
  21276. if (close_notify) { tls::shutdown(session, true); }
  21277. }
  21278. tls::free_session(session);
  21279. detail::close_socket(cli);
  21280. tls::free_context(ctx);
  21281. }
  21282. detail::close_socket(srv);
  21283. });
  21284. auto se = detail::scope_exit([&] { server_thread.join(); });
  21285. auto port = port_future.get();
  21286. ASSERT_GT(port, 0);
  21287. SSLClient cli("127.0.0.1", port);
  21288. cli.enable_server_certificate_verification(false);
  21289. fn(cli);
  21290. }
  21291. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21292. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21293. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21294. "Connection: close\r\n"
  21295. "\r\n"
  21296. "hello";
  21297. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21298. auto res = cli.Get("/");
  21299. ASSERT_TRUE(res) << to_string(res.error());
  21300. EXPECT_EQ("hello", res->body);
  21301. });
  21302. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21303. auto res = cli.Get("/");
  21304. ASSERT_FALSE(res);
  21305. EXPECT_EQ(Error::Read, res.error());
  21306. });
  21307. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21308. auto handle = cli.open_stream("GET", "/");
  21309. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21310. read_all(handle);
  21311. EXPECT_TRUE(handle.has_read_error());
  21312. });
  21313. // A framed body ends where its framing says, with or without the alert
  21314. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21315. "Content-Length: 5\r\n"
  21316. "Connection: close\r\n"
  21317. "\r\n"
  21318. "hello";
  21319. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21320. auto res = cli.Get("/");
  21321. ASSERT_TRUE(res) << to_string(res.error());
  21322. EXPECT_EQ("hello", res->body);
  21323. });
  21324. }
  21325. #endif
  21326. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21327. const char *responses[] = {
  21328. "HTTP/1.1 103 Early Hints\r\n"
  21329. "Link: </style.css>; rel=preload\r\n"
  21330. "\r\n"
  21331. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21332. "HTTP/1.1 100 Continue\r\n"
  21333. "X-Note: interim\r\n"
  21334. "\r\n"
  21335. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21336. };
  21337. for (auto response : responses) {
  21338. with_single_response(response, [](Client &cli) {
  21339. auto res = cli.Get("/");
  21340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21341. EXPECT_EQ(StatusCode::OK_200, res->status);
  21342. EXPECT_EQ("ok", res->body);
  21343. });
  21344. }
  21345. }
  21346. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21347. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21348. const std::string final_response =
  21349. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21350. std::string interims;
  21351. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21352. interims += interim;
  21353. }
  21354. with_single_response(interims + final_response, [](Client &cli) {
  21355. auto res = cli.Get("/");
  21356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21357. EXPECT_EQ("ok", res->body);
  21358. });
  21359. with_single_response(interims + interim + final_response, [](Client &cli) {
  21360. auto res = cli.Get("/");
  21361. ASSERT_FALSE(res);
  21362. EXPECT_EQ(Error::Read, res.error());
  21363. });
  21364. }
  21365. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21366. #ifndef _WIN32
  21367. signal(SIGPIPE, SIG_IGN);
  21368. #endif
  21369. // The server answers the head without asking for the body. Bytes it then
  21370. // reads on the connection would be taken for the body the request declared.
  21371. auto closed_by_client = false;
  21372. std::promise<int> port_promise;
  21373. auto server_thread = serve_single_response(
  21374. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21375. [&](socket_t sock) {
  21376. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21377. char buf[256];
  21378. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21379. });
  21380. Client cli("127.0.0.1", port_promise.get_future().get());
  21381. cli.set_keep_alive(true);
  21382. cli.set_read_timeout(1, 0);
  21383. // Long enough for the client to send Expect: 100-continue.
  21384. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21386. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21387. cli.Get("/second");
  21388. server_thread.join();
  21389. EXPECT_TRUE(closed_by_client);
  21390. }
  21391. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21392. // Long enough for the client to send Expect: 100-continue
  21393. with_single_response(
  21394. "HTTP/1.1 103 Early Hints\r\n"
  21395. "Link: </style.css>; rel=preload\r\n"
  21396. "\r\n"
  21397. "HTTP/1.1 401 Unauthorized\r\n"
  21398. "Content-Length: 0\r\n\r\n",
  21399. [](Client &cli) {
  21400. cli.set_read_timeout(2, 0);
  21401. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21403. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21404. });
  21405. }
  21406. #ifdef CPPHTTPLIB_SSL_ENABLED
  21407. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21408. #ifndef _WIN32
  21409. signal(SIGPIPE, SIG_IGN);
  21410. #endif
  21411. auto reused = false;
  21412. std::promise<int> port_promise;
  21413. auto server_thread = serve_single_response(
  21414. port_promise,
  21415. "HTTP/1.1 401 Unauthorized\r\n"
  21416. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21417. "Content-Length: 0\r\n\r\n",
  21418. [&](socket_t sock) {
  21419. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21420. char buf[256];
  21421. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21422. });
  21423. Client cli("127.0.0.1", port_promise.get_future().get());
  21424. cli.set_keep_alive(true);
  21425. cli.set_digest_auth("user", "pass");
  21426. cli.set_read_timeout(1, 0);
  21427. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21428. server_thread.join();
  21429. EXPECT_FALSE(reused);
  21430. }
  21431. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21432. // Any other answer to CONNECT would read as the origin's response.
  21433. struct {
  21434. const char *response;
  21435. bool passed_on;
  21436. } cases[] = {
  21437. {"HTTP/1.1 201 Created\r\n"
  21438. "Set-Cookie: session=from-proxy\r\n"
  21439. "Content-Length: 0\r\n\r\n",
  21440. false},
  21441. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21442. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21443. "Content-Length: 0\r\n\r\n",
  21444. true},
  21445. };
  21446. for (const auto &c : cases) {
  21447. std::promise<int> port_promise;
  21448. auto server_thread = serve_single_response(port_promise, c.response);
  21449. SSLClient cli("example.com", 443);
  21450. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21451. auto res = cli.Get("/");
  21452. server_thread.join();
  21453. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21454. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21455. if (res) {
  21456. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21457. }
  21458. }
  21459. }
  21460. #endif
  21461. // Records the client's error logger calls as "error METHOD path", or
  21462. // "error null" for a call without a request
  21463. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21464. return [&log](const Error &err, const Request *req) {
  21465. log.push_back(to_string(err) + " " +
  21466. (req ? req->method + " " + req->path : "null"));
  21467. };
  21468. }
  21469. // A failed request is reported once, with the request the caller made
  21470. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21471. Server svr;
  21472. svr.Get("/big", [](const Request &, Response &res) {
  21473. res.set_content(std::string(100000, 'b'), "text/plain");
  21474. });
  21475. auto port = svr.bind_to_any_port(HOST);
  21476. std::thread t([&]() { svr.listen_after_bind(); });
  21477. auto se = detail::scope_exit([&] {
  21478. svr.stop();
  21479. t.join();
  21480. });
  21481. svr.wait_until_ready();
  21482. Client cli(HOST, port);
  21483. std::vector<std::string> log;
  21484. cli.set_error_logger(record_errors(log));
  21485. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21486. cli.Get("/big", [](const char *, size_t) { return false; });
  21487. EXPECT_EQ(expected, log);
  21488. log.clear();
  21489. cli.Get("/big", [](size_t, size_t) { return false; });
  21490. EXPECT_EQ(expected, log);
  21491. }
  21492. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21493. // Fails while the body is read
  21494. auto broken = [](const Request &, Response &res) {
  21495. res.set_content_provider(10, "text/plain",
  21496. [](size_t, size_t, DataSink &) { return false; });
  21497. };
  21498. Server other;
  21499. other.Get("/broken", broken);
  21500. auto other_port = other.bind_to_any_port(HOST);
  21501. std::thread other_t([&]() { other.listen_after_bind(); });
  21502. auto other_se = detail::scope_exit([&] {
  21503. other.stop();
  21504. other_t.join();
  21505. });
  21506. other.wait_until_ready();
  21507. Server svr;
  21508. svr.Get("/broken", broken);
  21509. svr.Get("/same-origin",
  21510. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21511. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21512. res.set_redirect("http://" + std::string(HOST) + ":" +
  21513. std::to_string(other_port) + "/broken");
  21514. });
  21515. auto port = svr.bind_to_any_port(HOST);
  21516. std::thread t([&]() { svr.listen_after_bind(); });
  21517. auto se = detail::scope_exit([&] {
  21518. svr.stop();
  21519. t.join();
  21520. });
  21521. svr.wait_until_ready();
  21522. Client cli(HOST, port);
  21523. cli.set_follow_location(true);
  21524. std::vector<std::string> log;
  21525. cli.set_error_logger(record_errors(log));
  21526. for (auto path : {"/same-origin", "/cross-origin"}) {
  21527. log.clear();
  21528. auto res = cli.Get(path);
  21529. ASSERT_FALSE(res);
  21530. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21531. log);
  21532. }
  21533. }
  21534. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21535. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21536. std::vector<std::string> log;
  21537. cli.set_error_logger(record_errors(log));
  21538. auto handle = cli.open_stream("GET", "/x");
  21539. EXPECT_FALSE(handle.is_valid());
  21540. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21541. log);
  21542. });
  21543. }
  21544. #ifdef CPPHTTPLIB_SSL_ENABLED
  21545. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21546. // Not a TLS server, so the handshake fails. It waits for a request line in
  21547. // the handshake bytes, so a short read timeout lets it close quickly.
  21548. Server svr;
  21549. svr.set_read_timeout(0, 100000);
  21550. svr.Get("/x", [](const Request &, Response &res) {
  21551. res.set_content("x", "text/plain");
  21552. });
  21553. auto port = svr.bind_to_any_port(HOST);
  21554. std::thread t([&]() { svr.listen_after_bind(); });
  21555. auto se = detail::scope_exit([&] {
  21556. svr.stop();
  21557. t.join();
  21558. });
  21559. svr.wait_until_ready();
  21560. std::vector<std::string> log;
  21561. SSLClient cli(HOST, port);
  21562. cli.enable_server_certificate_verification(false);
  21563. cli.set_error_logger(record_errors(log));
  21564. auto res = cli.Get("/x");
  21565. ASSERT_FALSE(res);
  21566. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21567. log.clear();
  21568. auto handle = cli.open_stream("GET", "/x");
  21569. EXPECT_FALSE(handle.is_valid());
  21570. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21571. log.clear();
  21572. SSLClient no_ca(HOST, port);
  21573. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21574. no_ca.set_error_logger(record_errors(log));
  21575. res = no_ca.Get("/x");
  21576. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21577. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21578. }
  21579. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21580. #ifndef _WIN32
  21581. signal(SIGPIPE, SIG_IGN);
  21582. #endif
  21583. // Refused, answered with a challenge, or closed without an answer
  21584. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21585. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21586. "Content-Length: 0\r\n\r\n",
  21587. ""}) {
  21588. std::promise<int> port_promise;
  21589. auto server_thread = serve_single_response(port_promise, response);
  21590. SSLClient cli("example.com", 443);
  21591. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21592. std::vector<std::string> log;
  21593. cli.set_error_logger(record_errors(log));
  21594. auto res = cli.Get("/");
  21595. server_thread.join();
  21596. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21597. << response;
  21598. }
  21599. }
  21600. #endif
  21601. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21602. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21603. // the chunked coding and drop Content-Length, so a front-end that trusts
  21604. // Content-Length would disagree about where the body ends (response
  21605. // smuggling). The client must reject such a response.
  21606. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21607. for (const char *te : {"chunked", "gzip, chunked"}) {
  21608. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21609. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21610. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21611. "5\r\nhello\r\n0\r\n\r\n";
  21612. with_single_response(response, [&](Client &cli) {
  21613. auto res = cli.Get("/");
  21614. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21615. EXPECT_EQ(Error::Read, res.error()) << te;
  21616. });
  21617. with_single_response(response, [&](Client &cli) {
  21618. auto handle = cli.open_stream("GET", "/");
  21619. EXPECT_FALSE(handle.is_valid()) << te;
  21620. EXPECT_EQ(Error::Read, handle.error) << te;
  21621. });
  21622. }
  21623. }
  21624. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21625. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21626. // closing the connection (unlike a request, which must be rejected).
  21627. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21628. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21629. "Transfer-Encoding: chunked\r\n"
  21630. "Connection: close\r\n"
  21631. "\r\n"
  21632. "5\r\nhello\r\n0\r\n\r\n",
  21633. "HTTP/1.1 200 OK\r\n"
  21634. "Transfer-Encoding: gzip\r\n"
  21635. "Connection: close\r\n"
  21636. "\r\n"
  21637. "hello"}) {
  21638. with_single_response(response, [&](Client &cli) {
  21639. auto res = cli.Get("/");
  21640. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21641. EXPECT_EQ("hello", res->body);
  21642. });
  21643. with_single_response(response, [&](Client &cli) {
  21644. auto handle = cli.open_stream("GET", "/");
  21645. ASSERT_TRUE(handle.is_valid()) << response;
  21646. EXPECT_EQ("hello", read_all(handle));
  21647. });
  21648. }
  21649. }
  21650. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21651. // framing headers describe nothing to read and must not be rejected.
  21652. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21653. const std::string framing = "Content-Length: 5\r\n"
  21654. "Transfer-Encoding: chunked\r\n"
  21655. "Connection: close\r\n"
  21656. "\r\n";
  21657. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21658. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21659. });
  21660. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21661. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21662. });
  21663. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21664. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21665. with_single_response(response, [&](Client &cli) {
  21666. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21667. });
  21668. with_single_response(response, [&](Client &cli) {
  21669. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21670. });
  21671. }
  21672. }
  21673. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21674. // header section, so a stream opened on one has nothing to read, whatever
  21675. // framing or coding headers it carries.
  21676. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21677. struct Case {
  21678. const char *method;
  21679. const char *status;
  21680. };
  21681. // A reader of the declared body reports an early close when nothing
  21682. // follows, and hands back what does.
  21683. struct Framing {
  21684. const char *headers;
  21685. const char *after;
  21686. };
  21687. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21688. Case{"GET", "304 Not Modified"}}) {
  21689. for (const auto &f :
  21690. {Framing{"Content-Length: 5\r\n", ""},
  21691. Framing{"Content-Length: 5\r\n", "hello"},
  21692. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21693. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21694. // Not decoded, so a build without Brotli opens it too
  21695. Framing{"Content-Encoding: br\r\n", ""}}) {
  21696. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21697. "Connection: close\r\n"
  21698. "\r\n" +
  21699. f.after;
  21700. with_single_response(response, [&](Client &cli) {
  21701. auto handle = cli.open_stream(c.method, "/");
  21702. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21703. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21704. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21705. });
  21706. }
  21707. }
  21708. }
  21709. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21710. // response, is faulty framing, so the connection is not reused after it.
  21711. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21712. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21713. "Content-Length: 0\r\n"
  21714. "Transfer-Encoding: chunked\r\n"
  21715. "\r\n"
  21716. "5\r\nhello\r\n0\r\n\r\n",
  21717. "HTTP/1.0 200 Connection established\r\n"
  21718. "Connection: keep-alive\r\n"
  21719. "Transfer-Encoding: chunked\r\n"
  21720. "\r\n"
  21721. "5\r\nhello\r\n0\r\n\r\n"}) {
  21722. with_single_response(response, [&](Client &cli) {
  21723. cli.set_keep_alive(true);
  21724. auto res = cli.Get("/");
  21725. ASSERT_TRUE(res) << response;
  21726. EXPECT_EQ("hello", res->body);
  21727. EXPECT_FALSE(cli.is_socket_open()) << response;
  21728. });
  21729. }
  21730. }
  21731. // A payload max length of 0 means no limit, however the body is framed.
  21732. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21733. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21734. "Transfer-Encoding: chunked\r\n"
  21735. "\r\n"
  21736. "5\r\nhello\r\n0\r\n\r\n",
  21737. "HTTP/1.1 200 OK\r\n"
  21738. "Connection: close\r\n"
  21739. "\r\n"
  21740. "hello"}) {
  21741. with_single_response(response, [&](Client &cli) {
  21742. cli.set_payload_max_length(0);
  21743. auto res = cli.Get("/");
  21744. ASSERT_TRUE(res) << response;
  21745. EXPECT_EQ("hello", res->body) << response;
  21746. });
  21747. }
  21748. }
  21749. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21750. Server svr;
  21751. svr.set_payload_max_length(0);
  21752. svr.Post("/echo", [](const Request &req, Response &res) {
  21753. res.set_content(req.body, "text/plain");
  21754. });
  21755. auto port = svr.bind_to_any_port(HOST);
  21756. thread t = thread([&] { svr.listen_after_bind(); });
  21757. auto se = detail::scope_exit([&] {
  21758. svr.stop();
  21759. t.join();
  21760. ASSERT_FALSE(svr.is_running());
  21761. });
  21762. svr.wait_until_ready();
  21763. Client cli(HOST, port);
  21764. auto res = cli.Post(
  21765. "/echo",
  21766. [](size_t /*offset*/, DataSink &sink) {
  21767. sink.write("hello", 5);
  21768. sink.done();
  21769. return true;
  21770. },
  21771. "text/plain");
  21772. ASSERT_TRUE(res);
  21773. EXPECT_EQ(StatusCode::OK_200, res->status);
  21774. EXPECT_EQ("hello", res->body);
  21775. }
  21776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21777. TEST_F(OpenStreamTest, Gzip) {
  21778. Client cli("127.0.0.1", port_);
  21779. auto handle = cli.open_stream("GET", "/compressible", {},
  21780. {{"Accept-Encoding", "gzip"}});
  21781. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21782. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21783. }
  21784. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21785. Client cli("127.0.0.1", port_);
  21786. auto handle =
  21787. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21788. {{"Accept-Encoding", "gzip"}});
  21789. ASSERT_TRUE(handle.is_valid());
  21790. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21791. EXPECT_EQ("123456789", read_all(handle));
  21792. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21793. }
  21794. #endif
  21795. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21796. TEST_F(OpenStreamTest, Brotli) {
  21797. Client cli("127.0.0.1", port_);
  21798. auto handle =
  21799. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21800. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21801. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21802. }
  21803. #endif
  21804. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21805. TEST_F(OpenStreamTest, Zstd) {
  21806. Client cli("127.0.0.1", port_);
  21807. auto handle = cli.open_stream("GET", "/compressible", {},
  21808. {{"Accept-Encoding", "zstd"}});
  21809. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21810. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21811. }
  21812. #endif
  21813. #ifdef CPPHTTPLIB_SSL_ENABLED
  21814. class SSLOpenStreamTest : public ::testing::Test {
  21815. protected:
  21816. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21817. void SetUp() override {
  21818. svr_.Get("/hello", [](const Request &, Response &res) {
  21819. res.set_content("Hello SSL World!", "text/plain");
  21820. });
  21821. svr_.Get("/chunked", [](const Request &, Response &res) {
  21822. res.set_chunked_content_provider("text/plain",
  21823. [](size_t offset, DataSink &sink) {
  21824. if (offset < 15) {
  21825. sink.write("chunk", 5);
  21826. return true;
  21827. }
  21828. sink.done();
  21829. return true;
  21830. });
  21831. });
  21832. svr_.Post("/echo", [](const Request &req, Response &res) {
  21833. res.set_content(req.body, req.get_header_value("Content-Type"));
  21834. });
  21835. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21836. std::string body = req.body;
  21837. res.set_chunked_content_provider(
  21838. "text/plain", [body](size_t offset, DataSink &sink) {
  21839. if (offset < body.size()) {
  21840. sink.write(body.data() + offset, body.size() - offset);
  21841. }
  21842. sink.done();
  21843. return true;
  21844. });
  21845. });
  21846. port_ = svr_.bind_to_any_port("127.0.0.1");
  21847. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21848. svr_.wait_until_ready();
  21849. }
  21850. void TearDown() override {
  21851. svr_.stop();
  21852. if (thread_.joinable()) thread_.join();
  21853. }
  21854. SSLServer svr_;
  21855. std::thread thread_;
  21856. int port_ = 0;
  21857. };
  21858. TEST_F(SSLOpenStreamTest, Basic) {
  21859. SSLClient cli("127.0.0.1", port_);
  21860. cli.enable_server_certificate_verification(false);
  21861. auto handle = cli.open_stream("GET", "/hello");
  21862. ASSERT_TRUE(handle.is_valid());
  21863. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21864. }
  21865. TEST_F(SSLOpenStreamTest, Chunked) {
  21866. SSLClient cli("127.0.0.1", port_);
  21867. cli.enable_server_certificate_verification(false);
  21868. auto handle = cli.open_stream("GET", "/chunked");
  21869. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21870. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21871. "Transfer-Encoding") == "chunked");
  21872. auto body = read_all(handle);
  21873. EXPECT_EQ("chunkchunkchunk", body);
  21874. }
  21875. TEST_F(SSLOpenStreamTest, Post) {
  21876. SSLClient cli("127.0.0.1", port_);
  21877. cli.enable_server_certificate_verification(false);
  21878. auto handle =
  21879. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21880. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21881. EXPECT_EQ(200, handle.response->status);
  21882. auto body = read_all(handle);
  21883. EXPECT_EQ("Hello SSL POST", body);
  21884. }
  21885. TEST_F(SSLOpenStreamTest, PostChunked) {
  21886. SSLClient cli("127.0.0.1", port_);
  21887. cli.enable_server_certificate_verification(false);
  21888. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21889. "Chunked SSL Data", "text/plain");
  21890. ASSERT_TRUE(handle.is_valid());
  21891. EXPECT_EQ(200, handle.response->status);
  21892. auto body = read_all(handle);
  21893. EXPECT_EQ("Chunked SSL Data", body);
  21894. }
  21895. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21896. // Content-Length is terminated by the server closing the connection. When the
  21897. // SSL peer sends a close_notify after the body, the client must treat it as a
  21898. // clean EOF and return a successful response rather than an error.
  21899. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21901. ASSERT_TRUE(svr.is_valid());
  21902. svr.set_keep_alive_max_count(1);
  21903. const std::string expected_body = "Hello from connection-close response!";
  21904. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21905. res.set_content_provider("text/plain",
  21906. [&](size_t offset, DataSink &sink) -> bool {
  21907. if (offset < expected_body.size()) {
  21908. sink.write(expected_body.data() + offset,
  21909. expected_body.size() - offset);
  21910. }
  21911. sink.done();
  21912. return true;
  21913. });
  21914. });
  21915. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21916. auto se = detail::scope_exit([&] {
  21917. svr.stop();
  21918. listen_thread.join();
  21919. ASSERT_FALSE(svr.is_running());
  21920. });
  21921. svr.wait_until_ready();
  21922. SSLClient cli(HOST, PORT);
  21923. cli.enable_server_certificate_verification(false);
  21924. auto res = cli.Get("/no-content-length");
  21925. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21926. EXPECT_EQ(StatusCode::OK_200, res->status);
  21927. EXPECT_EQ(expected_body, res->body);
  21928. }
  21929. // Without Content-Length, the full buffer size reaches tls::read().
  21930. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21931. if (sizeof(size_t) <= sizeof(int)) {
  21932. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21933. }
  21934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21935. ASSERT_TRUE(svr.is_valid());
  21936. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21937. res.set_content_provider("text/plain",
  21938. [&](size_t offset, DataSink &sink) -> bool {
  21939. if (offset == 0) { sink.write("Hello", 5); }
  21940. sink.done();
  21941. return true;
  21942. });
  21943. });
  21944. auto port = svr.bind_to_any_port(HOST);
  21945. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21946. auto se = detail::scope_exit([&] {
  21947. svr.stop();
  21948. listen_thread.join();
  21949. });
  21950. svr.wait_until_ready();
  21951. SSLClient cli(HOST, port);
  21952. cli.enable_server_certificate_verification(false);
  21953. auto handle = cli.open_stream("GET", "/no-content-length");
  21954. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21955. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21956. std::unique_ptr<char[]> buf(new char[len]);
  21957. std::string body;
  21958. ssize_t n;
  21959. while ((n = handle.read(buf.get(), len)) > 0) {
  21960. body.append(buf.get(), static_cast<size_t>(n));
  21961. }
  21962. EXPECT_EQ(0, n);
  21963. EXPECT_EQ("Hello", body);
  21964. }
  21965. #endif // CPPHTTPLIB_SSL_ENABLED
  21966. //==============================================================================
  21967. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21968. // results for various scenarios.
  21969. //==============================================================================
  21970. TEST(ParityTest, GetVsOpenStream) {
  21971. Server svr;
  21972. const std::string path = "/parity";
  21973. const std::string content = "Parity test content: hello world";
  21974. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21975. res.set_content(content, "text/plain");
  21976. });
  21977. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21978. auto se = detail::scope_exit([&] {
  21979. svr.stop();
  21980. t.join();
  21981. ASSERT_FALSE(svr.is_running());
  21982. });
  21983. svr.wait_until_ready();
  21984. Client cli(HOST, PORT);
  21985. // Non-stream path
  21986. auto r1 = cli.Get(path);
  21987. ASSERT_TRUE(r1);
  21988. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21989. // Stream path
  21990. auto h = cli.open_stream("GET", path);
  21991. ASSERT_TRUE(h.is_valid());
  21992. EXPECT_EQ(r1->body, read_all(h));
  21993. }
  21994. // Helper to compress data with provided compressor type T
  21995. template <typename Compressor>
  21996. static std::string compress_payload_for_parity(const std::string &in) {
  21997. std::string out;
  21998. Compressor compressor;
  21999. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22000. [&](const char *data, size_t n) {
  22001. out.append(data, n);
  22002. return true;
  22003. });
  22004. EXPECT_TRUE(ok);
  22005. return out;
  22006. }
  22007. // Helper function for compression parity tests
  22008. template <typename Compressor>
  22009. static void test_compression_parity(const std::string &original,
  22010. const std::string &path,
  22011. const std::string &encoding) {
  22012. const std::string compressed =
  22013. compress_payload_for_parity<Compressor>(original);
  22014. Server svr;
  22015. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22016. res.set_content(compressed, "application/octet-stream");
  22017. res.set_header("Content-Encoding", encoding);
  22018. });
  22019. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22020. auto se = detail::scope_exit([&] {
  22021. svr.stop();
  22022. t.join();
  22023. ASSERT_FALSE(svr.is_running());
  22024. });
  22025. svr.wait_until_ready();
  22026. Client cli(HOST, PORT);
  22027. // Non-streaming
  22028. {
  22029. auto res = cli.Get(path);
  22030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22031. EXPECT_EQ(StatusCode::OK_200, res->status);
  22032. EXPECT_EQ(original, res->body);
  22033. }
  22034. // Streaming
  22035. {
  22036. auto h = cli.open_stream("GET", path);
  22037. ASSERT_TRUE(h.is_valid());
  22038. EXPECT_EQ(original, read_all(h));
  22039. }
  22040. }
  22041. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22042. TEST(ParityTest, Gzip) {
  22043. test_compression_parity<detail::gzip_compressor>(
  22044. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22045. }
  22046. #endif
  22047. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22048. TEST(ParityTest, Brotli) {
  22049. test_compression_parity<detail::brotli_compressor>(
  22050. "Hello, brotli parity test payload", "/parity-br", "br");
  22051. }
  22052. #endif
  22053. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22054. TEST(ParityTest, Zstd) {
  22055. test_compression_parity<detail::zstd_compressor>(
  22056. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22057. }
  22058. #endif
  22059. //==============================================================================
  22060. // New Stream API Tests
  22061. //==============================================================================
  22062. inline std::string read_body(httplib::stream::Result &result) {
  22063. std::string body;
  22064. while (result.next()) {
  22065. body.append(result.data(), result.size());
  22066. }
  22067. return body;
  22068. }
  22069. TEST(ClientConnectionTest, Basic) {
  22070. httplib::ClientConnection conn;
  22071. EXPECT_FALSE(conn.is_open());
  22072. conn.sock = 1;
  22073. EXPECT_TRUE(conn.is_open());
  22074. httplib::ClientConnection conn2(std::move(conn));
  22075. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22076. conn2.sock = INVALID_SOCKET;
  22077. }
  22078. // Unified test server for all stream::* tests
  22079. class StreamApiTest : public ::testing::Test {
  22080. protected:
  22081. void SetUp() override {
  22082. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22083. res.set_content("Hello World!", "text/plain");
  22084. });
  22085. svr_.Get("/echo-params",
  22086. [](const httplib::Request &req, httplib::Response &res) {
  22087. std::string r;
  22088. for (const auto &p : req.params) {
  22089. if (!r.empty()) r += "&";
  22090. r += p.first + "=" + p.second;
  22091. }
  22092. res.set_content(r, "text/plain");
  22093. });
  22094. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22095. res.set_content(req.body, req.get_header_value("Content-Type"));
  22096. });
  22097. svr_.Post("/echo-headers",
  22098. [](const httplib::Request &req, httplib::Response &res) {
  22099. std::string r;
  22100. for (const auto &h : req.headers)
  22101. r += h.first + ": " + h.second + "\n";
  22102. res.set_content(r, "text/plain");
  22103. });
  22104. svr_.Post("/echo-params",
  22105. [](const httplib::Request &req, httplib::Response &res) {
  22106. std::string r = "params:";
  22107. for (const auto &p : req.params)
  22108. r += p.first + "=" + p.second + ";";
  22109. res.set_content(r + " body:" + req.body, "text/plain");
  22110. });
  22111. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22112. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22113. });
  22114. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22115. res.set_content("PUT:" + req.body, "text/plain");
  22116. });
  22117. svr_.Patch("/echo",
  22118. [](const httplib::Request &req, httplib::Response &res) {
  22119. res.set_content("PATCH:" + req.body, "text/plain");
  22120. });
  22121. svr_.Delete(
  22122. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22123. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22124. "text/plain");
  22125. });
  22126. svr_.Get("/head-test",
  22127. [](const httplib::Request &, httplib::Response &res) {
  22128. res.set_content("body for HEAD", "text/plain");
  22129. });
  22130. svr_.Options("/options",
  22131. [](const httplib::Request &, httplib::Response &res) {
  22132. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22133. });
  22134. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22135. svr_.wait_until_ready();
  22136. }
  22137. void TearDown() override {
  22138. svr_.stop();
  22139. if (thread_.joinable()) thread_.join();
  22140. }
  22141. httplib::Server svr_;
  22142. std::thread thread_;
  22143. };
  22144. // stream::Get tests
  22145. TEST_F(StreamApiTest, GetBasic) {
  22146. httplib::Client cli(HOST, PORT);
  22147. auto result = httplib::stream::Get(cli, "/hello");
  22148. ASSERT_TRUE(result.is_valid());
  22149. EXPECT_EQ(200, result.status());
  22150. EXPECT_EQ("Hello World!", read_body(result));
  22151. }
  22152. TEST_F(StreamApiTest, GetWithParams) {
  22153. httplib::Client cli(HOST, PORT);
  22154. httplib::Params params{{"foo", "bar"}};
  22155. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22156. ASSERT_TRUE(result.is_valid());
  22157. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22158. }
  22159. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22160. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22161. httplib::Client cli(HOST, PORT);
  22162. cli.set_payload_max_length(0);
  22163. auto result = httplib::stream::Get(cli, "/hello");
  22164. ASSERT_TRUE(result.is_valid());
  22165. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22166. EXPECT_EQ("Hello World!", read_body(result));
  22167. }
  22168. #endif
  22169. TEST_F(StreamApiTest, GetConnectionError) {
  22170. httplib::Client cli(HOST, 9999);
  22171. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22172. }
  22173. TEST_F(StreamApiTest, Get404) {
  22174. httplib::Client cli(HOST, PORT);
  22175. auto result = httplib::stream::Get(cli, "/nonexistent");
  22176. EXPECT_TRUE(result.is_valid());
  22177. EXPECT_EQ(404, result.status());
  22178. }
  22179. // stream::Post tests
  22180. TEST_F(StreamApiTest, PostBasic) {
  22181. httplib::Client cli(HOST, PORT);
  22182. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22183. "application/json");
  22184. ASSERT_TRUE(result.is_valid());
  22185. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22186. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22187. }
  22188. TEST_F(StreamApiTest, PostWithHeaders) {
  22189. httplib::Client cli(HOST, PORT);
  22190. httplib::Headers headers{{"X-Custom", "value"}};
  22191. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22192. "text/plain");
  22193. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22194. }
  22195. TEST_F(StreamApiTest, PostWithParams) {
  22196. httplib::Client cli(HOST, PORT);
  22197. httplib::Params params{{"k", "v"}};
  22198. auto result =
  22199. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22200. auto body = read_body(result);
  22201. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22202. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22203. }
  22204. TEST_F(StreamApiTest, PostLarge) {
  22205. httplib::Client cli(HOST, PORT);
  22206. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22207. size_t total = 0;
  22208. while (result.next()) {
  22209. total += result.size();
  22210. }
  22211. EXPECT_EQ(100u * 1024u, total);
  22212. }
  22213. // stream::Put/Patch tests
  22214. TEST_F(StreamApiTest, PutAndPatch) {
  22215. httplib::Client cli(HOST, PORT);
  22216. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22217. EXPECT_EQ("PUT:test", read_body(put));
  22218. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22219. EXPECT_EQ("PATCH:test", read_body(patch));
  22220. }
  22221. // stream::Delete tests
  22222. TEST_F(StreamApiTest, Delete) {
  22223. httplib::Client cli(HOST, PORT);
  22224. auto del1 = httplib::stream::Delete(cli, "/resource");
  22225. EXPECT_EQ("Deleted", read_body(del1));
  22226. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22227. EXPECT_EQ("Deleted:data", read_body(del2));
  22228. }
  22229. // stream::Head/Options tests
  22230. TEST_F(StreamApiTest, HeadAndOptions) {
  22231. httplib::Client cli(HOST, PORT);
  22232. auto head = httplib::stream::Head(cli, "/head-test");
  22233. EXPECT_TRUE(head.is_valid());
  22234. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22235. auto opts = httplib::stream::Options(cli, "/options");
  22236. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22237. }
  22238. // SSL stream::* tests
  22239. #ifdef CPPHTTPLIB_SSL_ENABLED
  22240. class SSLStreamApiTest : public ::testing::Test {
  22241. protected:
  22242. void SetUp() override {
  22243. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22244. res.set_content("Hello SSL!", "text/plain");
  22245. });
  22246. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22247. res.set_content(req.body, "text/plain");
  22248. });
  22249. port_ = svr_.bind_to_any_port("127.0.0.1");
  22250. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22251. svr_.wait_until_ready();
  22252. }
  22253. void TearDown() override {
  22254. svr_.stop();
  22255. if (thread_.joinable()) thread_.join();
  22256. }
  22257. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22258. std::thread thread_;
  22259. int port_ = 0;
  22260. };
  22261. TEST_F(SSLStreamApiTest, GetAndPost) {
  22262. httplib::SSLClient cli("127.0.0.1", port_);
  22263. cli.enable_server_certificate_verification(false);
  22264. auto get = httplib::stream::Get(cli, "/hello");
  22265. EXPECT_EQ("Hello SSL!", read_body(get));
  22266. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22267. EXPECT_EQ("test", read_body(post));
  22268. }
  22269. #endif
  22270. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22271. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22272. // BodyReader
  22273. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22274. // Test that read timeout during streaming is detected
  22275. // Use a large content-length response where server delays mid-stream
  22276. Server svr;
  22277. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22278. // Send a large response with delay in the middle
  22279. res.set_content_provider(
  22280. 1000, // content_length
  22281. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22282. if (offset < 100) {
  22283. // Send first 100 bytes immediately
  22284. std::string data(100, 'A');
  22285. sink.write(data.c_str(), data.size());
  22286. return true;
  22287. }
  22288. // Then delay longer than client timeout
  22289. std::this_thread::sleep_for(std::chrono::seconds(3));
  22290. std::string data(900, 'B');
  22291. sink.write(data.c_str(), data.size());
  22292. return true;
  22293. });
  22294. });
  22295. auto port = 8091;
  22296. std::thread t([&]() { svr.listen("localhost", port); });
  22297. svr.wait_until_ready();
  22298. Client cli("localhost", port);
  22299. cli.set_read_timeout(1, 0); // 1 second timeout
  22300. auto handle = cli.open_stream("GET", "/slow-stream");
  22301. ASSERT_TRUE(handle.is_valid());
  22302. char buf[256];
  22303. ssize_t total = 0;
  22304. ssize_t n;
  22305. bool got_error = false;
  22306. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22307. total += n;
  22308. }
  22309. if (n < 0) {
  22310. got_error = true;
  22311. // Should be timeout or read error
  22312. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22313. handle.get_read_error() == Error::Read)
  22314. << "Actual error: " << to_string(handle.get_read_error());
  22315. }
  22316. // Either we got an error, or we got less data than expected
  22317. EXPECT_TRUE(got_error || total < 1000)
  22318. << "Expected timeout but got all " << total << " bytes";
  22319. svr.stop();
  22320. t.join();
  22321. }
  22322. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22323. // Test connection closed detection via BodyReader
  22324. Server svr;
  22325. std::atomic<bool> close_now{false};
  22326. svr.Get("/will-close", [&](const Request &, Response &res) {
  22327. res.set_content_provider(
  22328. 10000, // Large content_length that we won't fully send
  22329. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22330. if (offset < 100) {
  22331. std::string data(100, 'X');
  22332. sink.write(data.c_str(), data.size());
  22333. return true;
  22334. }
  22335. // Wait for signal then abort
  22336. while (!close_now) {
  22337. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22338. }
  22339. return false; // Abort - server will close connection
  22340. });
  22341. });
  22342. auto port = 8092;
  22343. std::thread t([&]() { svr.listen("localhost", port); });
  22344. svr.wait_until_ready();
  22345. Client cli("localhost", port);
  22346. auto handle = cli.open_stream("GET", "/will-close");
  22347. ASSERT_TRUE(handle.is_valid());
  22348. char buf[256];
  22349. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22350. EXPECT_GT(n, 0) << "First read should succeed";
  22351. // Signal server to close
  22352. close_now = true;
  22353. // Keep reading until error or EOF
  22354. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22355. // Keep reading
  22356. }
  22357. // Should get an error since content_length wasn't satisfied
  22358. if (n < 0) {
  22359. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22360. handle.get_read_error() == Error::Read)
  22361. << "Actual error: " << to_string(handle.get_read_error());
  22362. }
  22363. svr.stop();
  22364. t.join();
  22365. }
  22366. #ifdef CPPHTTPLIB_SSL_ENABLED
  22367. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22368. // Test that read timeout during SSL streaming is detected
  22369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22370. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22371. res.set_content_provider(
  22372. 1000, "text/plain",
  22373. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22374. if (offset < 100) {
  22375. std::string data(100, 'A');
  22376. sink.write(data.c_str(), data.size());
  22377. return true;
  22378. }
  22379. std::this_thread::sleep_for(std::chrono::seconds(3));
  22380. std::string data(900, 'B');
  22381. sink.write(data.c_str(), data.size());
  22382. return true;
  22383. });
  22384. });
  22385. auto port = 8093;
  22386. std::thread t([&]() { svr.listen("localhost", port); });
  22387. svr.wait_until_ready();
  22388. SSLClient cli("localhost", port);
  22389. cli.enable_server_certificate_verification(false);
  22390. cli.set_read_timeout(1, 0); // 1 second timeout
  22391. auto handle = cli.open_stream("GET", "/slow-stream");
  22392. ASSERT_TRUE(handle.is_valid());
  22393. char buf[256];
  22394. ssize_t total = 0;
  22395. ssize_t n;
  22396. bool got_error = false;
  22397. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22398. total += n;
  22399. }
  22400. if (n < 0) {
  22401. got_error = true;
  22402. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22403. handle.get_read_error() == Error::Read)
  22404. << "Actual error: " << to_string(handle.get_read_error());
  22405. }
  22406. EXPECT_TRUE(got_error || total < 1000)
  22407. << "Expected timeout but got all " << total << " bytes";
  22408. svr.stop();
  22409. t.join();
  22410. }
  22411. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22412. // Test SSL connection closed detection
  22413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22414. std::atomic<bool> close_now{false};
  22415. svr.Get("/will-close", [&](const Request &, Response &res) {
  22416. res.set_content_provider(
  22417. 10000, "text/plain",
  22418. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22419. if (offset < 100) {
  22420. std::string data(100, 'X');
  22421. sink.write(data.c_str(), data.size());
  22422. return true;
  22423. }
  22424. while (!close_now) {
  22425. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22426. }
  22427. return false;
  22428. });
  22429. });
  22430. auto port = 8094;
  22431. std::thread t([&]() { svr.listen("localhost", port); });
  22432. svr.wait_until_ready();
  22433. SSLClient cli("localhost", port);
  22434. cli.enable_server_certificate_verification(false);
  22435. auto handle = cli.open_stream("GET", "/will-close");
  22436. ASSERT_TRUE(handle.is_valid());
  22437. char buf[256];
  22438. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22439. EXPECT_GT(n, 0);
  22440. // Signal server to close
  22441. close_now = true;
  22442. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22443. // Keep reading
  22444. }
  22445. if (n < 0) {
  22446. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22447. handle.get_read_error() == Error::Read)
  22448. << "Actual error: " << to_string(handle.get_read_error());
  22449. }
  22450. svr.stop();
  22451. t.join();
  22452. }
  22453. #endif
  22454. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22455. using namespace httplib;
  22456. // Create a test file
  22457. const char *fname = "etag_testfile.txt";
  22458. const char *content = "etag-content";
  22459. {
  22460. std::ofstream ofs(fname);
  22461. ofs << content;
  22462. ASSERT_TRUE(ofs.good());
  22463. }
  22464. Server svr;
  22465. svr.set_mount_point("/static", ".");
  22466. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22467. svr.wait_until_ready();
  22468. Client cli(HOST, PORT);
  22469. // First request: should get 200 with ETag header
  22470. auto res1 = cli.Get("/static/etag_testfile.txt");
  22471. ASSERT_TRUE(res1);
  22472. ASSERT_EQ(200, res1->status);
  22473. ASSERT_TRUE(res1->has_header("ETag"));
  22474. std::string etag = res1->get_header_value("ETag");
  22475. EXPECT_FALSE(etag.empty());
  22476. // Verify ETag format: W/"hex-hex"
  22477. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22478. EXPECT_EQ('W', etag[0]);
  22479. EXPECT_EQ('/', etag[1]);
  22480. EXPECT_EQ('"', etag[2]);
  22481. EXPECT_EQ('"', etag.back());
  22482. // Exact match: expect 304 Not Modified
  22483. Headers h2 = {{"If-None-Match", etag}};
  22484. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22485. ASSERT_TRUE(res2);
  22486. EXPECT_EQ(304, res2->status);
  22487. // Wildcard match: expect 304 Not Modified
  22488. Headers h3 = {{"If-None-Match", "*"}};
  22489. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22490. ASSERT_TRUE(res3);
  22491. EXPECT_EQ(304, res3->status);
  22492. // Non-matching ETag: expect 200
  22493. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22494. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22495. ASSERT_TRUE(res4);
  22496. EXPECT_EQ(200, res4->status);
  22497. // Multiple ETags with one matching: expect 304
  22498. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22499. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22500. ASSERT_TRUE(res5);
  22501. EXPECT_EQ(304, res5->status);
  22502. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22503. // that equivalent to the single comma-separated list above, so the match on
  22504. // the second line must still be found.
  22505. Headers h6;
  22506. h6.emplace("If-None-Match", "W/\"other\"");
  22507. h6.emplace("If-None-Match", etag);
  22508. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22509. ASSERT_TRUE(res6);
  22510. EXPECT_EQ(304, res6->status);
  22511. svr.stop();
  22512. t.join();
  22513. std::remove(fname);
  22514. }
  22515. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22516. using namespace httplib;
  22517. Server svr;
  22518. svr.set_mount_point("/static", ".");
  22519. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22520. svr.wait_until_ready();
  22521. Client cli(HOST, PORT);
  22522. // Send If-None-Match: * to a non-existent file
  22523. Headers h = {{"If-None-Match", "*"}};
  22524. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22526. EXPECT_EQ(404, res->status);
  22527. svr.stop();
  22528. t.join();
  22529. }
  22530. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22531. using namespace httplib;
  22532. // Create a test file
  22533. const char *fname = "etag_boundary_testfile.txt";
  22534. const char *content = "boundary-test";
  22535. {
  22536. std::ofstream ofs(fname);
  22537. ofs << content;
  22538. ASSERT_TRUE(ofs.good());
  22539. }
  22540. Server svr;
  22541. svr.set_mount_point("/static", ".");
  22542. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22543. svr.wait_until_ready();
  22544. Client cli(HOST, PORT);
  22545. // Get the actual ETag
  22546. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22547. ASSERT_TRUE(res1);
  22548. ASSERT_EQ(200, res1->status);
  22549. ASSERT_TRUE(res1->has_header("ETag"));
  22550. std::string etag = res1->get_header_value("ETag");
  22551. // Test 1: Very long ETag value (longer than actual ETag)
  22552. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22553. Headers h1 = {{"If-None-Match", "W/"
  22554. "\"very-long-etag-value-that-is-much-longer-"
  22555. "than-the-actual-etag-value\""}};
  22556. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22557. ASSERT_TRUE(res2);
  22558. EXPECT_EQ(200, res2->status); // Should not match
  22559. // Test 2: Long string followed by wildcard
  22560. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22561. // string)
  22562. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22563. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22564. ASSERT_TRUE(res3);
  22565. EXPECT_EQ(304, res3->status); // Should match on "*"
  22566. // Test 3: Wildcard followed by long string
  22567. // Should match on "*" immediately and return 304
  22568. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22569. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22570. ASSERT_TRUE(res4);
  22571. EXPECT_EQ(304, res4->status); // Should match on "*"
  22572. // Test 4: Multiple long non-matching values
  22573. // Should NOT match and return 200 (test that all comparisons are safe)
  22574. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22575. "W/\"second-long-non-matching-value\", "
  22576. "W/\"third-long-non-matching-value\""}};
  22577. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22578. ASSERT_TRUE(res5);
  22579. EXPECT_EQ(200, res5->status); // Should not match
  22580. // Test 5: Single character that is not "*" (edge case)
  22581. Headers h5 = {{"If-None-Match", "X"}};
  22582. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22583. ASSERT_TRUE(res6);
  22584. EXPECT_EQ(200, res6->status); // Should not match
  22585. svr.stop();
  22586. t.join();
  22587. std::remove(fname);
  22588. }
  22589. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22590. using namespace httplib;
  22591. // Create a test file
  22592. const char *fname = "ims_testfile.txt";
  22593. const char *content = "if-modified-since-test";
  22594. {
  22595. std::ofstream ofs(fname);
  22596. ofs << content;
  22597. ASSERT_TRUE(ofs.good());
  22598. }
  22599. Server svr;
  22600. svr.set_mount_point("/static", ".");
  22601. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22602. svr.wait_until_ready();
  22603. Client cli(HOST, PORT);
  22604. // First request: should get 200 with Last-Modified header
  22605. auto res1 = cli.Get("/static/ims_testfile.txt");
  22606. ASSERT_TRUE(res1);
  22607. ASSERT_EQ(200, res1->status);
  22608. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22609. std::string last_modified = res1->get_header_value("Last-Modified");
  22610. EXPECT_FALSE(last_modified.empty());
  22611. // If-Modified-Since with same time: expect 304
  22612. Headers h2 = {{"If-Modified-Since", last_modified}};
  22613. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22614. ASSERT_TRUE(res2);
  22615. EXPECT_EQ(304, res2->status);
  22616. // If-Modified-Since with future time: expect 304
  22617. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22618. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22619. ASSERT_TRUE(res3);
  22620. EXPECT_EQ(304, res3->status);
  22621. // If-Modified-Since with past time: expect 200
  22622. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22623. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22624. ASSERT_TRUE(res4);
  22625. EXPECT_EQ(200, res4->status);
  22626. // If-None-Match takes precedence over If-Modified-Since
  22627. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22628. ASSERT_TRUE(res1->has_header("ETag"));
  22629. std::string etag = res1->get_header_value("ETag");
  22630. Headers h5 = {{"If-None-Match", etag},
  22631. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22632. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22633. ASSERT_TRUE(res5);
  22634. EXPECT_EQ(304, res5->status);
  22635. svr.stop();
  22636. t.join();
  22637. std::remove(fname);
  22638. }
  22639. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22640. using namespace httplib;
  22641. Server svr;
  22642. // Endpoint that returns compressible content
  22643. svr.Get("/compressible", [](const Request &, Response &res) {
  22644. // Return a large enough body to trigger compression
  22645. std::string body(1000, 'a');
  22646. res.set_content(body, "text/plain");
  22647. });
  22648. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22649. svr.wait_until_ready();
  22650. Client cli(HOST, PORT);
  22651. // Request with gzip support: should get Vary header when compressed
  22652. cli.set_compress(true);
  22653. auto res1 = cli.Get("/compressible");
  22654. ASSERT_TRUE(res1);
  22655. EXPECT_EQ(200, res1->status);
  22656. // If Content-Encoding is set, Vary should also be set
  22657. if (res1->has_header("Content-Encoding")) {
  22658. EXPECT_TRUE(res1->has_header("Vary"));
  22659. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22660. }
  22661. // Request without Accept-Encoding header: should not have compression
  22662. Headers h_no_compress;
  22663. auto res2 = cli.Get("/compressible", h_no_compress);
  22664. ASSERT_TRUE(res2);
  22665. EXPECT_EQ(200, res2->status);
  22666. // Verify Vary header is present when compression is applied
  22667. // (the exact behavior depends on server configuration)
  22668. svr.stop();
  22669. t.join();
  22670. }
  22671. TEST(ETagTest, IfRangeWithETag) {
  22672. using namespace httplib;
  22673. // Create a test file with known content
  22674. const char *fname = "if_range_testfile.txt";
  22675. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22676. {
  22677. std::ofstream ofs(fname);
  22678. ofs << content;
  22679. ASSERT_TRUE(ofs.good());
  22680. }
  22681. Server svr;
  22682. svr.set_mount_point("/static", ".");
  22683. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22684. svr.wait_until_ready();
  22685. Client cli(HOST, PORT);
  22686. // First request: get ETag
  22687. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22688. ASSERT_TRUE(res1);
  22689. ASSERT_EQ(200, res1->status);
  22690. ASSERT_TRUE(res1->has_header("ETag"));
  22691. std::string etag = res1->get_header_value("ETag");
  22692. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22693. // Since our server generates weak ETags (W/"..."), If-Range with our
  22694. // ETag should NOT result in partial content - it should return full content.
  22695. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22696. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22697. ASSERT_TRUE(res2);
  22698. // Weak ETag in If-Range -> full content (200), not partial (206)
  22699. EXPECT_EQ(200, res2->status);
  22700. EXPECT_EQ(content, res2->body);
  22701. EXPECT_FALSE(res2->has_header("Content-Range"));
  22702. // Range request with non-matching If-Range (ETag): should get 200 (full
  22703. // content)
  22704. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22705. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22706. ASSERT_TRUE(res3);
  22707. EXPECT_EQ(200, res3->status);
  22708. EXPECT_EQ(content, res3->body);
  22709. EXPECT_FALSE(res3->has_header("Content-Range"));
  22710. // Range request with strong ETag (hypothetical - our server doesn't generate
  22711. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22712. // should return full content)
  22713. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22714. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22715. ASSERT_TRUE(res4);
  22716. EXPECT_EQ(200, res4->status);
  22717. EXPECT_EQ(content, res4->body);
  22718. EXPECT_FALSE(res4->has_header("Content-Range"));
  22719. svr.stop();
  22720. t.join();
  22721. std::remove(fname);
  22722. }
  22723. TEST(ETagTest, IfRangeWithDate) {
  22724. using namespace httplib;
  22725. // Create a test file
  22726. const char *fname = "if_range_date_testfile.txt";
  22727. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22728. {
  22729. std::ofstream ofs(fname);
  22730. ofs << content;
  22731. ASSERT_TRUE(ofs.good());
  22732. }
  22733. Server svr;
  22734. svr.set_mount_point("/static", ".");
  22735. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22736. svr.wait_until_ready();
  22737. Client cli(HOST, PORT);
  22738. // First request: get Last-Modified
  22739. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22740. ASSERT_TRUE(res1);
  22741. ASSERT_EQ(200, res1->status);
  22742. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22743. std::string last_modified = res1->get_header_value("Last-Modified");
  22744. // Range request with matching If-Range (date): should get 206
  22745. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22746. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22747. ASSERT_TRUE(res2);
  22748. EXPECT_EQ(206, res2->status);
  22749. EXPECT_EQ("FGHIJ", res2->body);
  22750. // Range request with old If-Range date: should get 200 (full content)
  22751. Headers h3 = {{"Range", "bytes=5-9"},
  22752. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22753. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22754. ASSERT_TRUE(res3);
  22755. EXPECT_EQ(200, res3->status);
  22756. EXPECT_EQ(content, res3->body);
  22757. // Range request with future If-Range date: should get 206
  22758. Headers h4 = {{"Range", "bytes=0-4"},
  22759. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22760. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22761. ASSERT_TRUE(res4);
  22762. EXPECT_EQ(206, res4->status);
  22763. EXPECT_EQ("ABCDE", res4->body);
  22764. svr.stop();
  22765. t.join();
  22766. std::remove(fname);
  22767. }
  22768. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22769. using namespace httplib;
  22770. const char *fname = "etag_malformed.txt";
  22771. const char *content = "malformed-etag";
  22772. {
  22773. std::ofstream ofs(fname);
  22774. ofs << content;
  22775. ASSERT_TRUE(ofs.good());
  22776. }
  22777. Server svr;
  22778. svr.set_mount_point("/static", ".");
  22779. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22780. svr.wait_until_ready();
  22781. Client cli(HOST, PORT);
  22782. // baseline: should get 200 and an ETag
  22783. auto res1 = cli.Get("/static/etag_malformed.txt");
  22784. ASSERT_TRUE(res1);
  22785. ASSERT_EQ(200, res1->status);
  22786. ASSERT_TRUE(res1->has_header("ETag"));
  22787. // Malformed ETag value (missing quotes) should be treated as non-matching
  22788. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22789. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22790. ASSERT_TRUE(res_bad);
  22791. EXPECT_EQ(200, res_bad->status);
  22792. // Whitespace-only header value should be considered invalid / non-matching
  22793. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22794. "Host: localhost\r\n"
  22795. "If-None-Match: \r\n"
  22796. "Connection: close\r\n"
  22797. "\r\n";
  22798. std::string out;
  22799. ASSERT_TRUE(send_request(5, raw_req, &out));
  22800. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22801. svr.stop();
  22802. t.join();
  22803. std::remove(fname);
  22804. }
  22805. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22806. using namespace httplib;
  22807. const char *fname = "ims_invalid_format.txt";
  22808. const char *content = "ims-bad-format";
  22809. {
  22810. std::ofstream ofs(fname);
  22811. ofs << content;
  22812. ASSERT_TRUE(ofs.good());
  22813. }
  22814. Server svr;
  22815. svr.set_mount_point("/static", ".");
  22816. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22817. svr.wait_until_ready();
  22818. Client cli(HOST, PORT);
  22819. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22820. ASSERT_TRUE(res1);
  22821. ASSERT_EQ(200, res1->status);
  22822. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22823. // If-Modified-Since with invalid format should not result in 304
  22824. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22825. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22826. ASSERT_TRUE(res_bad);
  22827. EXPECT_EQ(200, res_bad->status);
  22828. // If-Range with invalid date format should be treated as mismatch -> full
  22829. // content (200)
  22830. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22831. {"If-Range", "invalid-date"}};
  22832. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22833. ASSERT_TRUE(res_ifrange);
  22834. EXPECT_EQ(200, res_ifrange->status);
  22835. svr.stop();
  22836. t.join();
  22837. std::remove(fname);
  22838. }
  22839. TEST(ETagTest, IfRangeWithMalformedETag) {
  22840. using namespace httplib;
  22841. const char *fname = "ifrange_malformed.txt";
  22842. const std::string content = "0123456789";
  22843. {
  22844. std::ofstream ofs(fname);
  22845. ofs << content;
  22846. ASSERT_TRUE(ofs.good());
  22847. }
  22848. Server svr;
  22849. svr.set_mount_point("/static", ".");
  22850. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22851. svr.wait_until_ready();
  22852. Client cli(HOST, PORT);
  22853. // First request: get ETag
  22854. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22855. ASSERT_TRUE(res1);
  22856. ASSERT_EQ(200, res1->status);
  22857. ASSERT_TRUE(res1->has_header("ETag"));
  22858. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22859. // full content (200)
  22860. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22861. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22862. ASSERT_TRUE(res2);
  22863. EXPECT_EQ(200, res2->status);
  22864. EXPECT_EQ(content, res2->body);
  22865. svr.stop();
  22866. t.join();
  22867. std::remove(fname);
  22868. }
  22869. TEST(ETagTest, ExtremeLargeDateValues) {
  22870. using namespace httplib;
  22871. const char *fname = "ims_extreme_date.txt";
  22872. const char *content = "ims-extreme-date";
  22873. {
  22874. std::ofstream ofs(fname);
  22875. ofs << content;
  22876. ASSERT_TRUE(ofs.good());
  22877. }
  22878. Server svr;
  22879. svr.set_mount_point("/static", ".");
  22880. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22881. svr.wait_until_ready();
  22882. Client cli(HOST, PORT);
  22883. auto res1 = cli.Get(std::string("/static/") + fname);
  22884. ASSERT_TRUE(res1);
  22885. ASSERT_EQ(200, res1->status);
  22886. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22887. // Extremely large year that may overflow date parsing routines.
  22888. Headers h_large_date = {
  22889. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22890. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22891. ASSERT_TRUE(res_bad);
  22892. // Expect server to treat this as invalid/mismatch and return full content
  22893. EXPECT_EQ(200, res_bad->status);
  22894. // If-Range with extremely large date should be treated as mismatch -> full
  22895. // content (200)
  22896. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22897. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22898. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22899. ASSERT_TRUE(res_ifrange);
  22900. EXPECT_EQ(200, res_ifrange->status);
  22901. svr.stop();
  22902. t.join();
  22903. std::remove(fname);
  22904. }
  22905. TEST(ETagTest, NegativeFileModificationTime) {
  22906. using namespace httplib;
  22907. const char *fname = "ims_negative_mtime.txt";
  22908. const std::string content = "negative-mtime";
  22909. {
  22910. std::ofstream ofs(fname);
  22911. ofs << content;
  22912. ASSERT_TRUE(ofs.good());
  22913. }
  22914. // Try to set file mtime to a negative value. This may fail on some
  22915. // platforms/filesystems; if it fails, the test will still verify server
  22916. // behaves safely by performing a regular conditional request.
  22917. #if defined(__APPLE__) || defined(__linux__)
  22918. bool set_negative = false;
  22919. do {
  22920. struct timeval times[2];
  22921. // access time: now
  22922. times[0].tv_sec = time(nullptr);
  22923. times[0].tv_usec = 0;
  22924. // modification time: negative (e.g., -1)
  22925. times[1].tv_sec = -1;
  22926. times[1].tv_usec = 0;
  22927. if (utimes(fname, times) == 0) { set_negative = true; }
  22928. } while (0);
  22929. #else
  22930. bool set_negative = false;
  22931. #endif
  22932. Server svr;
  22933. svr.set_mount_point("/static", ".");
  22934. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22935. svr.wait_until_ready();
  22936. Client cli(HOST, PORT);
  22937. auto res1 = cli.Get(std::string("/static/") + fname);
  22938. ASSERT_TRUE(res1);
  22939. ASSERT_EQ(200, res1->status);
  22940. bool has_last_modified = res1->has_header("Last-Modified");
  22941. std::string last_modified;
  22942. if (has_last_modified) {
  22943. last_modified = res1->get_header_value("Last-Modified");
  22944. }
  22945. if (set_negative) {
  22946. // If we successfully set a negative mtime, ensure server returns a
  22947. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22948. // with an old date and ensure server handles it without crash.
  22949. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22950. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22951. ASSERT_TRUE(res2);
  22952. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22953. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22954. } else {
  22955. // Could not set negative mtime on this platform; fall back to verifying
  22956. // that normal invalid/malformed dates are treated safely (non-304).
  22957. Headers h_bad_date = {
  22958. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22959. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22960. ASSERT_TRUE(res_bad);
  22961. EXPECT_EQ(200, res_bad->status);
  22962. }
  22963. svr.stop();
  22964. t.join();
  22965. std::remove(fname);
  22966. }
  22967. //==============================================================================
  22968. // Integration Tests with Server
  22969. //==============================================================================
  22970. class SSEIntegrationTest : public ::testing::Test {
  22971. protected:
  22972. void SetUp() override {
  22973. stop_server_.store(false);
  22974. events_.clear();
  22975. server_ = httplib::detail::make_unique<Server>();
  22976. setup_server();
  22977. start_server();
  22978. }
  22979. void TearDown() override {
  22980. stop_server_.store(true);
  22981. event_cv_.notify_all();
  22982. server_->stop();
  22983. if (server_thread_.joinable()) { server_thread_.join(); }
  22984. }
  22985. void setup_server() {
  22986. // Simple SSE endpoint
  22987. server_->Get("/events", [this](const Request &req, Response &res) {
  22988. auto last_id = req.get_header_value("Last-Event-ID");
  22989. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22990. res.set_chunked_content_provider(
  22991. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22992. std::unique_lock<std::mutex> lock(event_mutex_);
  22993. if (event_cv_.wait_for(
  22994. lock, std::chrono::milliseconds(200), [this] {
  22995. return !events_.empty() || stop_server_.load();
  22996. })) {
  22997. if (stop_server_.load()) { return false; }
  22998. if (!events_.empty()) {
  22999. std::string event = events_.front();
  23000. events_.erase(events_.begin());
  23001. sink.write(event.data(), event.size());
  23002. return true;
  23003. }
  23004. }
  23005. return !stop_server_.load();
  23006. });
  23007. });
  23008. // Endpoint that returns error
  23009. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23010. res.status = 500;
  23011. res.set_content("Internal Server Error", "text/plain");
  23012. });
  23013. // Endpoint for custom event types
  23014. server_->Get("/custom-events", [](const Request &, Response &res) {
  23015. res.set_chunked_content_provider(
  23016. "text/event-stream", [](size_t offset, DataSink &sink) {
  23017. if (offset == 0) {
  23018. std::string event = "event: update\ndata: updated\n\n"
  23019. "event: delete\ndata: deleted\n\n";
  23020. sink.write(event.data(), event.size());
  23021. }
  23022. return false; // End stream after sending
  23023. });
  23024. });
  23025. }
  23026. void start_server() {
  23027. port_ = server_->bind_to_any_port(HOST);
  23028. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23029. // Wait for server to start
  23030. while (!server_->is_running()) {
  23031. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23032. }
  23033. }
  23034. int get_port() const { return port_; }
  23035. void send_event(const std::string &event) {
  23036. std::lock_guard<std::mutex> lock(event_mutex_);
  23037. events_.push_back(event);
  23038. event_cv_.notify_all();
  23039. }
  23040. std::unique_ptr<Server> server_;
  23041. std::thread server_thread_;
  23042. std::mutex event_mutex_;
  23043. std::condition_variable event_cv_;
  23044. std::vector<std::string> events_;
  23045. std::atomic<bool> stop_server_{false};
  23046. std::string last_received_event_id_;
  23047. int port_ = 0;
  23048. };
  23049. //==============================================================================
  23050. // SSE Parser Tests
  23051. //==============================================================================
  23052. struct SSEParseResult {
  23053. std::vector<sse::SSEMessage> events;
  23054. std::vector<std::string> ids;
  23055. std::vector<int> retries;
  23056. bool ok = true;
  23057. std::string trace; // Every handler call in order
  23058. };
  23059. static SSEParseResult
  23060. sse_parse(const std::vector<std::string> &chunks,
  23061. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23062. SSEParseResult r;
  23063. detail::SSEParser parser(
  23064. [&](const sse::SSEMessage &msg) {
  23065. r.events.push_back(msg);
  23066. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23067. },
  23068. [&](const std::string &id) {
  23069. r.ids.push_back(id);
  23070. r.trace += "id[" + id + "]";
  23071. },
  23072. [&](int retry_ms) {
  23073. r.retries.push_back(retry_ms);
  23074. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23075. },
  23076. max_event_length);
  23077. for (const auto &chunk : chunks) {
  23078. if (!parser.parse(chunk.data(), chunk.size())) {
  23079. r.ok = false;
  23080. break;
  23081. }
  23082. }
  23083. return r;
  23084. }
  23085. static SSEParseResult sse_parse(const std::string &stream) {
  23086. return sse_parse(std::vector<std::string>{stream});
  23087. }
  23088. TEST(SSEParserTest, SingleLineData) {
  23089. auto r = sse_parse("data: hello\n\n");
  23090. ASSERT_EQ(r.events.size(), 1u);
  23091. EXPECT_EQ(r.events[0].data, "hello");
  23092. EXPECT_EQ(r.events[0].event, "message");
  23093. }
  23094. TEST(SSEParserTest, MultiLineData) {
  23095. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23096. ASSERT_EQ(r.events.size(), 1u);
  23097. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23098. }
  23099. TEST(SSEParserTest, CustomEventType) {
  23100. auto r = sse_parse("event: update\ndata: payload\n\n");
  23101. ASSERT_EQ(r.events.size(), 1u);
  23102. EXPECT_EQ(r.events[0].event, "update");
  23103. EXPECT_EQ(r.events[0].data, "payload");
  23104. }
  23105. TEST(SSEParserTest, EventIdHandling) {
  23106. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23107. ASSERT_EQ(r.events.size(), 1u);
  23108. EXPECT_EQ(r.events[0].id, "12345");
  23109. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23110. }
  23111. TEST(SSEParserTest, EmptyEventId) {
  23112. auto r = sse_parse("id:\ndata: test\n\n");
  23113. ASSERT_EQ(r.events.size(), 1u);
  23114. EXPECT_EQ(r.events[0].id, "");
  23115. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23116. }
  23117. TEST(SSEParserTest, CommentsIgnored) {
  23118. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23119. ASSERT_EQ(r.events.size(), 1u);
  23120. EXPECT_EQ(r.events[0].data, "hello");
  23121. EXPECT_EQ(r.events[0].event, "message");
  23122. }
  23123. TEST(SSEParserTest, ColonInValue) {
  23124. auto r = sse_parse("data: hello:world:test\n\n");
  23125. ASSERT_EQ(r.events.size(), 1u);
  23126. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23127. }
  23128. TEST(SSEParserTest, FieldNameOnly) {
  23129. // A line without a colon is a field name with an empty value
  23130. auto r = sse_parse("data\n\n");
  23131. ASSERT_EQ(r.events.size(), 1u);
  23132. EXPECT_EQ(r.events[0].data, "");
  23133. }
  23134. TEST(SSEParserTest, TrailingCarriageReturn) {
  23135. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23136. ASSERT_EQ(r.events.size(), 1u);
  23137. EXPECT_EQ(r.events[0].event, "update");
  23138. EXPECT_EQ(r.events[0].data, "hello");
  23139. }
  23140. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23141. auto r = sse_parse("data\r\n\r\n");
  23142. ASSERT_EQ(r.events.size(), 1u);
  23143. EXPECT_EQ(r.events[0].data, "");
  23144. }
  23145. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23146. auto r = sse_parse("event: update\rdata: hello\r\r");
  23147. ASSERT_EQ(r.events.size(), 1u);
  23148. EXPECT_EQ(r.events[0].event, "update");
  23149. EXPECT_EQ(r.events[0].data, "hello");
  23150. }
  23151. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23152. // Chunk boundaries fall inside every \r\n and right before the first one
  23153. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23154. "\ndata: hello\r", "\n\r", "\n"});
  23155. ASSERT_EQ(r.events.size(), 1u);
  23156. EXPECT_EQ(r.events[0].event, "update");
  23157. EXPECT_EQ(r.events[0].data, "hello");
  23158. }
  23159. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23160. // Only a BOM at the start of the stream is ignored
  23161. auto r = sse_parse("\xEF\xBB\xBF"
  23162. "data: first\n\n"
  23163. "\xEF\xBB\xBF"
  23164. "data: second\n\n");
  23165. ASSERT_EQ(r.events.size(), 1u);
  23166. EXPECT_EQ(r.events[0].data, "first");
  23167. }
  23168. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23169. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23170. ASSERT_EQ(r.events.size(), 1u);
  23171. EXPECT_EQ(r.events[0].data, "hello");
  23172. EXPECT_EQ(r.events[0].event, "message");
  23173. }
  23174. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23175. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23176. ASSERT_EQ(r.events.size(), 2u);
  23177. EXPECT_EQ(r.events[0].data, "hello");
  23178. EXPECT_EQ(r.events[1].data, "hello");
  23179. }
  23180. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23181. // An event without data is not dispatched, and its type must not leak
  23182. // into the next event
  23183. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23184. ASSERT_EQ(r.events.size(), 1u);
  23185. EXPECT_EQ(r.events[0].event, "message");
  23186. EXPECT_EQ(r.events[0].data, "hello");
  23187. }
  23188. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23189. // Also when the empty field replaces an earlier type
  23190. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23191. ASSERT_EQ(r.events.size(), 2u);
  23192. EXPECT_EQ(r.events[0].event, "message");
  23193. EXPECT_EQ(r.events[1].event, "message");
  23194. }
  23195. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23196. auto r = sse_parse("id: 42\n\n");
  23197. EXPECT_TRUE(r.events.empty());
  23198. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23199. }
  23200. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23201. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23202. ASSERT_EQ(r.events.size(), 2u);
  23203. EXPECT_EQ(r.events[0].id, "1");
  23204. EXPECT_EQ(r.events[1].id, "");
  23205. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23206. }
  23207. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23208. // Ids that cannot be carried in a Last-Event-ID header
  23209. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23210. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23211. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23212. }
  23213. TEST(SSEParserTest, RetryDigitsOnly) {
  23214. auto r = sse_parse("retry: 1000\n");
  23215. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23216. // A value that is not all ASCII digits, or does not fit, is ignored
  23217. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23218. EXPECT_TRUE(r.retries.empty());
  23219. }
  23220. TEST(SSEParserTest, CompleteEventParsing) {
  23221. auto r = sse_parse("event: notification\nid: evt-42\n"
  23222. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23223. ASSERT_EQ(r.events.size(), 1u);
  23224. EXPECT_EQ(r.events[0].event, "notification");
  23225. EXPECT_EQ(r.events[0].id, "evt-42");
  23226. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23227. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23228. }
  23229. TEST(SSEParserTest, IncompleteEventNotReported) {
  23230. // An event still waiting for its blank line when the stream ends is
  23231. // discarded per the SSE spec
  23232. auto r = sse_parse("id: 1\ndata: x\n");
  23233. EXPECT_TRUE(r.events.empty());
  23234. EXPECT_TRUE(r.ids.empty());
  23235. }
  23236. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23237. const std::vector<std::string> streams = {
  23238. "\xEF\xBB\xBF"
  23239. "data: bom\r\n\r\n",
  23240. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23241. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23242. };
  23243. for (const auto &stream : streams) {
  23244. auto expected = sse_parse(stream).trace;
  23245. ASSERT_FALSE(expected.empty());
  23246. for (size_t i = 0; i <= stream.size(); i++) {
  23247. auto r = sse_parse(
  23248. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23249. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23250. }
  23251. std::vector<std::string> bytes;
  23252. for (auto c : stream) {
  23253. bytes.emplace_back(1, c);
  23254. }
  23255. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23256. }
  23257. }
  23258. TEST(SSEParserTest, MaxEventLength) {
  23259. // A line still waiting for its end
  23260. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23261. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23262. // Data accumulated over the lines of one event
  23263. EXPECT_TRUE(
  23264. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23265. EXPECT_FALSE(
  23266. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23267. // 0 means no limit
  23268. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23269. // Events completed in the same chunk are still reported
  23270. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23271. EXPECT_FALSE(r.ok);
  23272. ASSERT_EQ(r.events.size(), 1u);
  23273. EXPECT_EQ(r.events[0].data, "a");
  23274. }
  23275. TEST(SSEMessageTest, Clear) {
  23276. sse::SSEMessage msg;
  23277. msg.event = "custom";
  23278. msg.data = "some data";
  23279. msg.id = "123";
  23280. msg.clear();
  23281. EXPECT_EQ(msg.event, "message");
  23282. EXPECT_EQ(msg.data, "");
  23283. EXPECT_EQ(msg.id, "");
  23284. }
  23285. //==============================================================================
  23286. // SSE Integration Tests
  23287. //==============================================================================
  23288. // Test: Successful connection and on_open callback
  23289. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23290. // Add a simple endpoint that sends one event and closes
  23291. server_->Get("/simple-event", [](const Request &, Response &res) {
  23292. res.set_chunked_content_provider(
  23293. "text/event-stream", [](size_t offset, DataSink &sink) {
  23294. if (offset == 0) {
  23295. std::string event = "data: hello\n\n";
  23296. sink.write(event.data(), event.size());
  23297. }
  23298. return false; // Close stream after sending
  23299. });
  23300. });
  23301. Client client("localhost", get_port());
  23302. sse::SSEClient sse(client, "/simple-event");
  23303. std::atomic<bool> open_called{false};
  23304. std::atomic<bool> message_received{false};
  23305. sse.on_open([&open_called]() { open_called.store(true); });
  23306. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23307. if (msg.data == "hello") { message_received.store(true); }
  23308. });
  23309. sse.set_reconnect_interval(100);
  23310. sse.set_max_reconnect_attempts(1);
  23311. // Start async
  23312. sse.start_async();
  23313. // Wait for message to be processed
  23314. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23315. sse.stop();
  23316. EXPECT_TRUE(open_called.load());
  23317. EXPECT_TRUE(message_received.load());
  23318. }
  23319. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23320. // A data line that never ends.
  23321. server_->Get("/endless-line", [](const Request &, Response &res) {
  23322. res.set_chunked_content_provider(
  23323. "text/event-stream", [](size_t offset, DataSink &sink) {
  23324. if (offset == 0) { sink.write("data: ", 6); }
  23325. std::string chunk(64 * 1024, 'A');
  23326. return sink.write(chunk.data(), chunk.size());
  23327. });
  23328. });
  23329. Client client("localhost", get_port());
  23330. sse::SSEClient sse(client, "/endless-line");
  23331. std::atomic<bool> too_long{false};
  23332. sse.on_error([&](Error err) {
  23333. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23334. });
  23335. sse.set_max_reconnect_attempts(1);
  23336. sse.start_async();
  23337. for (int i = 0; i < 500 && !too_long; i++) {
  23338. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23339. }
  23340. sse.stop();
  23341. EXPECT_TRUE(too_long);
  23342. }
  23343. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23344. // Far more in all than the client's payload limit below.
  23345. server_->Get("/many-events", [](const Request &, Response &res) {
  23346. res.set_chunked_content_provider(
  23347. "text/event-stream", [](size_t offset, DataSink &sink) {
  23348. if (offset == 0) {
  23349. std::string events;
  23350. for (int i = 0; i < 1000; i++) {
  23351. events += "data: message\n\n";
  23352. }
  23353. sink.write(events.data(), events.size());
  23354. }
  23355. return false;
  23356. });
  23357. });
  23358. Client client("localhost", get_port());
  23359. client.set_payload_max_length(1024);
  23360. sse::SSEClient sse(client, "/many-events");
  23361. std::atomic<int> messages{0};
  23362. std::atomic<bool> too_large{false};
  23363. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23364. sse.on_error([&](Error err) {
  23365. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23366. });
  23367. sse.set_max_reconnect_attempts(1);
  23368. sse.start_async();
  23369. for (int i = 0; i < 500 && messages < 1000; i++) {
  23370. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23371. }
  23372. sse.stop();
  23373. EXPECT_GE(messages.load(), 1000);
  23374. EXPECT_FALSE(too_large);
  23375. }
  23376. // Test: on_message callback
  23377. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23378. // Endpoint that sends multiple events then closes
  23379. server_->Get("/multi-event", [](const Request &, Response &res) {
  23380. res.set_chunked_content_provider(
  23381. "text/event-stream", [](size_t offset, DataSink &sink) {
  23382. if (offset == 0) {
  23383. std::string events = "data: message1\n\ndata: message2\n\n";
  23384. sink.write(events.data(), events.size());
  23385. }
  23386. return false;
  23387. });
  23388. });
  23389. Client client("localhost", get_port());
  23390. sse::SSEClient sse(client, "/multi-event");
  23391. std::vector<std::string> received_messages;
  23392. std::mutex messages_mutex;
  23393. sse.on_message([&](const sse::SSEMessage &msg) {
  23394. std::lock_guard<std::mutex> lock(messages_mutex);
  23395. received_messages.push_back(msg.data);
  23396. });
  23397. sse.set_reconnect_interval(100);
  23398. sse.set_max_reconnect_attempts(1);
  23399. sse.start_async();
  23400. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23401. sse.stop();
  23402. std::lock_guard<std::mutex> lock(messages_mutex);
  23403. EXPECT_GE(received_messages.size(), 2u);
  23404. if (received_messages.size() >= 2) {
  23405. EXPECT_EQ(received_messages[0], "message1");
  23406. EXPECT_EQ(received_messages[1], "message2");
  23407. }
  23408. }
  23409. // Test: on_event for specific types
  23410. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23411. Client client("localhost", get_port());
  23412. sse::SSEClient sse(client, "/custom-events");
  23413. std::atomic<bool> update_received{false};
  23414. std::atomic<bool> delete_received{false};
  23415. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23416. if (msg.data == "updated") { update_received.store(true); }
  23417. });
  23418. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23419. if (msg.data == "deleted") { delete_received.store(true); }
  23420. });
  23421. sse.set_max_reconnect_attempts(1);
  23422. sse.start_async();
  23423. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23424. sse.stop();
  23425. EXPECT_TRUE(update_received.load());
  23426. EXPECT_TRUE(delete_received.load());
  23427. }
  23428. // Test: on_error callback on connection failure
  23429. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23430. // Connect to a non-existent port
  23431. Client client("localhost", 59999);
  23432. sse::SSEClient sse(client, "/events");
  23433. std::atomic<bool> error_called{false};
  23434. Error received_error = Error::Success;
  23435. sse.on_error([&](Error err) {
  23436. error_called.store(true);
  23437. received_error = err;
  23438. });
  23439. sse.set_reconnect_interval(50);
  23440. sse.set_max_reconnect_attempts(1);
  23441. sse.start_async();
  23442. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23443. sse.stop();
  23444. EXPECT_TRUE(error_called.load());
  23445. EXPECT_NE(received_error, Error::Success);
  23446. }
  23447. // Test: Last-Event-ID header sent on reconnect
  23448. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23449. // Endpoint that sends event with ID
  23450. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23451. res.set_chunked_content_provider(
  23452. "text/event-stream", [](size_t offset, DataSink &sink) {
  23453. if (offset == 0) {
  23454. std::string event = "id: evt-123\ndata: test\n\n";
  23455. sink.write(event.data(), event.size());
  23456. }
  23457. return false;
  23458. });
  23459. });
  23460. Client client("localhost", get_port());
  23461. sse::SSEClient sse(client, "/event-with-id");
  23462. std::atomic<bool> id_received{false};
  23463. sse.on_message([&](const sse::SSEMessage &msg) {
  23464. if (!msg.id.empty()) { id_received.store(true); }
  23465. });
  23466. sse.set_reconnect_interval(100);
  23467. sse.set_max_reconnect_attempts(1);
  23468. sse.start_async();
  23469. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23470. sse.stop();
  23471. EXPECT_TRUE(id_received.load());
  23472. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23473. }
  23474. // Test: last_event_id() read from another thread while start_async() runs
  23475. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23476. // Ids of every length up to 200, so the stored id keeps changing size
  23477. server_->Get("/many-ids", [](const Request &, Response &res) {
  23478. res.set_chunked_content_provider(
  23479. "text/event-stream", [](size_t offset, DataSink &sink) {
  23480. if (offset == 0) {
  23481. std::string events;
  23482. for (size_t i = 0; i < 2000; i++) {
  23483. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23484. events += "data: x\n\n";
  23485. }
  23486. events += "id: end\ndata: x\n\n";
  23487. sink.write(events.data(), events.size());
  23488. }
  23489. return false;
  23490. });
  23491. });
  23492. Client client("localhost", get_port());
  23493. sse::SSEClient sse(client, "/many-ids");
  23494. // Wait out the rest of the test rather than replay the stream
  23495. sse.set_reconnect_interval(10000);
  23496. sse.set_max_reconnect_attempts(1);
  23497. sse.start_async();
  23498. auto well_formed = true;
  23499. std::string id;
  23500. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23501. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23502. id = sse.last_event_id();
  23503. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23504. well_formed = false;
  23505. }
  23506. }
  23507. sse.stop();
  23508. EXPECT_TRUE(well_formed);
  23509. EXPECT_EQ(sse.last_event_id(), "end");
  23510. }
  23511. // Test: Manual stop
  23512. TEST_F(SSEIntegrationTest, ManualStop) {
  23513. // Endpoint that sends one event and stays open briefly. The server outlives
  23514. // this test body, so the provider uses the fixture's flag, not a local.
  23515. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23516. res.set_chunked_content_provider(
  23517. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23518. if (offset == 0) {
  23519. std::string event = "data: connected\n\n";
  23520. sink.write(event.data(), event.size());
  23521. }
  23522. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23523. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23524. }
  23525. return false;
  23526. });
  23527. });
  23528. Client client("localhost", get_port());
  23529. sse::SSEClient sse(client, "/stay-open");
  23530. std::atomic<bool> connected{false};
  23531. sse.on_open([&connected]() { connected.store(true); });
  23532. sse.set_reconnect_interval(100);
  23533. sse.set_max_reconnect_attempts(1);
  23534. sse.start_async();
  23535. // Wait for connection to establish
  23536. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23537. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23538. }
  23539. EXPECT_TRUE(connected.load());
  23540. EXPECT_TRUE(sse.is_connected());
  23541. // Signal handler to stop
  23542. stop_server_.store(true);
  23543. // Stop SSE client
  23544. sse.stop();
  23545. EXPECT_FALSE(sse.is_connected());
  23546. }
  23547. // Sends one event, then nothing until stop is set
  23548. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23549. return [&stop](const Request &, Response &res) {
  23550. res.set_chunked_content_provider(
  23551. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23552. if (offset == 0) {
  23553. std::string event = "data: hello\n\n";
  23554. sink.write(event.data(), event.size());
  23555. }
  23556. while (!stop.load()) {
  23557. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23558. }
  23559. return false;
  23560. });
  23561. };
  23562. }
  23563. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23564. static void check_stop_interrupts_blocked_read(Client &client) {
  23565. client.set_read_timeout(30, 0);
  23566. for (auto by_destructor : {false, true}) {
  23567. std::atomic<bool> received{false};
  23568. std::chrono::steady_clock::time_point start;
  23569. {
  23570. sse::SSEClient sse(client, "/idle-stream");
  23571. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23572. sse.start_async();
  23573. for (int i = 0; i < 500 && !received.load(); ++i) {
  23574. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23575. }
  23576. ASSERT_TRUE(received.load());
  23577. // Let the client block in the next read
  23578. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23579. start = std::chrono::steady_clock::now();
  23580. if (!by_destructor) { sse.stop(); }
  23581. }
  23582. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23583. std::chrono::seconds(2));
  23584. }
  23585. }
  23586. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23587. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23588. Client client("localhost", get_port());
  23589. check_stop_interrupts_blocked_read(client);
  23590. }
  23591. #ifdef CPPHTTPLIB_SSL_ENABLED
  23592. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23594. std::atomic<bool> done{false};
  23595. svr.Get("/idle-stream", idle_event_stream(done));
  23596. auto port = svr.bind_to_any_port(HOST);
  23597. std::thread t([&] { svr.listen_after_bind(); });
  23598. auto se = detail::scope_exit([&] {
  23599. done.store(true);
  23600. svr.stop();
  23601. t.join();
  23602. });
  23603. svr.wait_until_ready();
  23604. Client client("https://localhost:" + std::to_string(port));
  23605. client.enable_server_certificate_verification(false);
  23606. check_stop_interrupts_blocked_read(client);
  23607. }
  23608. #endif
  23609. // Test: SSEClient with custom headers
  23610. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23611. // Setup a server endpoint that checks for custom header
  23612. std::atomic<bool> header_received{false};
  23613. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23614. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23615. header_received.store(true);
  23616. }
  23617. res.set_chunked_content_provider("text/event-stream",
  23618. [](size_t, DataSink &) { return false; });
  23619. });
  23620. Client client("localhost", get_port());
  23621. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23622. sse::SSEClient sse(client, "/header-check", headers);
  23623. sse.set_max_reconnect_attempts(1);
  23624. sse.start_async();
  23625. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23626. sse.stop();
  23627. EXPECT_TRUE(header_received.load());
  23628. }
  23629. // Test: Reconnect interval configuration
  23630. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23631. Client client("localhost", get_port());
  23632. sse::SSEClient sse(client, "/events");
  23633. auto &result = sse.set_reconnect_interval(500);
  23634. // Builder pattern should return reference to self
  23635. EXPECT_EQ(&result, &sse);
  23636. }
  23637. // Test: Max reconnect attempts
  23638. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23639. // Connect to non-existent port to force reconnects
  23640. Client client("localhost", 59998);
  23641. sse::SSEClient sse(client, "/events");
  23642. std::atomic<int> error_count{0};
  23643. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23644. sse.set_reconnect_interval(50);
  23645. sse.set_max_reconnect_attempts(2);
  23646. auto start = std::chrono::steady_clock::now();
  23647. sse.start(); // Blocking call
  23648. auto end = std::chrono::steady_clock::now();
  23649. // Should have stopped after 2 failed attempts
  23650. EXPECT_GE(error_count.load(), 2);
  23651. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23652. auto duration =
  23653. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23654. #ifdef _WIN32
  23655. // Windows is much slower for socket connection failures
  23656. EXPECT_LT(duration.count(), 7000);
  23657. #else
  23658. EXPECT_LT(duration.count(), 1000);
  23659. #endif
  23660. }
  23661. // Test: Multi-line data in integration
  23662. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23663. // Endpoint with multi-line data
  23664. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23665. res.set_chunked_content_provider(
  23666. "text/event-stream", [](size_t offset, DataSink &sink) {
  23667. if (offset == 0) {
  23668. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23669. sink.write(event.data(), event.size());
  23670. }
  23671. return false;
  23672. });
  23673. });
  23674. Client client("localhost", get_port());
  23675. sse::SSEClient sse(client, "/multiline-data");
  23676. std::string received_data;
  23677. std::mutex data_mutex;
  23678. sse.on_message([&](const sse::SSEMessage &msg) {
  23679. std::lock_guard<std::mutex> lock(data_mutex);
  23680. received_data = msg.data;
  23681. });
  23682. sse.set_reconnect_interval(100);
  23683. sse.set_max_reconnect_attempts(1);
  23684. sse.start_async();
  23685. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23686. sse.stop();
  23687. std::lock_guard<std::mutex> lock(data_mutex);
  23688. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23689. }
  23690. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23691. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23692. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23693. DataSink &sink) {
  23694. if (offset == 0) {
  23695. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23696. sink.write(events.data(), events.size());
  23697. }
  23698. return false;
  23699. });
  23700. });
  23701. Client client("localhost", get_port());
  23702. sse::SSEClient sse(client, "/empty-data-lines");
  23703. std::mutex mutex;
  23704. std::condition_variable cv;
  23705. std::vector<std::string> received;
  23706. sse.on_message([&](const sse::SSEMessage &msg) {
  23707. std::lock_guard<std::mutex> lock(mutex);
  23708. received.push_back(msg.data);
  23709. cv.notify_all();
  23710. });
  23711. sse.set_max_reconnect_attempts(1);
  23712. sse.start_async();
  23713. {
  23714. std::unique_lock<std::mutex> lock(mutex);
  23715. cv.wait_for(lock, std::chrono::seconds(2),
  23716. [&] { return received.size() >= 3; });
  23717. }
  23718. sse.stop();
  23719. ASSERT_GE(received.size(), 3u);
  23720. EXPECT_EQ(received[0], "");
  23721. EXPECT_EQ(received[1], "\nhello");
  23722. EXPECT_EQ(received[2], "");
  23723. }
  23724. // Test: Auto-reconnect after server disconnection
  23725. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23726. std::atomic<int> connection_count{0};
  23727. std::atomic<int> message_count{0};
  23728. // Endpoint that sends one event and closes, forcing reconnect
  23729. server_->Get("/reconnect-test",
  23730. [&connection_count](const Request &, Response &res) {
  23731. connection_count.fetch_add(1);
  23732. res.set_chunked_content_provider(
  23733. "text/event-stream", [](size_t offset, DataSink &sink) {
  23734. if (offset == 0) {
  23735. std::string event = "data: hello\n\n";
  23736. sink.write(event.data(), event.size());
  23737. }
  23738. return false; // Close connection after sending
  23739. });
  23740. });
  23741. Client client("localhost", get_port());
  23742. sse::SSEClient sse(client, "/reconnect-test");
  23743. sse.on_message([&message_count](const sse::SSEMessage &) {
  23744. message_count.fetch_add(1);
  23745. });
  23746. sse.set_reconnect_interval(100);
  23747. sse.set_max_reconnect_attempts(3);
  23748. sse.start_async();
  23749. // Wait long enough for multiple reconnects
  23750. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23751. sse.stop();
  23752. // Should have connected multiple times (initial + reconnects)
  23753. EXPECT_GE(connection_count.load(), 2);
  23754. // Should have received messages from multiple connections
  23755. EXPECT_GE(message_count.load(), 2);
  23756. }
  23757. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23758. std::atomic<int> connection_count{0};
  23759. // Neither Content-Length nor chunked: the close ends the stream
  23760. server_->Get("/close-delimited",
  23761. [&connection_count](const Request &, Response &res) {
  23762. connection_count.fetch_add(1);
  23763. res.set_content_provider(
  23764. "text/event-stream", [](size_t offset, DataSink &sink) {
  23765. if (offset == 0) {
  23766. std::string event = "data: hello\n\n";
  23767. sink.write(event.data(), event.size());
  23768. } else {
  23769. sink.done();
  23770. }
  23771. return true;
  23772. });
  23773. });
  23774. Client client("localhost", get_port());
  23775. sse::SSEClient sse(client, "/close-delimited");
  23776. std::atomic<int> error_count{0};
  23777. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23778. sse.set_reconnect_interval(100);
  23779. sse.start_async();
  23780. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23781. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23782. }
  23783. sse.stop();
  23784. // Reconnects as after any end of the stream, but reports no error
  23785. EXPECT_GE(connection_count.load(), 2);
  23786. EXPECT_EQ(0, error_count.load());
  23787. }
  23788. // Test: A retry field of all ASCII digits sets the reconnection time
  23789. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23790. std::mutex mutex;
  23791. std::condition_variable cv;
  23792. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23793. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23794. {
  23795. std::lock_guard<std::mutex> lock(mutex);
  23796. connected_at.push_back(std::chrono::steady_clock::now());
  23797. cv.notify_all();
  23798. }
  23799. res.set_chunked_content_provider(
  23800. "text/event-stream", [](size_t offset, DataSink &sink) {
  23801. if (offset == 0) {
  23802. std::string event = "retry: 0\ndata: hello\n\n";
  23803. sink.write(event.data(), event.size());
  23804. }
  23805. return false;
  23806. });
  23807. });
  23808. Client client("localhost", get_port());
  23809. sse::SSEClient sse(client, "/zero-retry");
  23810. sse.set_reconnect_interval(10000);
  23811. sse.start_async();
  23812. {
  23813. std::unique_lock<std::mutex> lock(mutex);
  23814. cv.wait_for(lock, std::chrono::seconds(5),
  23815. [&] { return connected_at.size() >= 2; });
  23816. }
  23817. sse.stop();
  23818. // The server-supplied interval is applied, but never below 100ms, so
  23819. // "retry: 0" does not cause a busy reconnect loop
  23820. std::lock_guard<std::mutex> lock(mutex);
  23821. ASSERT_GE(connected_at.size(), 2u);
  23822. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23823. connected_at[1] - connected_at[0])
  23824. .count();
  23825. EXPECT_GE(interval_ms, 100);
  23826. }
  23827. // Test: Last-Event-ID sent on reconnect
  23828. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23829. std::atomic<int> connection_count{0};
  23830. std::vector<std::string> received_last_event_ids;
  23831. std::mutex id_mutex;
  23832. // Endpoint that checks Last-Event-ID header and sends event with ID
  23833. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23834. int conn = connection_count.fetch_add(1);
  23835. // Capture the Last-Event-ID header from each connection
  23836. {
  23837. std::lock_guard<std::mutex> lock(id_mutex);
  23838. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23839. }
  23840. res.set_chunked_content_provider(
  23841. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23842. if (offset == 0) {
  23843. std::string event =
  23844. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23845. sink.write(event.data(), event.size());
  23846. }
  23847. return false;
  23848. });
  23849. });
  23850. Client client("localhost", get_port());
  23851. sse::SSEClient sse(client, "/reconnect-with-id");
  23852. sse.set_reconnect_interval(100);
  23853. sse.set_max_reconnect_attempts(3);
  23854. sse.start_async();
  23855. // Wait for at least 2 connections
  23856. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23857. sse.stop();
  23858. // Verify behavior
  23859. std::lock_guard<std::mutex> lock(id_mutex);
  23860. EXPECT_GE(received_last_event_ids.size(), 2u);
  23861. // First connection should have no Last-Event-ID
  23862. if (!received_last_event_ids.empty()) {
  23863. EXPECT_EQ(received_last_event_ids[0], "");
  23864. }
  23865. // Second connection should have Last-Event-ID from first connection
  23866. if (received_last_event_ids.size() >= 2) {
  23867. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23868. }
  23869. }
  23870. // Test: set_headers updates headers used on reconnect
  23871. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23872. std::vector<std::string> received_tokens;
  23873. std::mutex token_mutex;
  23874. // Endpoint that captures Authorization header
  23875. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23876. {
  23877. std::lock_guard<std::mutex> lock(token_mutex);
  23878. received_tokens.push_back(req.get_header_value("Authorization"));
  23879. }
  23880. res.set_chunked_content_provider(
  23881. "text/event-stream", [](size_t offset, DataSink &sink) {
  23882. if (offset == 0) {
  23883. std::string event = "data: hello\n\n";
  23884. sink.write(event.data(), event.size());
  23885. }
  23886. return false; // Close connection to trigger reconnect
  23887. });
  23888. });
  23889. Client client("localhost", get_port());
  23890. Headers headers = {{"Authorization", "Bearer old-token"}};
  23891. sse::SSEClient sse(client, "/auth-check", headers);
  23892. // Update headers on each successful connection
  23893. sse.on_open(
  23894. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23895. sse.set_reconnect_interval(100);
  23896. sse.set_max_reconnect_attempts(3);
  23897. sse.start_async();
  23898. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23899. sse.stop();
  23900. std::lock_guard<std::mutex> lock(token_mutex);
  23901. ASSERT_GE(received_tokens.size(), 2u);
  23902. // First connection uses original header
  23903. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23904. // Second connection uses updated header from set_headers
  23905. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23906. }
  23907. // Test: 401 allows reconnection (so on_error can refresh headers)
  23908. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23909. std::atomic<int> connection_count{0};
  23910. // Endpoint: returns 401 on first attempt, 200 on second
  23911. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23912. int conn = connection_count.fetch_add(1);
  23913. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23914. res.status = StatusCode::Unauthorized_401;
  23915. res.set_content("Unauthorized", "text/plain");
  23916. return;
  23917. }
  23918. res.set_chunked_content_provider(
  23919. "text/event-stream", [](size_t offset, DataSink &sink) {
  23920. if (offset == 0) {
  23921. std::string event = "data: authenticated\n\n";
  23922. sink.write(event.data(), event.size());
  23923. }
  23924. return false;
  23925. });
  23926. });
  23927. Client client("localhost", get_port());
  23928. Headers headers = {{"Authorization", "Bearer expired"}};
  23929. sse::SSEClient sse(client, "/auth-retry", headers);
  23930. std::atomic<bool> message_received{false};
  23931. // Refresh token on error
  23932. sse.on_error(
  23933. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23934. sse.on_message([&](const sse::SSEMessage &msg) {
  23935. if (msg.data == "authenticated") { message_received.store(true); }
  23936. });
  23937. sse.set_reconnect_interval(100);
  23938. sse.set_max_reconnect_attempts(3);
  23939. sse.start_async();
  23940. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23941. sse.stop();
  23942. // Should have reconnected after 401 and succeeded with new token
  23943. EXPECT_GE(connection_count.load(), 2);
  23944. EXPECT_TRUE(message_received.load());
  23945. }
  23946. TEST(Issue2318Test, EmptyHostString) {
  23947. {
  23948. httplib::Client cli_empty("", PORT);
  23949. auto res = cli_empty.Get("/");
  23950. ASSERT_FALSE(res);
  23951. EXPECT_EQ(httplib::Error::Connection, res.error());
  23952. }
  23953. {
  23954. httplib::Client cli(" ", PORT);
  23955. auto res = cli.Get("/");
  23956. ASSERT_FALSE(res);
  23957. EXPECT_EQ(httplib::Error::Connection, res.error());
  23958. }
  23959. }
  23960. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23961. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23962. Server svr;
  23963. // Set a small payload limit (1KB)
  23964. svr.set_payload_max_length(1024);
  23965. svr.Post("/test", [&](const Request &req, Response &res) {
  23966. res.set_content("Body size: " + std::to_string(req.body.size()),
  23967. "text/plain");
  23968. });
  23969. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23970. auto se = detail::scope_exit([&] {
  23971. svr.stop();
  23972. listen_thread.join();
  23973. });
  23974. svr.wait_until_ready();
  23975. // Create data that compresses well but exceeds limit when decompressed
  23976. // 8KB of repeated null bytes compresses to a very small size
  23977. std::string original_data(8 * 1024, '\0');
  23978. // Compress the data using gzip
  23979. std::string compressed_data;
  23980. detail::gzip_compressor compressor;
  23981. compressor.compress(original_data.data(), original_data.size(), true,
  23982. [&](const char *data, size_t size) {
  23983. compressed_data.append(data, size);
  23984. return true;
  23985. });
  23986. // Verify compression worked (compressed should be much smaller)
  23987. ASSERT_LT(compressed_data.size(), original_data.size());
  23988. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23989. // Send compressed data with Content-Encoding: gzip
  23990. Client cli(HOST, PORT);
  23991. Headers headers = {{"Content-Encoding", "gzip"}};
  23992. auto res =
  23993. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23994. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23996. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23997. }
  23998. #endif
  23999. // ============================================================================
  24000. // OpenSSL-Specific Tests
  24001. // ============================================================================
  24002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24003. X509 *readCertificate(const std::string &strFileName) {
  24004. std::ifstream inStream(strFileName);
  24005. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24006. std::istreambuf_iterator<char>());
  24007. if (strCertPEM.empty()) return (nullptr);
  24008. BIO *pbCert = BIO_new(BIO_s_mem());
  24009. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24010. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24011. BIO_free(pbCert);
  24012. return (pCert);
  24013. }
  24014. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24015. std::ifstream inStream(strFileName);
  24016. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24017. std::istreambuf_iterator<char>());
  24018. if (strPrivateKeyPEM.empty()) return (nullptr);
  24019. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24020. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24021. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24022. BIO_free(pbPrivKey);
  24023. return (pPrivateKey);
  24024. }
  24025. TEST(BindServerTest, UpdateCerts) {
  24026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24027. int port = svr.bind_to_any_port("0.0.0.0");
  24028. ASSERT_TRUE(svr.is_valid());
  24029. ASSERT_TRUE(port > 0);
  24030. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24031. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24032. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24033. ASSERT_TRUE(cert != nullptr);
  24034. ASSERT_TRUE(ca_cert != nullptr);
  24035. ASSERT_TRUE(key != nullptr);
  24036. X509_STORE *cert_store = X509_STORE_new();
  24037. X509_STORE_add_cert(cert_store, ca_cert);
  24038. // svr.update_certs(cert, key, cert_store); // deprecated
  24039. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24040. CLIENT_CA_CERT_FILE);
  24041. ASSERT_TRUE(svr.is_valid());
  24042. svr.stop();
  24043. X509_STORE_free(cert_store);
  24044. X509_free(cert);
  24045. X509_free(ca_cert);
  24046. EVP_PKEY_free(key);
  24047. }
  24048. // Test that update_certs() updates client CA list correctly
  24049. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24050. // Start with file-based constructor
  24051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24052. ASSERT_TRUE(svr.is_valid());
  24053. // Initially no client CA list should be set
  24054. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24055. ASSERT_TRUE(ssl_ctx != nullptr);
  24056. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24057. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24058. // Now update with client CA (PEM string)
  24059. std::string cert_pem, key_pem, ca_pem;
  24060. read_file(SERVER_CERT_FILE, cert_pem);
  24061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24063. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24064. ASSERT_TRUE(svr.is_valid());
  24065. // Now client CA list should be set
  24066. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24067. ASSERT_TRUE(ca_list_after != nullptr);
  24068. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24069. }
  24070. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24071. // Test that the file-path SSLServer constructor properly sets the client CA
  24072. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24074. ASSERT_TRUE(svr.is_valid());
  24075. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24076. ASSERT_TRUE(ssl_ctx != nullptr);
  24077. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24078. ASSERT_TRUE(ca_list != nullptr);
  24079. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24080. }
  24081. #endif
  24082. // ============================================================================
  24083. // MbedTLS-Specific Tests
  24084. // ============================================================================
  24085. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24086. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24087. using namespace httplib::tls;
  24088. // Track if callback was invoked
  24089. bool callback_invoked = false;
  24090. // The callback receives void* ctx which is actually MbedTlsContext*
  24091. // We can access the mbedtls_ssl_config via the context
  24092. auto setup_callback = [&callback_invoked](void *ctx) {
  24093. callback_invoked = true;
  24094. // Cast to MbedTlsContext* to access the ssl config
  24095. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24096. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24097. // Use static variables to hold certificate data (simplified for test)
  24098. static mbedtls_x509_crt own_cert;
  24099. static mbedtls_pk_context own_key;
  24100. static mbedtls_x509_crt ca_chain;
  24101. static bool initialized = false;
  24102. if (!initialized) {
  24103. mbedtls_x509_crt_init(&own_cert);
  24104. mbedtls_pk_init(&own_key);
  24105. mbedtls_x509_crt_init(&ca_chain);
  24106. // Load server certificate
  24107. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24108. return false;
  24109. }
  24110. // Load server private key.
  24111. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24112. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24113. #if MBEDTLS_VERSION_MAJOR == 3
  24114. ,
  24115. mbedtls_ctr_drbg_random, nullptr
  24116. #endif
  24117. ) != 0) {
  24118. return false;
  24119. }
  24120. // Load CA chain for client verification
  24121. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24122. return false;
  24123. }
  24124. initialized = true;
  24125. }
  24126. // Configure the SSL config
  24127. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24128. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24129. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24130. // Set minimum TLS version using mbedTLS native API
  24131. #if MBEDTLS_VERSION_MAJOR >= 3
  24132. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24133. #else
  24134. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24135. MBEDTLS_SSL_MINOR_VERSION_3);
  24136. #endif
  24137. return true;
  24138. };
  24139. SSLServer svr(setup_callback);
  24140. ASSERT_TRUE(svr.is_valid());
  24141. ASSERT_TRUE(callback_invoked);
  24142. svr.Get("/test", [&](const Request &req, Response &res) {
  24143. res.set_content("test", "text/plain");
  24144. auto cert = req.peer_cert();
  24145. ASSERT_TRUE(static_cast<bool>(cert));
  24146. auto common_name = cert.subject_cn();
  24147. EXPECT_EQ("Common Name", common_name);
  24148. });
  24149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24150. auto se = detail::scope_exit([&] {
  24151. svr.stop();
  24152. t.join();
  24153. ASSERT_FALSE(svr.is_running());
  24154. });
  24155. svr.wait_until_ready();
  24156. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24157. cli.enable_server_certificate_verification(false);
  24158. cli.set_connection_timeout(30);
  24159. auto res = cli.Get("/test");
  24160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24161. ASSERT_EQ(StatusCode::OK_200, res->status);
  24162. }
  24163. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24164. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24165. // keep-alive SSL session, which reads through that config in
  24166. // mbedtls_ssl_close_notify.
  24167. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24169. ASSERT_TRUE(svr.is_valid());
  24170. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24171. res.set_content("test", "text/plain");
  24172. });
  24173. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24174. auto se = detail::scope_exit([&] {
  24175. svr.stop();
  24176. t.join();
  24177. ASSERT_FALSE(svr.is_running());
  24178. });
  24179. svr.wait_until_ready();
  24180. {
  24181. SSLClient cli(HOST, PORT);
  24182. cli.enable_server_certificate_verification(false);
  24183. cli.set_keep_alive(true);
  24184. auto res = cli.Get("/test");
  24185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24186. ASSERT_EQ(StatusCode::OK_200, res->status);
  24187. // cli is destructed here with the keep-alive SSL session still open.
  24188. }
  24189. }
  24190. #endif
  24191. // WebSocket Tests
  24192. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24193. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24194. // defining the meaning of these bits has been negotiated.
  24195. auto make_frame = [](uint8_t first_byte) {
  24196. std::string frame;
  24197. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24198. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24199. frame += "Hello";
  24200. return frame;
  24201. };
  24202. // RSV1 set (0x40)
  24203. {
  24204. detail::BufferStream strm;
  24205. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24206. ws::Opcode opcode;
  24207. std::string payload;
  24208. bool fin;
  24209. EXPECT_EQ(
  24210. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24211. ws::impl::FrameRead::Fail);
  24212. }
  24213. // RSV2 set (0x20)
  24214. {
  24215. detail::BufferStream strm;
  24216. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24217. ws::Opcode opcode;
  24218. std::string payload;
  24219. bool fin;
  24220. EXPECT_EQ(
  24221. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24222. ws::impl::FrameRead::Fail);
  24223. }
  24224. // RSV3 set (0x10)
  24225. {
  24226. detail::BufferStream strm;
  24227. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24228. ws::Opcode opcode;
  24229. std::string payload;
  24230. bool fin;
  24231. EXPECT_EQ(
  24232. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24233. ws::impl::FrameRead::Fail);
  24234. }
  24235. // No RSV bits set - should succeed
  24236. {
  24237. detail::BufferStream strm;
  24238. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24239. ws::Opcode opcode;
  24240. std::string payload;
  24241. bool fin;
  24242. EXPECT_EQ(
  24243. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24244. ws::impl::FrameRead::Ok);
  24245. EXPECT_EQ(ws::Opcode::Text, opcode);
  24246. EXPECT_EQ("Hello", payload);
  24247. EXPECT_TRUE(fin);
  24248. }
  24249. }
  24250. TEST(WebSocketTest, ControlFrameValidation) {
  24251. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24252. // payload length <= 125.
  24253. // Ping with FIN=0 - must be rejected
  24254. {
  24255. detail::BufferStream strm;
  24256. std::string frame;
  24257. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24258. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24259. strm.write(frame.data(), frame.size());
  24260. ws::Opcode opcode;
  24261. std::string payload;
  24262. bool fin;
  24263. EXPECT_EQ(
  24264. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24265. ws::impl::FrameRead::Fail);
  24266. }
  24267. // Close with FIN=0 - must be rejected
  24268. {
  24269. detail::BufferStream strm;
  24270. std::string frame;
  24271. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24272. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24273. strm.write(frame.data(), frame.size());
  24274. ws::Opcode opcode;
  24275. std::string payload;
  24276. bool fin;
  24277. EXPECT_EQ(
  24278. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24279. ws::impl::FrameRead::Fail);
  24280. }
  24281. // Ping with payload_len=126 (extended length) - must be rejected
  24282. {
  24283. detail::BufferStream strm;
  24284. std::string frame;
  24285. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24286. frame += static_cast<char>(126); // payload_len=126 (>125)
  24287. frame += static_cast<char>(0x00); // extended length high byte
  24288. frame += static_cast<char>(126); // extended length low byte
  24289. frame += std::string(126, 'x');
  24290. strm.write(frame.data(), frame.size());
  24291. ws::Opcode opcode;
  24292. std::string payload;
  24293. bool fin;
  24294. EXPECT_EQ(
  24295. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24296. ws::impl::FrameRead::Fail);
  24297. }
  24298. // Ping with FIN=1 and payload_len=125 - should succeed
  24299. {
  24300. detail::BufferStream strm;
  24301. std::string frame;
  24302. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24303. frame += static_cast<char>(125); // payload_len=125
  24304. frame += std::string(125, 'x');
  24305. strm.write(frame.data(), frame.size());
  24306. ws::Opcode opcode;
  24307. std::string payload;
  24308. bool fin;
  24309. EXPECT_EQ(
  24310. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24311. ws::impl::FrameRead::Ok);
  24312. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24313. EXPECT_EQ(125u, payload.size());
  24314. EXPECT_TRUE(fin);
  24315. }
  24316. }
  24317. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24318. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24319. // length MUST be 0.
  24320. // MSB set - must be rejected
  24321. {
  24322. detail::BufferStream strm;
  24323. std::string frame;
  24324. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24325. frame += static_cast<char>(127); // 64-bit extended length
  24326. frame += static_cast<char>(0x80); // MSB set (invalid)
  24327. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24328. strm.write(frame.data(), frame.size());
  24329. ws::Opcode opcode;
  24330. std::string payload;
  24331. bool fin;
  24332. EXPECT_EQ(
  24333. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24334. ws::impl::FrameRead::Fail);
  24335. }
  24336. // MSB clear - should pass length parsing (will be rejected by max_len,
  24337. // but that's a different check; use a small length to verify)
  24338. {
  24339. detail::BufferStream strm;
  24340. std::string frame;
  24341. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24342. frame += static_cast<char>(127); // 64-bit extended length
  24343. frame += std::string(7, '\0'); // high bytes = 0
  24344. frame += static_cast<char>(0x03); // length = 3
  24345. frame += "abc";
  24346. strm.write(frame.data(), frame.size());
  24347. ws::Opcode opcode;
  24348. std::string payload;
  24349. bool fin;
  24350. EXPECT_EQ(
  24351. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24352. ws::impl::FrameRead::Ok);
  24353. EXPECT_EQ(ws::Opcode::Text, opcode);
  24354. EXPECT_EQ("abc", payload);
  24355. }
  24356. }
  24357. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24358. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24359. // Valid UTF-8
  24360. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24361. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24362. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24363. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24364. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24365. // Invalid UTF-8
  24366. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24367. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24368. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24369. EXPECT_FALSE(
  24370. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24371. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24372. }
  24373. TEST(WebSocketTest, ConnectAndDisconnect) {
  24374. Server svr;
  24375. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24376. std::string msg;
  24377. while (ws.read(msg)) {}
  24378. });
  24379. auto port = svr.bind_to_any_port(HOST);
  24380. std::thread t([&]() { svr.listen_after_bind(); });
  24381. svr.wait_until_ready();
  24382. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24383. auto res = client.connect();
  24384. ASSERT_TRUE(res);
  24385. EXPECT_EQ(Error::Success, res.error());
  24386. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24387. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24388. EXPECT_TRUE(client.is_open());
  24389. client.close();
  24390. EXPECT_FALSE(client.is_open());
  24391. svr.stop();
  24392. t.join();
  24393. }
  24394. TEST(WebSocketTest, ValidURL) {
  24395. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24396. EXPECT_TRUE(ws1.is_valid());
  24397. ws::WebSocketClient ws2("ws://example.com/path");
  24398. EXPECT_TRUE(ws2.is_valid());
  24399. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24400. EXPECT_TRUE(ws3.is_valid());
  24401. #ifdef CPPHTTPLIB_SSL_ENABLED
  24402. ws::WebSocketClient wss1("wss://example.com/path");
  24403. EXPECT_TRUE(wss1.is_valid());
  24404. ws::WebSocketClient wss2("wss://example.com:443/path");
  24405. EXPECT_TRUE(wss2.is_valid());
  24406. #endif
  24407. }
  24408. TEST(WebSocketTest, InvalidURL) {
  24409. // No scheme
  24410. ws::WebSocketClient ws1("localhost:8080/path");
  24411. EXPECT_FALSE(ws1.is_valid());
  24412. // No path
  24413. ws::WebSocketClient ws2("ws://localhost:8080");
  24414. EXPECT_FALSE(ws2.is_valid());
  24415. // Empty string
  24416. ws::WebSocketClient ws3("");
  24417. EXPECT_FALSE(ws3.is_valid());
  24418. // Missing host
  24419. ws::WebSocketClient ws4("ws://:8080/path");
  24420. EXPECT_FALSE(ws4.is_valid());
  24421. // Port number overflow — should not crash
  24422. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24423. EXPECT_FALSE(ws5.is_valid());
  24424. // Port out of range
  24425. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24426. EXPECT_FALSE(ws6.is_valid());
  24427. }
  24428. TEST(WebSocketTest, UnsupportedScheme) {
  24429. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24430. ws::WebSocketClient ws1("http://localhost:8080/path");
  24431. EXPECT_FALSE(ws1.is_valid());
  24432. ws::WebSocketClient ws2("https://localhost:8080/path");
  24433. EXPECT_FALSE(ws2.is_valid());
  24434. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24435. EXPECT_FALSE(ws3.is_valid());
  24436. #else
  24437. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24438. std::invalid_argument);
  24439. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24440. std::invalid_argument);
  24441. #endif
  24442. }
  24443. TEST(WebSocketTest, ConnectWhenInvalid) {
  24444. ws::WebSocketClient ws("not a valid url");
  24445. EXPECT_FALSE(ws.is_valid());
  24446. auto res = ws.connect();
  24447. EXPECT_FALSE(res);
  24448. EXPECT_EQ(Error::Connection, res.error());
  24449. EXPECT_EQ(-1, res.status());
  24450. }
  24451. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24452. // Grab a port that is free, then close it again so nothing listens there
  24453. Server svr;
  24454. auto port = svr.bind_to_any_port(HOST);
  24455. svr.stop();
  24456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24457. auto res = client.connect();
  24458. ASSERT_FALSE(res);
  24459. EXPECT_EQ(Error::Connection, res.error());
  24460. EXPECT_EQ(-1, res.status());
  24461. }
  24462. TEST(WebSocketTest, DefaultPort) {
  24463. ws::WebSocketClient ws1("ws://example.com/path");
  24464. EXPECT_TRUE(ws1.is_valid());
  24465. // ws:// defaults to port 80 (verified by successful parse)
  24466. #ifdef CPPHTTPLIB_SSL_ENABLED
  24467. ws::WebSocketClient ws2("wss://example.com/path");
  24468. EXPECT_TRUE(ws2.is_valid());
  24469. // wss:// defaults to port 443 (verified by successful parse)
  24470. #endif
  24471. }
  24472. TEST(WebSocketTest, IPv6LiteralAddress) {
  24473. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24474. EXPECT_TRUE(ws1.is_valid());
  24475. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24476. EXPECT_TRUE(ws2.is_valid());
  24477. }
  24478. TEST(WebSocketTest, ComplexPath) {
  24479. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24480. EXPECT_TRUE(ws1.is_valid());
  24481. ws::WebSocketClient ws2("ws://localhost:8080/");
  24482. EXPECT_TRUE(ws2.is_valid());
  24483. }
  24484. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24485. Server svr;
  24486. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24487. std::string msg;
  24488. while (ws.read(msg)) {}
  24489. });
  24490. auto port = svr.bind_to_any_port(HOST);
  24491. std::thread t([&]() { svr.listen_after_bind(); });
  24492. svr.wait_until_ready();
  24493. auto another_host = "example.com";
  24494. auto wrong_ip = "192.0.2.1";
  24495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24496. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24497. ASSERT_TRUE(client.connect());
  24498. EXPECT_TRUE(client.is_open());
  24499. client.close();
  24500. svr.stop();
  24501. t.join();
  24502. }
  24503. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24504. Server svr;
  24505. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24506. std::string msg;
  24507. while (ws.read(msg)) {}
  24508. });
  24509. auto port = svr.bind_to_any_port(HOST);
  24510. std::thread t([&]() { svr.listen_after_bind(); });
  24511. svr.wait_until_ready();
  24512. auto wrong_ip = "192.0.2.1";
  24513. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24514. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24515. client.set_connection_timeout(1);
  24516. client.set_read_timeout(1);
  24517. client.set_write_timeout(1);
  24518. EXPECT_FALSE(client.connect());
  24519. EXPECT_FALSE(client.is_open());
  24520. svr.stop();
  24521. t.join();
  24522. }
  24523. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24524. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24525. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24526. // (RFC 6761) is only a map key and the Host header value.
  24527. auto host = "target.invalid";
  24528. Server svr;
  24529. std::string received_host;
  24530. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24531. received_host = req.get_header_value("Host");
  24532. std::string msg;
  24533. while (ws.read(msg)) {}
  24534. });
  24535. auto port = svr.bind_to_any_port(HOST);
  24536. std::thread t([&]() { svr.listen_after_bind(); });
  24537. // ASSERT_* below returns from the test body, which would leave t joinable
  24538. // and make ~thread call std::terminate.
  24539. auto se = detail::scope_exit([&] {
  24540. svr.stop();
  24541. if (t.joinable()) { t.join(); }
  24542. });
  24543. svr.wait_until_ready();
  24544. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24545. std::to_string(port) + "/ws");
  24546. client.set_direct_hostname_addr_map({{host, HOST}});
  24547. ASSERT_TRUE(client.connect());
  24548. EXPECT_TRUE(client.is_open());
  24549. client.close();
  24550. svr.stop();
  24551. t.join();
  24552. // The mapping only redirects the connection; the identity stays host_.
  24553. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24554. }
  24555. class WebSocketIntegrationTest : public ::testing::Test {
  24556. protected:
  24557. void SetUp() override {
  24558. server_ = httplib::detail::make_unique<Server>();
  24559. setup_server();
  24560. start_server();
  24561. }
  24562. void TearDown() override {
  24563. server_->stop();
  24564. if (server_thread_.joinable()) { server_thread_.join(); }
  24565. }
  24566. void setup_server() {
  24567. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24568. std::string msg;
  24569. ws::ReadResult ret;
  24570. while ((ret = ws.read(msg))) {
  24571. if (ret == ws::Binary) {
  24572. ws.send(msg.data(), msg.size());
  24573. } else {
  24574. ws.send(msg);
  24575. }
  24576. }
  24577. });
  24578. server_->WebSocket("/ws-echo-string",
  24579. [](const Request &, ws::WebSocket &ws) {
  24580. std::string msg;
  24581. while (ws.read(msg)) {
  24582. ws.send("echo: " + msg);
  24583. }
  24584. });
  24585. server_->WebSocket(
  24586. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24587. // Echo back request metadata
  24588. ws.send("path:" + req.path);
  24589. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24590. std::string msg;
  24591. while (ws.read(msg)) {}
  24592. });
  24593. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24594. std::string msg;
  24595. ws.read(msg); // wait for a message
  24596. ws.close();
  24597. });
  24598. server_->WebSocket("/ws-close-status",
  24599. [](const Request &, ws::WebSocket &ws) {
  24600. std::string msg;
  24601. ws.read(msg); // wait for a message
  24602. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24603. });
  24604. server_->WebSocket(
  24605. "/ws-subprotocol",
  24606. [](const Request &, ws::WebSocket &ws) {
  24607. std::string msg;
  24608. while (ws.read(msg)) {
  24609. ws.send(msg);
  24610. }
  24611. },
  24612. [](const std::vector<std::string> &protocols) -> std::string {
  24613. for (const auto &p : protocols) {
  24614. if (p == "graphql-ws") { return p; }
  24615. }
  24616. return "";
  24617. });
  24618. server_->WebSocket(
  24619. "/ws-subprotocol-unoffered",
  24620. [](const Request &, ws::WebSocket &ws) {
  24621. std::string msg;
  24622. while (ws.read(msg)) {
  24623. ws.send(msg);
  24624. }
  24625. },
  24626. [](const std::vector<std::string> &) -> std::string {
  24627. return "admin";
  24628. });
  24629. }
  24630. void start_server() {
  24631. port_ = server_->bind_to_any_port(HOST);
  24632. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24633. server_->wait_until_ready();
  24634. }
  24635. std::unique_ptr<Server> server_;
  24636. std::thread server_thread_;
  24637. int port_ = 0;
  24638. };
  24639. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24640. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24641. "/ws-echo");
  24642. ASSERT_TRUE(client.connect());
  24643. ASSERT_TRUE(client.is_open());
  24644. ASSERT_TRUE(client.send("Hello WebSocket"));
  24645. std::string msg;
  24646. EXPECT_EQ(ws::Text, client.read(msg));
  24647. EXPECT_EQ("Hello WebSocket", msg);
  24648. client.close();
  24649. }
  24650. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24651. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24652. "/ws-echo");
  24653. ASSERT_TRUE(client.connect());
  24654. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24655. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24656. std::string msg;
  24657. EXPECT_EQ(ws::Binary, client.read(msg));
  24658. EXPECT_EQ(binary_data, msg);
  24659. client.close();
  24660. }
  24661. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24663. "/ws-echo");
  24664. ASSERT_TRUE(client.connect());
  24665. for (int i = 0; i < 10; i++) {
  24666. auto text = "message " + std::to_string(i);
  24667. ASSERT_TRUE(client.send(text));
  24668. std::string msg;
  24669. ASSERT_TRUE(client.read(msg));
  24670. EXPECT_EQ(text, msg);
  24671. }
  24672. client.close();
  24673. }
  24674. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24675. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24676. "/ws-close");
  24677. ASSERT_TRUE(client.connect());
  24678. // Send a message to trigger the server to close
  24679. ASSERT_TRUE(client.send("trigger close"));
  24680. // The server will close, so read should return false
  24681. std::string msg;
  24682. EXPECT_FALSE(client.read(msg));
  24683. EXPECT_FALSE(client.is_open());
  24684. }
  24685. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24687. "/ws-echo");
  24688. ASSERT_TRUE(client.connect());
  24689. // 128KB message
  24690. std::string large_data(128 * 1024, 'X');
  24691. ASSERT_TRUE(client.send(large_data));
  24692. std::string msg;
  24693. ASSERT_TRUE(client.read(msg));
  24694. EXPECT_EQ(large_data, msg);
  24695. client.close();
  24696. }
  24697. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24699. "/ws-echo");
  24700. ASSERT_TRUE(client.connect());
  24701. const int num_threads = 4;
  24702. std::vector<std::thread> threads;
  24703. std::atomic<int> send_count{0};
  24704. for (int t = 0; t < num_threads; t++) {
  24705. threads.emplace_back([&client, &send_count, t]() {
  24706. for (int i = 0; i < 5; i++) {
  24707. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24708. if (client.send(text)) { send_count++; }
  24709. }
  24710. });
  24711. }
  24712. for (auto &th : threads) {
  24713. th.join();
  24714. }
  24715. int received = 0;
  24716. std::string msg;
  24717. while (received < send_count.load()) {
  24718. if (!client.read(msg)) { break; }
  24719. received++;
  24720. }
  24721. EXPECT_EQ(send_count.load(), received);
  24722. client.close();
  24723. }
  24724. TEST_F(WebSocketIntegrationTest, ReadString) {
  24725. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24726. "/ws-echo-string");
  24727. ASSERT_TRUE(client.connect());
  24728. ASSERT_TRUE(client.send("hello"));
  24729. std::string msg;
  24730. ASSERT_TRUE(client.read(msg));
  24731. EXPECT_EQ("echo: hello", msg);
  24732. ASSERT_TRUE(client.send("world"));
  24733. ASSERT_TRUE(client.read(msg));
  24734. EXPECT_EQ("echo: world", msg);
  24735. client.close();
  24736. }
  24737. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24738. Headers headers = {{"X-Test-Header", "test-value"}};
  24739. ws::WebSocketClient client(
  24740. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24741. ASSERT_TRUE(client.connect());
  24742. std::string msg;
  24743. ASSERT_TRUE(client.read(msg));
  24744. EXPECT_EQ("path:/ws-request-info", msg);
  24745. ASSERT_TRUE(client.read(msg));
  24746. EXPECT_EQ("header:test-value", msg);
  24747. client.close();
  24748. }
  24749. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24751. "/ws-echo");
  24752. client.set_read_timeout(1, 0); // 1 second
  24753. ASSERT_TRUE(client.connect());
  24754. // Don't send anything — server echo handler waits for a message, so read()
  24755. // should time out. The connection survives it: nothing was consumed.
  24756. std::string msg;
  24757. EXPECT_EQ(client.read(msg), ws::Timeout);
  24758. EXPECT_TRUE(client.is_open());
  24759. // And it is still usable afterwards.
  24760. EXPECT_TRUE(client.send("after timeout"));
  24761. EXPECT_EQ(client.read(msg), ws::Text);
  24762. EXPECT_EQ(msg, "after timeout");
  24763. }
  24764. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24765. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24766. "/ws-echo");
  24767. client.set_read_timeout(1, 0);
  24768. ASSERT_TRUE(client.connect());
  24769. ASSERT_TRUE(client.send("first"));
  24770. std::string msg;
  24771. ASSERT_EQ(client.read(msg), ws::Text);
  24772. ASSERT_EQ(msg, "first");
  24773. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24774. // not be used with a read timeout: it would reprocess the previous message.
  24775. EXPECT_EQ(client.read(msg), ws::Timeout);
  24776. EXPECT_EQ(msg, "first");
  24777. }
  24778. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24780. "/ws-echo");
  24781. ASSERT_TRUE(client.connect());
  24782. // Setting it once the connection is open reaches the live stream, not just
  24783. // the seed for the next connect().
  24784. client.set_read_timeout(1, 0);
  24785. std::string msg;
  24786. EXPECT_EQ(client.read(msg), ws::Timeout);
  24787. EXPECT_TRUE(client.is_open());
  24788. }
  24789. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24791. "/ws-echo");
  24792. client.set_read_timeout(5, 0);
  24793. ASSERT_TRUE(client.connect());
  24794. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24795. // The server should reject it and close the connection.
  24796. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24797. client.send(oversized);
  24798. // The server's read() should have failed due to payload limit,
  24799. // so our read() should return false (connection closed).
  24800. std::string msg;
  24801. EXPECT_FALSE(client.read(msg));
  24802. }
  24803. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24804. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24805. "/ws-echo");
  24806. client.set_read_timeout(10, 0);
  24807. ASSERT_TRUE(client.connect());
  24808. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24809. // This should succeed.
  24810. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24811. ASSERT_TRUE(client.send(at_limit));
  24812. std::string msg;
  24813. ASSERT_TRUE(client.read(msg));
  24814. EXPECT_EQ(at_limit.size(), msg.size());
  24815. client.close();
  24816. }
  24817. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24818. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24819. "/nonexistent");
  24820. auto res = client.connect();
  24821. EXPECT_FALSE(res);
  24822. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24823. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24824. EXPECT_FALSE(client.is_open());
  24825. }
  24826. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24828. "/ws-echo");
  24829. ASSERT_TRUE(client.connect());
  24830. ASSERT_TRUE(client.send(""));
  24831. std::string msg;
  24832. EXPECT_EQ(ws::Text, client.read(msg));
  24833. EXPECT_EQ("", msg);
  24834. client.close();
  24835. }
  24836. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24837. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24838. "/ws-echo");
  24839. // First connection
  24840. ASSERT_TRUE(client.connect());
  24841. ASSERT_TRUE(client.send("first"));
  24842. std::string msg;
  24843. ASSERT_TRUE(client.read(msg));
  24844. EXPECT_EQ("first", msg);
  24845. client.close();
  24846. EXPECT_FALSE(client.is_open());
  24847. // Reconnect using the same client object
  24848. ASSERT_TRUE(client.connect());
  24849. ASSERT_TRUE(client.is_open());
  24850. ASSERT_TRUE(client.send("second"));
  24851. ASSERT_TRUE(client.read(msg));
  24852. EXPECT_EQ("second", msg);
  24853. client.close();
  24854. }
  24855. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24857. "/ws-close-status");
  24858. ASSERT_TRUE(client.connect());
  24859. // Trigger the server to close with GoingAway status
  24860. ASSERT_TRUE(client.send("trigger"));
  24861. // read() should return false after receiving the close frame
  24862. std::string msg;
  24863. EXPECT_FALSE(client.read(msg));
  24864. EXPECT_FALSE(client.is_open());
  24865. }
  24866. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24868. "/ws-echo");
  24869. ASSERT_TRUE(client.connect());
  24870. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24871. EXPECT_FALSE(client.is_open());
  24872. }
  24873. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24874. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24875. ws::WebSocketClient client(
  24876. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24877. ASSERT_TRUE(client.connect());
  24878. // Server should have selected graphql-ws
  24879. EXPECT_EQ("graphql-ws", client.subprotocol());
  24880. client.close();
  24881. }
  24882. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24883. Headers headers;
  24884. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24885. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24886. ws::WebSocketClient client(
  24887. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24888. ASSERT_TRUE(client.connect());
  24889. // The offer on the second field line counts too, so graphql-ws is selected
  24890. EXPECT_EQ("graphql-ws", client.subprotocol());
  24891. client.close();
  24892. }
  24893. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24894. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24895. ws::WebSocketClient client(
  24896. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24897. ASSERT_TRUE(client.connect());
  24898. // Server should not have selected any subprotocol
  24899. EXPECT_TRUE(client.subprotocol().empty());
  24900. client.close();
  24901. }
  24902. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24903. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24905. "/ws-subprotocol-unoffered",
  24906. headers);
  24907. ASSERT_TRUE(client.connect());
  24908. EXPECT_TRUE(client.subprotocol().empty());
  24909. client.close();
  24910. }
  24911. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24912. // Connect without requesting any subprotocol
  24913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24914. "/ws-subprotocol");
  24915. ASSERT_TRUE(client.connect());
  24916. EXPECT_TRUE(client.subprotocol().empty());
  24917. client.close();
  24918. }
  24919. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24921. "/ws-echo");
  24922. client.set_tcp_nodelay(true);
  24923. client.set_connection_timeout(3, 0);
  24924. bool socket_options_called = false;
  24925. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24926. ASSERT_TRUE(client.connect());
  24927. ASSERT_TRUE(client.is_open());
  24928. EXPECT_TRUE(socket_options_called);
  24929. ASSERT_TRUE(client.send("hello"));
  24930. std::string msg;
  24931. auto result = client.read(msg);
  24932. EXPECT_EQ(result, ws::ReadResult::Text);
  24933. EXPECT_EQ(msg, "hello");
  24934. client.close();
  24935. }
  24936. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24938. "/ws-echo");
  24939. client.set_connection_timeout(std::chrono::seconds(3));
  24940. client.set_write_timeout(std::chrono::seconds(3));
  24941. // A sub-second remainder exercises the seconds/microseconds split.
  24942. client.set_read_timeout(std::chrono::milliseconds(1500));
  24943. ASSERT_TRUE(client.connect());
  24944. auto start = std::chrono::steady_clock::now();
  24945. std::string msg;
  24946. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24947. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24948. std::chrono::steady_clock::now() - start)
  24949. .count();
  24950. // Above 1s so that dropping the microseconds half of the split fails here.
  24951. // Ignoring the setter altogether would not reach this line at all: a client
  24952. // waits forever by default.
  24953. EXPECT_GE(elapsed, 1400);
  24954. EXPECT_LT(elapsed, 30000);
  24955. }
  24956. #ifndef _WIN32
  24957. // A send() that times out after part of the data went out returns the count
  24958. // written so far. Every byte of the frame must still be sent, or the peer reads
  24959. // the next frame's header and payload as the rest of this one.
  24960. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24961. signal(SIGPIPE, SIG_IGN);
  24962. const std::string large(4 * 1024 * 1024, 'A');
  24963. std::atomic<bool> large_sent{false};
  24964. std::atomic<bool> small_sent{false};
  24965. Server svr;
  24966. svr.set_write_timeout(0, 500000);
  24967. svr.set_socket_options([](socket_t sock) {
  24968. int size = 8192;
  24969. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24970. reinterpret_cast<const char *>(&size), sizeof(size));
  24971. });
  24972. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24973. large_sent = ws.send(large.data(), large.size());
  24974. small_sent = ws.send("after");
  24975. std::string msg;
  24976. while (ws.read(msg)) {}
  24977. });
  24978. auto port = svr.bind_to_any_port(HOST);
  24979. std::thread t([&]() { svr.listen_after_bind(); });
  24980. auto se = detail::scope_exit([&] {
  24981. svr.stop();
  24982. t.join();
  24983. });
  24984. svr.wait_until_ready();
  24985. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24986. std::to_string(port) + "/ws");
  24987. client.set_read_timeout(5);
  24988. client.set_socket_options([](socket_t sock) {
  24989. int size = 8192;
  24990. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24991. reinterpret_cast<const char *>(&size), sizeof(size));
  24992. });
  24993. ASSERT_TRUE(client.connect());
  24994. // Outlast the server's write timeout, then drain.
  24995. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24996. std::string msg;
  24997. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24998. EXPECT_TRUE(msg == large);
  24999. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25000. EXPECT_EQ("after", msg);
  25001. EXPECT_TRUE(large_sent);
  25002. EXPECT_TRUE(small_sent);
  25003. client.close();
  25004. }
  25005. // A send() that fails partway leaves a frame on the wire whose header announces
  25006. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25007. // as the rest of it and a later payload's bytes as a frame of their own.
  25008. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25009. signal(SIGPIPE, SIG_IGN);
  25010. const std::string large(4 * 1024 * 1024, 'A');
  25011. std::atomic<bool> large_sent{true};
  25012. std::atomic<bool> open_after_failure{true};
  25013. std::atomic<bool> handler_done{false};
  25014. Server svr;
  25015. svr.set_write_timeout(0, 200000);
  25016. svr.set_socket_options([](socket_t sock) {
  25017. int size = 8192;
  25018. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25019. reinterpret_cast<const char *>(&size), sizeof(size));
  25020. });
  25021. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25022. large_sent = ws.send(large.data(), large.size());
  25023. open_after_failure = ws.is_open();
  25024. handler_done = true;
  25025. });
  25026. auto port = svr.bind_to_any_port(HOST);
  25027. std::thread t([&]() { svr.listen_after_bind(); });
  25028. auto se = detail::scope_exit([&] {
  25029. svr.stop();
  25030. t.join();
  25031. });
  25032. svr.wait_until_ready();
  25033. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25034. std::to_string(port) + "/ws");
  25035. client.set_socket_options([](socket_t sock) {
  25036. int size = 8192;
  25037. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25038. reinterpret_cast<const char *>(&size), sizeof(size));
  25039. });
  25040. ASSERT_TRUE(client.connect());
  25041. // Read nothing, so the server's write times out partway through the frame.
  25042. for (int i = 0; i < 100 && !handler_done; i++) {
  25043. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25044. }
  25045. ASSERT_TRUE(handler_done);
  25046. ASSERT_FALSE(large_sent);
  25047. EXPECT_FALSE(open_after_failure);
  25048. client.close();
  25049. }
  25050. #endif
  25051. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25052. Server svr;
  25053. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25054. if (!req.has_header("Authorization")) {
  25055. res.status = StatusCode::Unauthorized_401;
  25056. res.set_content("Unauthorized", "text/plain");
  25057. return Server::HandlerResponse::Handled;
  25058. }
  25059. return Server::HandlerResponse::Unhandled;
  25060. });
  25061. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25062. std::string msg;
  25063. while (ws.read(msg)) {
  25064. ws.send(msg);
  25065. }
  25066. });
  25067. auto port = svr.bind_to_any_port("localhost");
  25068. std::thread t([&]() { svr.listen_after_bind(); });
  25069. svr.wait_until_ready();
  25070. // Without Authorization header - should be rejected before upgrade
  25071. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25072. EXPECT_FALSE(client1.connect());
  25073. // The rejection is framed like any other HTTP response
  25074. {
  25075. Client cli("localhost", port);
  25076. Headers headers = {{"Upgrade", "websocket"},
  25077. {"Connection", "Upgrade"},
  25078. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25079. {"Sec-WebSocket-Version", "13"}};
  25080. auto res = cli.Get("/ws", headers);
  25081. ASSERT_TRUE(res);
  25082. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25083. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25084. EXPECT_EQ("Unauthorized", res->body);
  25085. }
  25086. // With Authorization header - should succeed
  25087. Headers headers = {{"Authorization", "Bearer token123"}};
  25088. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25089. headers);
  25090. ASSERT_TRUE(client2.connect());
  25091. ASSERT_TRUE(client2.send("hello"));
  25092. std::string msg;
  25093. ASSERT_TRUE(client2.read(msg));
  25094. EXPECT_EQ("hello", msg);
  25095. client2.close();
  25096. svr.stop();
  25097. t.join();
  25098. }
  25099. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25100. Server svr;
  25101. std::atomic<int> pre_routing_calls{0};
  25102. std::atomic<int> pre_request_calls{0};
  25103. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25104. pre_routing_calls++;
  25105. if (req.path == "/handled") {
  25106. res.set_content("handled", "text/plain");
  25107. return Server::HandlerResponse::Handled;
  25108. }
  25109. return Server::HandlerResponse::Unhandled;
  25110. });
  25111. svr.set_pre_request_handler([&](const Request &, Response &) {
  25112. pre_request_calls++;
  25113. return Server::HandlerResponse::Unhandled;
  25114. });
  25115. svr.Get("/http", [](const Request &, Response &res) {
  25116. res.set_content("http", "text/plain");
  25117. });
  25118. svr.WebSocket("/ws",
  25119. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25120. auto port = svr.bind_to_any_port("localhost");
  25121. std::thread t([&]() { svr.listen_after_bind(); });
  25122. auto se = detail::scope_exit([&] {
  25123. svr.stop();
  25124. t.join();
  25125. });
  25126. svr.wait_until_ready();
  25127. Headers upgrade = {{"Upgrade", "websocket"},
  25128. {"Connection", "Upgrade"},
  25129. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25130. {"Sec-WebSocket-Version", "13"}};
  25131. auto get = [&](const char *path) {
  25132. pre_routing_calls = 0;
  25133. return Client("localhost", port).Get(path, upgrade);
  25134. };
  25135. // No WebSocket route, but an HTTP one
  25136. auto res = get("/http");
  25137. ASSERT_TRUE(res);
  25138. EXPECT_EQ(StatusCode::OK_200, res->status);
  25139. EXPECT_EQ("http", res->body);
  25140. EXPECT_EQ(1, pre_routing_calls);
  25141. EXPECT_EQ(1, pre_request_calls);
  25142. // No route at all
  25143. res = get("/none");
  25144. ASSERT_TRUE(res);
  25145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25146. EXPECT_EQ(1, pre_routing_calls);
  25147. // Answered by the pre-routing handler
  25148. res = get("/handled");
  25149. ASSERT_TRUE(res);
  25150. EXPECT_EQ(StatusCode::OK_200, res->status);
  25151. EXPECT_EQ("handled", res->body);
  25152. EXPECT_EQ(1, pre_routing_calls);
  25153. // A WebSocket route
  25154. pre_routing_calls = 0;
  25155. pre_request_calls = 0;
  25156. {
  25157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25158. "/ws");
  25159. ASSERT_TRUE(client.connect());
  25160. std::string msg;
  25161. ASSERT_TRUE(client.read(msg));
  25162. EXPECT_EQ("ws", msg);
  25163. client.close();
  25164. }
  25165. EXPECT_EQ(1, pre_routing_calls);
  25166. EXPECT_EQ(1, pre_request_calls);
  25167. }
  25168. // An upgrade request answered by a hook leaves its body unread, so that body
  25169. // must not be served as the next request on the connection.
  25170. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25171. Server svr;
  25172. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25173. if (req.path == "/pre-routing") {
  25174. res.set_content("pre-routing", "text/plain");
  25175. return Server::HandlerResponse::Handled;
  25176. }
  25177. return Server::HandlerResponse::Unhandled;
  25178. });
  25179. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25180. if (req.matched_route == "/pre-request") {
  25181. res.set_content("pre-request", "text/plain");
  25182. return Server::HandlerResponse::Handled;
  25183. }
  25184. return Server::HandlerResponse::Unhandled;
  25185. });
  25186. svr.Get("/smuggled", [](const Request &, Response &res) {
  25187. res.set_content("smuggled", "text/plain");
  25188. });
  25189. svr.WebSocket("/pre-request",
  25190. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25191. auto port = svr.bind_to_any_port(HOST);
  25192. std::thread t([&]() { svr.listen_after_bind(); });
  25193. auto se = detail::scope_exit([&] {
  25194. svr.stop();
  25195. t.join();
  25196. });
  25197. svr.wait_until_ready();
  25198. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25199. for (auto path : {"/pre-routing", "/pre-request"}) {
  25200. std::string req = std::string("GET ") + path +
  25201. " HTTP/1.1\r\n"
  25202. "Host: localhost\r\n"
  25203. "Upgrade: websocket\r\n"
  25204. "Connection: Upgrade\r\n"
  25205. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25206. "Sec-WebSocket-Version: 13\r\n"
  25207. "Content-Length: " +
  25208. std::to_string(body.size()) + "\r\n\r\n" + body;
  25209. std::string res;
  25210. ASSERT_TRUE(send_request(5, req, &res, port));
  25211. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25212. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25213. // Only one response, and the body was not served as a request
  25214. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25215. }
  25216. }
  25217. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25218. Server svr;
  25219. std::atomic<int> pre_request_calls{0};
  25220. std::atomic<bool> route_matched{false};
  25221. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25222. pre_request_calls++;
  25223. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25224. if (req.get_header_value("Authorization") != "Bearer token123") {
  25225. res.status = StatusCode::Unauthorized_401;
  25226. res.set_content("Unauthorized", "text/plain");
  25227. return Server::HandlerResponse::Handled;
  25228. }
  25229. return Server::HandlerResponse::Unhandled;
  25230. });
  25231. std::atomic<bool> handler_called{false};
  25232. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25233. handler_called = true;
  25234. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25235. });
  25236. auto port = svr.bind_to_any_port("localhost");
  25237. std::thread t([&]() { svr.listen_after_bind(); });
  25238. svr.wait_until_ready();
  25239. // Without Authorization header - should be rejected before upgrade
  25240. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25241. "/ws/1");
  25242. EXPECT_FALSE(client1.connect());
  25243. EXPECT_FALSE(handler_called);
  25244. EXPECT_EQ(1, pre_request_calls);
  25245. EXPECT_TRUE(route_matched);
  25246. // The rejection is an ordinary HTTP response, not a protocol switch
  25247. {
  25248. Client cli("localhost", port);
  25249. Headers headers = {{"Upgrade", "websocket"},
  25250. {"Connection", "Upgrade"},
  25251. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25252. {"Sec-WebSocket-Version", "13"}};
  25253. auto res = cli.Get("/ws/1", headers);
  25254. ASSERT_TRUE(res);
  25255. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25256. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25257. EXPECT_EQ("Unauthorized", res->body);
  25258. }
  25259. EXPECT_FALSE(handler_called);
  25260. // With Authorization header - should succeed
  25261. Headers headers = {{"Authorization", "Bearer token123"}};
  25262. ws::WebSocketClient client2(
  25263. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25264. ASSERT_TRUE(client2.connect());
  25265. std::string msg;
  25266. ASSERT_TRUE(client2.read(msg));
  25267. EXPECT_EQ("/ws/:id 2", msg);
  25268. EXPECT_TRUE(handler_called);
  25269. client2.close();
  25270. svr.stop();
  25271. t.join();
  25272. }
  25273. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25274. static Headers websocket_upgrade_headers() {
  25275. return {{"Upgrade", "websocket"},
  25276. {"Connection", "Upgrade"},
  25277. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25278. {"Sec-WebSocket-Version", "13"},
  25279. {"Sec-WebSocket-Protocol", "chat"}};
  25280. }
  25281. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25282. Server svr;
  25283. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25284. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25285. return Server::HandlerResponse::Unhandled;
  25286. });
  25287. svr.set_pre_request_handler([](const Request &req, Response &) {
  25288. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25289. return Server::HandlerResponse::Unhandled;
  25290. });
  25291. svr.set_exception_handler(
  25292. [](const Request &, Response &res, std::exception_ptr ep) {
  25293. try {
  25294. std::rethrow_exception(ep);
  25295. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25296. });
  25297. auto handler = [](const Request &, ws::WebSocket &) {};
  25298. svr.WebSocket("/pre-routing", handler);
  25299. svr.WebSocket("/pre-request", handler);
  25300. svr.WebSocket("/sub-protocol", handler,
  25301. [](const std::vector<std::string> &) -> std::string {
  25302. throw std::runtime_error("/sub-protocol");
  25303. });
  25304. auto port = svr.bind_to_any_port(HOST);
  25305. ASSERT_GT(port, 0);
  25306. thread t = thread([&] { svr.listen_after_bind(); });
  25307. auto se = detail::scope_exit([&] {
  25308. svr.stop();
  25309. t.join();
  25310. ASSERT_FALSE(svr.is_running());
  25311. });
  25312. svr.wait_until_ready();
  25313. Client cli(HOST, port);
  25314. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25315. auto res = cli.Get(path, websocket_upgrade_headers());
  25316. if (!res) {
  25317. ADD_FAILURE() << path << ": " << to_string(res.error());
  25318. continue;
  25319. }
  25320. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25321. EXPECT_EQ(path, res->body);
  25322. }
  25323. }
  25324. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25325. Server svr;
  25326. svr.set_pre_routing_handler(
  25327. [](const Request &, Response &) -> Server::HandlerResponse {
  25328. throw std::runtime_error("pre-routing");
  25329. });
  25330. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25331. auto port = svr.bind_to_any_port(HOST);
  25332. ASSERT_GT(port, 0);
  25333. thread t = thread([&] { svr.listen_after_bind(); });
  25334. auto se = detail::scope_exit([&] {
  25335. svr.stop();
  25336. t.join();
  25337. ASSERT_FALSE(svr.is_running());
  25338. });
  25339. svr.wait_until_ready();
  25340. Client cli(HOST, port);
  25341. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25342. ASSERT_TRUE(res) << to_string(res.error());
  25343. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25344. }
  25345. #endif
  25346. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25347. Server svr;
  25348. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25349. // A read timeout is how a handler gets control back. Without it, a handler
  25350. // parked in read() can never write on the connection it is reading.
  25351. ws.set_read_timeout(std::chrono::milliseconds(100));
  25352. std::string msg;
  25353. while (ws.is_open()) {
  25354. auto r = ws.read(msg);
  25355. if (r == httplib::ws::Timeout) {
  25356. ws.send("tick");
  25357. continue;
  25358. }
  25359. if (r == httplib::ws::Fail) { break; }
  25360. ws.send(msg);
  25361. }
  25362. });
  25363. auto port = svr.bind_to_any_port("localhost");
  25364. std::thread t([&]() { svr.listen_after_bind(); });
  25365. svr.wait_until_ready();
  25366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25367. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25368. ASSERT_TRUE(client.connect());
  25369. // The client sends nothing, so anything it receives came out of the
  25370. // handler's timeout path.
  25371. std::string msg;
  25372. ASSERT_EQ(client.read(msg), ws::Text);
  25373. EXPECT_EQ("tick", msg);
  25374. client.close();
  25375. svr.stop();
  25376. t.join();
  25377. }
  25378. // Stream::read may return fewer bytes than asked for. This is that contract at
  25379. // its worst -- one byte per call -- which is what a frame header straddling a
  25380. // read buffer's boundary looks like to the frame parser.
  25381. class WsByteAtATimeStream : public Stream {
  25382. public:
  25383. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25384. bool is_readable() const override { return true; }
  25385. bool wait_readable() const override { return true; }
  25386. bool wait_writable() const override { return true; }
  25387. ssize_t read(char *ptr, size_t size) override {
  25388. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25389. *ptr = data_[pos_++];
  25390. return 1;
  25391. }
  25392. ssize_t write(const char *, size_t size) override {
  25393. return static_cast<ssize_t>(size);
  25394. }
  25395. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25396. ip = "127.0.0.1";
  25397. port = 0;
  25398. }
  25399. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25400. ip = "127.0.0.1";
  25401. port = 0;
  25402. }
  25403. socket_t socket() const override { return INVALID_SOCKET; }
  25404. time_t duration() const override { return 0; }
  25405. private:
  25406. std::string data_;
  25407. size_t pos_ = 0;
  25408. };
  25409. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25410. // The payload uses the 16-bit extended length, so the header, the length
  25411. // and the mask key are all multi-byte fields here. Each used to be read
  25412. // with a single read() call, which fails as soon as one is split. The
  25413. // payload is also a little over one read chunk, so it is read in two.
  25414. std::string body;
  25415. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25416. body += static_cast<char>(i % 251);
  25417. }
  25418. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25419. std::string frame;
  25420. frame += static_cast<char>(0x81); // FIN + Text
  25421. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25422. frame += static_cast<char>(body.size() >> 8);
  25423. frame += static_cast<char>(body.size() & 0xff);
  25424. for (size_t i = 0; i < 4; i++) {
  25425. frame += static_cast<char>(mask[i]);
  25426. }
  25427. for (size_t i = 0; i < body.size(); i++) {
  25428. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25429. }
  25430. WsByteAtATimeStream strm(frame);
  25431. ws::Opcode opcode;
  25432. std::string payload;
  25433. bool fin = false;
  25434. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25435. /*expect_masked=*/true, body.size()),
  25436. ws::impl::FrameRead::Ok);
  25437. EXPECT_TRUE(fin);
  25438. EXPECT_EQ(opcode, ws::Opcode::Text);
  25439. EXPECT_EQ(payload, body);
  25440. }
  25441. // Keeps what is written, counting the writes, and reads it back.
  25442. class WsWriteCountingStream : public Stream {
  25443. public:
  25444. bool is_readable() const override { return true; }
  25445. bool wait_readable() const override { return true; }
  25446. bool wait_writable() const override { return true; }
  25447. ssize_t read(char *ptr, size_t size) override {
  25448. auto n = (std::min)(size, data_.size() - pos_);
  25449. if (n == 0) { return 0; }
  25450. memcpy(ptr, data_.data() + pos_, n);
  25451. pos_ += n;
  25452. return static_cast<ssize_t>(n);
  25453. }
  25454. ssize_t write(const char *ptr, size_t size) override {
  25455. writes++;
  25456. data_.append(ptr, size);
  25457. return static_cast<ssize_t>(size);
  25458. }
  25459. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25460. ip = "127.0.0.1";
  25461. port = 0;
  25462. }
  25463. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25464. ip = "127.0.0.1";
  25465. port = 0;
  25466. }
  25467. socket_t socket() const override { return INVALID_SOCKET; }
  25468. time_t duration() const override { return 0; }
  25469. int writes = 0;
  25470. private:
  25471. std::string data_;
  25472. size_t pos_ = 0;
  25473. };
  25474. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25475. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25476. // masked and not, reads back as written; a payload over one chunk follows
  25477. // its first in more writes.
  25478. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25479. for (auto mask : {false, true}) {
  25480. std::string body(len, '\0');
  25481. for (size_t i = 0; i < len; i++) {
  25482. body[i] = static_cast<char>(i % 251);
  25483. }
  25484. WsWriteCountingStream strm;
  25485. ASSERT_TRUE(detail::write_websocket_frame(
  25486. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25487. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25488. ws::Opcode opcode;
  25489. std::string payload;
  25490. bool fin = false;
  25491. ASSERT_EQ(
  25492. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25493. ws::impl::FrameRead::Ok)
  25494. << len << " " << mask;
  25495. EXPECT_TRUE(fin);
  25496. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25497. EXPECT_EQ(body, payload) << len << " " << mask;
  25498. }
  25499. }
  25500. }
  25501. // Hands out its pieces one read at a time, timing out between each two.
  25502. class WsTimeoutBetweenPiecesStream : public Stream {
  25503. public:
  25504. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25505. : pieces_(std::move(pieces)) {}
  25506. bool is_readable() const override { return true; }
  25507. bool wait_readable() const override { return true; }
  25508. bool wait_writable() const override { return true; }
  25509. ssize_t read(char *ptr, size_t size) override {
  25510. if (time_out_) {
  25511. time_out_ = false;
  25512. error_ = Error::Timeout;
  25513. return -1;
  25514. }
  25515. if (i_ >= pieces_.size()) {
  25516. error_ = Error::ConnectionClosed;
  25517. return 0;
  25518. }
  25519. auto &piece = pieces_[i_];
  25520. auto n = (std::min)(size, piece.size() - at_);
  25521. memcpy(ptr, piece.data() + at_, n);
  25522. at_ += n;
  25523. if (at_ == piece.size()) {
  25524. i_++;
  25525. at_ = 0;
  25526. time_out_ = true;
  25527. }
  25528. return static_cast<ssize_t>(n);
  25529. }
  25530. ssize_t write(const char *, size_t size) override {
  25531. return static_cast<ssize_t>(size);
  25532. }
  25533. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25534. ip = "127.0.0.1";
  25535. port = 0;
  25536. }
  25537. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25538. ip = "127.0.0.1";
  25539. port = 0;
  25540. }
  25541. socket_t socket() const override { return INVALID_SOCKET; }
  25542. time_t duration() const override { return 0; }
  25543. private:
  25544. std::vector<std::string> pieces_;
  25545. size_t i_ = 0;
  25546. size_t at_ = 0;
  25547. bool time_out_ = false;
  25548. };
  25549. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25550. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25551. std::string frame = "\x81\x85";
  25552. frame.append(4, '\0');
  25553. frame += "Hello";
  25554. // The header's first byte, then its second with half the mask key, then
  25555. // the rest
  25556. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25557. frame.substr(4)};
  25558. WsTimeoutBetweenPiecesStream strm(pieces);
  25559. ws::impl::FrameReader reader;
  25560. ws::Opcode opcode;
  25561. std::string payload;
  25562. bool fin = false;
  25563. for (int i = 0; i < 2; i++) {
  25564. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25565. reader.read(strm, opcode, payload, fin, true, 0));
  25566. EXPECT_TRUE(reader.begun());
  25567. }
  25568. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25569. reader.read(strm, opcode, payload, fin, true, 0));
  25570. EXPECT_FALSE(reader.begun());
  25571. EXPECT_TRUE(fin);
  25572. EXPECT_EQ(ws::Opcode::Text, opcode);
  25573. EXPECT_EQ("Hello", payload);
  25574. // Read in one go, the frame cannot be gone on with after a timeout
  25575. WsTimeoutBetweenPiecesStream again(pieces);
  25576. EXPECT_EQ(
  25577. ws::impl::FrameRead::Fail,
  25578. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25579. }
  25580. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25581. std::string body(2000, 'x');
  25582. std::string frame;
  25583. frame += static_cast<char>(0x82); // FIN + Binary
  25584. frame += static_cast<char>(126); // 16-bit length follows
  25585. frame += static_cast<char>(body.size() >> 8);
  25586. frame += static_cast<char>(body.size() & 0xff);
  25587. frame += body;
  25588. detail::BufferStream strm;
  25589. strm.write(frame.data(), frame.size());
  25590. ws::Opcode opcode;
  25591. std::string payload;
  25592. bool fin;
  25593. EXPECT_EQ(
  25594. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25595. ws::impl::FrameRead::Ok);
  25596. EXPECT_EQ(body, payload);
  25597. }
  25598. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25599. // The header announces the largest payload allowed, and only 3 bytes of it
  25600. // ever arrive.
  25601. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25602. std::string frame;
  25603. frame += static_cast<char>(0x82); // FIN + Binary
  25604. frame += static_cast<char>(127); // 64-bit length follows
  25605. for (int shift = 56; shift >= 0; shift -= 8) {
  25606. frame += static_cast<char>((len >> shift) & 0xff);
  25607. }
  25608. frame += "abc";
  25609. detail::BufferStream strm;
  25610. strm.write(frame.data(), frame.size());
  25611. ws::Opcode opcode;
  25612. std::string payload;
  25613. bool fin;
  25614. EXPECT_EQ(
  25615. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25616. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25617. ws::impl::FrameRead::Fail);
  25618. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25619. }
  25620. TEST(WebSocketTest, QueryStringInHandshake) {
  25621. Server svr;
  25622. std::mutex mtx;
  25623. std::string received_target;
  25624. std::string received_token;
  25625. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25626. {
  25627. std::lock_guard<std::mutex> lock(mtx);
  25628. received_target = req.target;
  25629. if (req.has_param("token")) {
  25630. received_token = req.get_param_value("token");
  25631. }
  25632. }
  25633. std::string msg;
  25634. while (ws.read(msg)) {
  25635. ws.send(msg);
  25636. }
  25637. });
  25638. auto port = svr.bind_to_any_port("localhost");
  25639. std::thread t([&]() { svr.listen_after_bind(); });
  25640. svr.wait_until_ready();
  25641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25642. "/ws?token=ABC&session=123");
  25643. ASSERT_TRUE(client.connect());
  25644. // Round-trip ensures the handler has run and captured the request.
  25645. ASSERT_TRUE(client.send("hello"));
  25646. std::string msg;
  25647. ASSERT_TRUE(client.read(msg));
  25648. EXPECT_EQ("hello", msg);
  25649. client.close();
  25650. {
  25651. std::lock_guard<std::mutex> lock(mtx);
  25652. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25653. EXPECT_EQ("ABC", received_token);
  25654. }
  25655. svr.stop();
  25656. t.join();
  25657. }
  25658. // Run a handshake against a throwaway server and hand the request the server
  25659. // received back to the caller, so tests can assert on the headers the client
  25660. // actually put on the wire.
  25661. static void capture_websocket_handshake_request(
  25662. const Headers &client_headers,
  25663. std::function<void(const Request &, int port)> verify) {
  25664. Server svr;
  25665. std::mutex mtx;
  25666. Request received;
  25667. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25668. {
  25669. std::lock_guard<std::mutex> lock(mtx);
  25670. received = req;
  25671. }
  25672. std::string msg;
  25673. while (ws.read(msg)) {
  25674. ws.send(msg);
  25675. }
  25676. });
  25677. auto port = svr.bind_to_any_port("localhost");
  25678. std::thread t([&]() { svr.listen_after_bind(); });
  25679. auto se = detail::scope_exit([&] {
  25680. svr.stop();
  25681. t.join();
  25682. });
  25683. svr.wait_until_ready();
  25684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25685. client_headers);
  25686. ASSERT_TRUE(client.connect());
  25687. ASSERT_TRUE(client.send("hello"));
  25688. std::string msg;
  25689. ASSERT_TRUE(client.read(msg));
  25690. client.close();
  25691. {
  25692. std::lock_guard<std::mutex> lock(mtx);
  25693. verify(received, port);
  25694. }
  25695. }
  25696. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25697. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25698. // Non-default port must be present in the Host header. Default ports
  25699. // (80/443) are omitted; that logic is covered by
  25700. // MakeHostAndPortStringTest.
  25701. EXPECT_EQ("localhost:" + std::to_string(port),
  25702. req.get_header_value("Host"));
  25703. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25704. req.get_header_value("User-Agent"));
  25705. EXPECT_FALSE(req.has_header("Accept"));
  25706. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25707. EXPECT_FALSE(req.has_header("Content-Length"));
  25708. });
  25709. }
  25710. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25711. capture_websocket_handshake_request(
  25712. {{"Host", "example.com"},
  25713. {"User-Agent", "custom-agent"},
  25714. {"X-Custom", "value"}},
  25715. [](const Request &req, int) {
  25716. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25717. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25718. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25719. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25720. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25721. });
  25722. }
  25723. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25724. capture_websocket_handshake_request(
  25725. {{"Upgrade", "bogus"},
  25726. {"Connection", "close"},
  25727. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25728. {"Sec-WebSocket-Version", "8"}},
  25729. [](const Request &req, int) {
  25730. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25731. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25732. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25733. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25734. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25735. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25736. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25737. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25738. req.get_header_value("Sec-WebSocket-Key"));
  25739. });
  25740. }
  25741. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25742. // A header the client refuses to send must abort the handshake before any
  25743. // part of it reaches the wire; a lone request line would otherwise sit in
  25744. // the peer's buffer as a truncated request.
  25745. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25746. ASSERT_NE(INVALID_SOCKET, srv);
  25747. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25748. sockaddr_in addr{};
  25749. addr.sin_family = AF_INET;
  25750. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25751. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25752. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25753. ASSERT_EQ(0, ::listen(srv, 1));
  25754. sockaddr_in bound{};
  25755. socklen_t bound_len = sizeof(bound);
  25756. ASSERT_EQ(
  25757. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25758. auto port = ntohs(bound.sin_port);
  25759. ssize_t received = -1;
  25760. std::thread t([&] {
  25761. // Bound every blocking call so a regression fails the test with a bad
  25762. // value instead of hanging the suite.
  25763. fd_set rfds;
  25764. FD_ZERO(&rfds);
  25765. FD_SET(srv, &rfds);
  25766. timeval tv{5, 0};
  25767. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25768. 0) {
  25769. return;
  25770. }
  25771. sockaddr_in cli_addr{};
  25772. socklen_t cli_len = sizeof(cli_addr);
  25773. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25774. if (cli == INVALID_SOCKET) { return; }
  25775. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25776. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25777. char buf[4096];
  25778. received = ::recv(cli, buf, sizeof(buf), 0);
  25779. });
  25780. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25781. // connect() has already shut the socket down by the time it returns false,
  25782. // so the peer sees EOF without waiting for the client to be destroyed.
  25783. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25784. {{"X-Bad", "a\r\nInjected: 1"}});
  25785. EXPECT_FALSE(client.connect());
  25786. t.join();
  25787. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25788. EXPECT_EQ(0, received);
  25789. }
  25790. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25791. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25792. // contains "upgrade" as a substring is a different token and must not
  25793. // start a WebSocket handshake.
  25794. auto make_request = [](const std::vector<std::string> &connection_values) {
  25795. Request req;
  25796. req.method = "GET";
  25797. req.headers.emplace("Upgrade", "websocket");
  25798. for (const auto &value : connection_values) {
  25799. req.headers.emplace("Connection", value);
  25800. }
  25801. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25802. req.headers.emplace("Sec-WebSocket-Version", "13");
  25803. return req;
  25804. };
  25805. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25806. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25807. EXPECT_TRUE(
  25808. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25809. EXPECT_TRUE(
  25810. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25811. EXPECT_TRUE(
  25812. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25813. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25814. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25815. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25816. EXPECT_FALSE(
  25817. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25818. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25819. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25820. }
  25821. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25822. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25823. // asks recipients to match each protocol-name case-insensitively, and RFC
  25824. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25825. // client naming websocket alongside another protocol, or on a second field
  25826. // line, is offering websocket; a value that merely contains "websocket" as a
  25827. // substring is a different protocol name and is not.
  25828. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25829. Request req;
  25830. req.method = "GET";
  25831. for (const auto &value : upgrade_values) {
  25832. req.headers.emplace("Upgrade", value);
  25833. }
  25834. req.headers.emplace("Connection", "Upgrade");
  25835. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25836. req.headers.emplace("Sec-WebSocket-Version", "13");
  25837. return req;
  25838. };
  25839. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25840. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25841. EXPECT_TRUE(
  25842. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25843. EXPECT_TRUE(
  25844. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25845. EXPECT_TRUE(
  25846. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25847. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25848. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25849. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25850. EXPECT_FALSE(
  25851. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25852. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25853. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25854. }
  25855. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25856. Server svr;
  25857. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25858. auto port = svr.bind_to_any_port("localhost");
  25859. std::thread t([&]() { svr.listen_after_bind(); });
  25860. auto se = detail::scope_exit([&] {
  25861. svr.stop();
  25862. t.join();
  25863. });
  25864. svr.wait_until_ready();
  25865. Headers headers = {{"Upgrade", "websocket"},
  25866. {"Connection", "notupgrade"},
  25867. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25868. {"Sec-WebSocket-Version", "13"}};
  25869. Client cli("localhost", port);
  25870. auto res = cli.Get("/ws", headers);
  25871. // The route exists only as a WebSocket route, so a request that fails the
  25872. // handshake check falls through to ordinary routing.
  25873. ASSERT_TRUE(res);
  25874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25875. }
  25876. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25877. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25878. // Connection value is the only thing left for the client to reject.
  25879. Server svr;
  25880. svr.Get("/ws", [](const Request &req, Response &res) {
  25881. res.status = StatusCode::SwitchingProtocol_101;
  25882. res.set_header("Upgrade", "websocket");
  25883. res.set_header("Connection", "notupgrade");
  25884. res.set_header("Sec-WebSocket-Accept",
  25885. detail::websocket_accept_key(
  25886. req.get_header_value("Sec-WebSocket-Key")));
  25887. });
  25888. auto port = svr.bind_to_any_port("localhost");
  25889. std::thread t([&]() { svr.listen_after_bind(); });
  25890. auto se = detail::scope_exit([&] {
  25891. svr.stop();
  25892. t.join();
  25893. });
  25894. svr.wait_until_ready();
  25895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25896. auto res = client.connect();
  25897. EXPECT_FALSE(res);
  25898. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25899. EXPECT_FALSE(client.is_open());
  25900. }
  25901. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25902. Server svr;
  25903. svr.Get("/ws", [](const Request &req, Response &res) {
  25904. res.status = StatusCode::SwitchingProtocol_101;
  25905. res.set_header("Upgrade", "websocket");
  25906. res.set_header("Connection", "Upgrade");
  25907. res.set_header("Sec-WebSocket-Accept",
  25908. detail::websocket_accept_key(
  25909. req.get_header_value("Sec-WebSocket-Key")));
  25910. res.set_header("Sec-WebSocket-Protocol", "admin");
  25911. });
  25912. auto port = svr.bind_to_any_port("localhost");
  25913. std::thread t([&]() { svr.listen_after_bind(); });
  25914. auto se = detail::scope_exit([&] {
  25915. svr.stop();
  25916. t.join();
  25917. });
  25918. svr.wait_until_ready();
  25919. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25920. // Server selects a subprotocol the client never offered
  25921. {
  25922. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25923. ws::WebSocketClient client(url, headers);
  25924. auto res = client.connect();
  25925. EXPECT_FALSE(res);
  25926. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25927. EXPECT_FALSE(client.is_open());
  25928. EXPECT_TRUE(client.subprotocol().empty());
  25929. }
  25930. // Client offered none but the server named one anyway
  25931. {
  25932. ws::WebSocketClient client(url);
  25933. auto res = client.connect();
  25934. EXPECT_FALSE(res);
  25935. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25936. EXPECT_FALSE(client.is_open());
  25937. EXPECT_TRUE(client.subprotocol().empty());
  25938. }
  25939. }
  25940. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25941. // The socket path doubles as the URL host, so it must not contain '/'.
  25942. const char *shard = getenv("GTEST_SHARD_INDEX");
  25943. const std::string sock_path =
  25944. shard ? std::string("httplib-ws-") + shard + ".sock"
  25945. : std::string("httplib-ws.sock");
  25946. std::remove(sock_path.c_str());
  25947. Server svr;
  25948. std::mutex mtx;
  25949. std::string received_host;
  25950. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25951. {
  25952. std::lock_guard<std::mutex> lock(mtx);
  25953. received_host = req.get_header_value("Host");
  25954. }
  25955. std::string msg;
  25956. while (ws.read(msg)) {
  25957. ws.send(msg);
  25958. }
  25959. });
  25960. svr.set_address_family(AF_UNIX);
  25961. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25962. auto se = detail::scope_exit([&] {
  25963. svr.stop();
  25964. t.join();
  25965. std::remove(sock_path.c_str());
  25966. });
  25967. svr.wait_until_ready();
  25968. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25969. client.set_address_family(AF_UNIX);
  25970. ASSERT_TRUE(client.connect());
  25971. ASSERT_TRUE(client.send("hello"));
  25972. std::string msg;
  25973. ASSERT_TRUE(client.read(msg));
  25974. client.close();
  25975. {
  25976. std::lock_guard<std::mutex> lock(mtx);
  25977. // There is no host:port for a Unix socket, so the same "localhost"
  25978. // placeholder the HTTP client uses is expected.
  25979. EXPECT_EQ("localhost", received_host);
  25980. }
  25981. }
  25982. // Two threads must never parse WebSocket frames from the same stream.
  25983. // close() used to read the peer's Close reply with its own frame read, so it
  25984. // raced a reader thread that was in the middle of a payload: the payload loop
  25985. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25986. // so bytes taken by close() were replaced with bytes from further along the
  25987. // stream. The message kept its length and silently changed content.
  25988. //
  25989. // The raw peer below sends a frame header plus part of the payload, waits for
  25990. // the handler to call close(), and only then sends the rest. Whichever thread
  25991. // would win the race for those bytes, the message must arrive intact, because
  25992. // close() must not touch the stream while read() owns it.
  25993. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25994. #ifndef _WIN32
  25995. signal(SIGPIPE, SIG_IGN);
  25996. #endif
  25997. const size_t payload_len = 120; // fits the 7-bit length field
  25998. const size_t prefix_len = 8;
  25999. const int attempts = 8;
  26000. std::string expected(payload_len, '\0');
  26001. for (size_t i = 0; i < payload_len; i++) {
  26002. expected[i] = static_cast<char>('a' + i % 26);
  26003. }
  26004. std::atomic<bool> peer_stalled{false};
  26005. std::atomic<bool> handler_done{false};
  26006. std::mutex received_mutex;
  26007. std::vector<std::string> received;
  26008. // Bound every wait, so a regression fails the test instead of hanging the
  26009. // suite.
  26010. auto wait_for = [](const std::atomic<bool> &flag) {
  26011. for (int i = 0; i < 500 && !flag; i++) {
  26012. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26013. }
  26014. };
  26015. Server svr;
  26016. svr.set_websocket_ping_interval(0);
  26017. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26018. std::thread reader([&]() {
  26019. std::string msg;
  26020. while (ws.read(msg)) {
  26021. std::lock_guard<std::mutex> guard(received_mutex);
  26022. received.push_back(msg);
  26023. }
  26024. });
  26025. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26026. // inside a frame when close() runs.
  26027. wait_for(peer_stalled);
  26028. ws.close();
  26029. reader.join();
  26030. handler_done = true;
  26031. });
  26032. auto port = svr.bind_to_any_port("127.0.0.1");
  26033. std::thread t([&]() { svr.listen_after_bind(); });
  26034. auto se = detail::scope_exit([&] {
  26035. svr.stop();
  26036. t.join();
  26037. });
  26038. svr.wait_until_ready();
  26039. auto send_bytes = [](socket_t s, const std::string &data) {
  26040. #ifdef _WIN32
  26041. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26042. #else
  26043. auto n = ::send(s, data.data(), data.size(), 0);
  26044. #endif
  26045. return n == static_cast<decltype(n)>(data.size());
  26046. };
  26047. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26048. // Every length used here fits the 7-bit length field.
  26049. auto masked_header = [](uint8_t first_byte, size_t len) {
  26050. std::string h;
  26051. h += static_cast<char>(first_byte);
  26052. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26053. h.append(4, '\0'); // mask key
  26054. return h;
  26055. };
  26056. for (int attempt = 0; attempt < attempts; attempt++) {
  26057. peer_stalled = false;
  26058. handler_done = false;
  26059. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26060. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26061. auto se_sock = detail::scope_exit([&] {
  26062. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26063. });
  26064. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26065. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26066. sockaddr_in addr{};
  26067. addr.sin_family = AF_INET;
  26068. addr.sin_port = htons(static_cast<uint16_t>(port));
  26069. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26070. ASSERT_EQ(
  26071. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26072. << "attempt " << attempt;
  26073. ASSERT_TRUE(send_bytes(sock,
  26074. "GET /ws HTTP/1.1\r\n"
  26075. "Host: 127.0.0.1\r\n"
  26076. "Upgrade: websocket\r\n"
  26077. "Connection: Upgrade\r\n"
  26078. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26079. "Sec-WebSocket-Version: 13\r\n"
  26080. "\r\n"))
  26081. << "attempt " << attempt;
  26082. std::string response;
  26083. while (response.find("\r\n\r\n") == std::string::npos) {
  26084. char buf[512];
  26085. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26086. if (n <= 0) { break; }
  26087. response.append(buf, static_cast<size_t>(n));
  26088. }
  26089. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26090. << "attempt " << attempt;
  26091. // Send the header of a Binary message but only the first prefix_len bytes
  26092. // of its payload, leaving the reader thread stalled inside the payload.
  26093. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26094. expected.substr(0, prefix_len)))
  26095. << "attempt " << attempt;
  26096. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26097. peer_stalled = true;
  26098. // Let close() send its Close frame and park in its own read before the
  26099. // rest of the payload arrives, so both threads are waiting for it.
  26100. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26101. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26102. close_frame += static_cast<char>(0x03); // status 1000
  26103. close_frame += static_cast<char>(0xE8);
  26104. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26105. << "attempt " << attempt;
  26106. // Closing the peer releases the reader thread even on the buggy path,
  26107. // where it waits for bytes another thread already consumed.
  26108. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26109. detail::close_socket(sock);
  26110. sock = INVALID_SOCKET;
  26111. wait_for(handler_done);
  26112. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26113. }
  26114. std::lock_guard<std::mutex> guard(received_mutex);
  26115. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26116. << "a message in flight when close() ran was dropped";
  26117. for (size_t i = 0; i < received.size(); i++) {
  26118. EXPECT_EQ(expected, received[i]) << "message " << i;
  26119. }
  26120. }
  26121. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26122. // returning the socket, or INVALID_SOCKET.
  26123. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26124. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26125. if (sock == INVALID_SOCKET) { return sock; }
  26126. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26127. sockaddr_in addr{};
  26128. addr.sin_family = AF_INET;
  26129. addr.sin_port = htons(static_cast<uint16_t>(port));
  26130. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26131. std::string req = "GET " + path +
  26132. " HTTP/1.1\r\n"
  26133. "Host: 127.0.0.1\r\n"
  26134. "Upgrade: websocket\r\n"
  26135. "Connection: Upgrade\r\n"
  26136. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26137. "Sec-WebSocket-Version: 13\r\n"
  26138. "\r\n";
  26139. std::string res;
  26140. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26141. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26142. static_cast<ssize_t>(req.size())) {
  26143. char c;
  26144. while (res.find("\r\n\r\n") == std::string::npos &&
  26145. ::recv(sock, &c, 1, 0) == 1) {
  26146. res += c;
  26147. }
  26148. }
  26149. if (res.find(" 101 ") == std::string::npos) {
  26150. detail::close_socket(sock);
  26151. return INVALID_SOCKET;
  26152. }
  26153. return sock;
  26154. }
  26155. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26156. // The payload must fit the 7-bit length field.
  26157. static std::string masked_frame(uint8_t first_byte,
  26158. const std::string &payload) {
  26159. std::string f;
  26160. f += static_cast<char>(first_byte);
  26161. f += static_cast<char>(0x80 | payload.size());
  26162. f.append(4, '\0');
  26163. return f + payload;
  26164. }
  26165. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26166. std::atomic<bool> done{false};
  26167. std::string received;
  26168. Server svr;
  26169. svr.set_websocket_ping_interval(0);
  26170. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26171. std::string msg;
  26172. if (ws.read(msg) == ws::Binary) { received = msg; }
  26173. done = true;
  26174. });
  26175. auto port = svr.bind_to_any_port("127.0.0.1");
  26176. std::thread t([&]() { svr.listen_after_bind(); });
  26177. auto se = detail::scope_exit([&] {
  26178. svr.stop();
  26179. t.join();
  26180. });
  26181. svr.wait_until_ready();
  26182. auto sock = connect_raw_websocket(port, "/ws");
  26183. ASSERT_NE(INVALID_SOCKET, sock);
  26184. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26185. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26186. masked_frame(0x89, "p") + // FIN + Ping
  26187. masked_frame(0x80, "lo"); // FIN + Continuation
  26188. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26189. for (int i = 0; i < 500 && !done; i++) {
  26190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26191. }
  26192. ASSERT_TRUE(done);
  26193. EXPECT_EQ("Hello", received);
  26194. // The Ping between the fragments is answered with a Pong.
  26195. char pong[3];
  26196. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26197. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26198. }
  26199. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26200. #ifndef _WIN32
  26201. signal(SIGPIPE, SIG_IGN);
  26202. #endif
  26203. std::atomic<bool> read_ended{false};
  26204. std::atomic<bool> sending{true};
  26205. Server svr;
  26206. svr.set_websocket_ping_interval(0);
  26207. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26208. std::thread reader([&]() {
  26209. std::string msg;
  26210. while (ws.read(msg)) {}
  26211. read_ended = true;
  26212. });
  26213. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26214. ws.close();
  26215. reader.join();
  26216. });
  26217. auto port = svr.bind_to_any_port("127.0.0.1");
  26218. std::thread t([&]() { svr.listen_after_bind(); });
  26219. auto se = detail::scope_exit([&] {
  26220. svr.stop();
  26221. t.join();
  26222. });
  26223. svr.wait_until_ready();
  26224. auto sock = connect_raw_websocket(port, "/ws");
  26225. ASSERT_NE(INVALID_SOCKET, sock);
  26226. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26227. // A Text message whose empty continuation frames never end
  26228. std::thread sender([&]() {
  26229. auto data = masked_frame(0x01, "");
  26230. while (sending) {
  26231. data += masked_frame(0x00, "");
  26232. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26233. return;
  26234. }
  26235. data.clear();
  26236. }
  26237. });
  26238. for (int i = 0; i < 300 && !read_ended; i++) {
  26239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26240. }
  26241. sending = false;
  26242. sender.join();
  26243. EXPECT_TRUE(read_ended);
  26244. }
  26245. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26246. Server svr;
  26247. svr.set_websocket_ping_interval(-1);
  26248. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26249. std::string msg;
  26250. while (ws.read(msg)) {}
  26251. });
  26252. auto port = svr.bind_to_any_port("127.0.0.1");
  26253. std::thread t([&]() { svr.listen_after_bind(); });
  26254. auto se = detail::scope_exit([&] {
  26255. svr.stop();
  26256. t.join();
  26257. });
  26258. svr.wait_until_ready();
  26259. auto sock = connect_raw_websocket(port, "/ws");
  26260. ASSERT_NE(INVALID_SOCKET, sock);
  26261. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26262. // Nothing comes while the client stays quiet.
  26263. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26264. char c;
  26265. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26266. }
  26267. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26268. // and that has to end a read() already waiting on the peer, on every platform.
  26269. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26270. // The peer sends no pings, and its handler never calls read(), which is
  26271. // where pongs are written.
  26272. std::mutex mutex;
  26273. std::condition_variable cv;
  26274. auto release = false;
  26275. svr.set_websocket_ping_interval(0);
  26276. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26277. std::unique_lock<std::mutex> lock(mutex);
  26278. cv.wait(lock, [&] { return release; });
  26279. });
  26280. auto port = svr.bind_to_any_port(HOST);
  26281. std::thread t([&]() { svr.listen_after_bind(); });
  26282. auto se = detail::scope_exit([&] {
  26283. {
  26284. std::lock_guard<std::mutex> lock(mutex);
  26285. release = true;
  26286. }
  26287. cv.notify_all();
  26288. svr.stop();
  26289. t.join();
  26290. });
  26291. svr.wait_until_ready();
  26292. ws::WebSocketClient client(std::string(scheme) +
  26293. "://localhost:" + std::to_string(port) + "/ws");
  26294. #ifdef CPPHTTPLIB_SSL_ENABLED
  26295. client.enable_server_certificate_verification(false);
  26296. #endif
  26297. // A ping a second, given up on after two go unanswered: about 3s
  26298. client.set_websocket_ping_interval(1);
  26299. client.set_websocket_max_missed_pongs(2);
  26300. // Well past that, so that a read the timeout ends instead stands out
  26301. client.set_read_timeout(10);
  26302. ASSERT_TRUE(client.connect());
  26303. auto start = std::chrono::steady_clock::now();
  26304. std::string msg;
  26305. EXPECT_EQ(ws::Fail, client.read(msg));
  26306. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26307. std::chrono::steady_clock::now() - start)
  26308. .count(),
  26309. 6000);
  26310. EXPECT_FALSE(client.is_open());
  26311. }
  26312. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26313. Server svr;
  26314. check_pong_timeout_ends_read(svr, "ws");
  26315. }
  26316. #ifdef CPPHTTPLIB_SSL_ENABLED
  26317. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26319. ASSERT_TRUE(svr.is_valid());
  26320. check_pong_timeout_ends_read(svr, "wss");
  26321. }
  26322. #endif
  26323. // listen() returns only after every handler has, so Server::stop() has to end
  26324. // a WebSocket handler's read() waiting on a client that stays connected and
  26325. // quiet, whether or not the handler bounded its reads, and the client's
  26326. // connection ends with it.
  26327. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26328. bool bounded) {
  26329. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26330. if (bounded) { ws.set_read_timeout(0, 50000); }
  26331. std::string msg;
  26332. while (ws.read(msg) != ws::Fail) {}
  26333. });
  26334. auto port = svr.bind_to_any_port(HOST);
  26335. std::thread t([&]() { svr.listen_after_bind(); });
  26336. auto se = detail::scope_exit([&] {
  26337. if (t.joinable()) {
  26338. svr.stop();
  26339. t.join();
  26340. }
  26341. });
  26342. svr.wait_until_ready();
  26343. ws::WebSocketClient client(std::string(scheme) +
  26344. "://localhost:" + std::to_string(port) + "/ws");
  26345. #ifdef CPPHTTPLIB_SSL_ENABLED
  26346. client.enable_server_certificate_verification(false);
  26347. #endif
  26348. client.set_read_timeout(2);
  26349. ASSERT_TRUE(client.connect());
  26350. auto stopped = std::async(std::launch::async, [&] {
  26351. svr.stop();
  26352. t.join();
  26353. });
  26354. std::string msg;
  26355. EXPECT_EQ(ws::Fail, client.read(msg));
  26356. EXPECT_FALSE(client.is_open());
  26357. auto in_time =
  26358. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26359. // A handler the stop did not reach ends when the client leaves
  26360. if (!in_time) { client.close(); }
  26361. stopped.wait();
  26362. EXPECT_TRUE(in_time);
  26363. }
  26364. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26365. Server svr;
  26366. check_stop_ends_websocket_read(svr, "ws", false);
  26367. }
  26368. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26369. Server svr;
  26370. check_stop_ends_websocket_read(svr, "ws", true);
  26371. }
  26372. #ifdef CPPHTTPLIB_SSL_ENABLED
  26373. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26375. ASSERT_TRUE(svr.is_valid());
  26376. check_stop_ends_websocket_read(svr, "wss", false);
  26377. }
  26378. #endif
  26379. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26380. // dropped connection, whether the handler waits for a message or for the rest
  26381. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26382. // time out inside the message as well, and the stop ends them too.
  26383. static void check_stop_closes_with_going_away(const std::string &sent,
  26384. bool bounded = false) {
  26385. Server svr;
  26386. svr.set_websocket_ping_interval(0);
  26387. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26388. if (bounded) { ws.set_read_timeout(0, 10000); }
  26389. std::string msg;
  26390. while (ws.read(msg) != ws::Fail) {}
  26391. });
  26392. auto port = svr.bind_to_any_port("127.0.0.1");
  26393. std::thread t([&]() { svr.listen_after_bind(); });
  26394. auto se = detail::scope_exit([&] {
  26395. svr.stop();
  26396. t.join();
  26397. });
  26398. svr.wait_until_ready();
  26399. // Closed before the join above, which a handler the stop did not reach
  26400. // would otherwise hold up.
  26401. auto sock = connect_raw_websocket(port, "/ws");
  26402. ASSERT_NE(INVALID_SOCKET, sock);
  26403. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26404. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26405. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26406. // Let the handler take what was sent and wait for more
  26407. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26408. svr.stop();
  26409. // FIN + Close, its length, then the code: unmasked, from a server
  26410. std::string head;
  26411. char c;
  26412. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26413. head += c;
  26414. }
  26415. const std::string reason = "server stopping";
  26416. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26417. "\x03\xe9",
  26418. head);
  26419. }
  26420. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26421. check_stop_closes_with_going_away("");
  26422. }
  26423. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26424. // A Text frame without FIN: the first fragment of a message
  26425. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26426. }
  26427. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26428. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26429. /*bounded=*/true);
  26430. }
  26431. // A handler that bounds its reads gets control back within its timeout even
  26432. // while a message arrives in pieces, and the message whole once the last has
  26433. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26434. // sent a while after the one before, much longer than the handler's timeout.
  26435. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26436. const std::string &expected) {
  26437. std::atomic<bool> done{false};
  26438. std::string received;
  26439. std::chrono::steady_clock::duration longest{};
  26440. Server svr;
  26441. svr.set_websocket_ping_interval(0);
  26442. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26443. ws.set_read_timeout(0, 10000);
  26444. std::string msg;
  26445. ws::ReadResult r;
  26446. do {
  26447. auto began = std::chrono::steady_clock::now();
  26448. r = ws.read(msg);
  26449. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26450. } while (r == ws::Timeout);
  26451. if (r == ws::Text) { received = msg; }
  26452. done = true;
  26453. });
  26454. auto port = svr.bind_to_any_port("127.0.0.1");
  26455. std::thread t([&]() { svr.listen_after_bind(); });
  26456. auto se = detail::scope_exit([&] {
  26457. svr.stop();
  26458. t.join();
  26459. });
  26460. svr.wait_until_ready();
  26461. auto sock = connect_raw_websocket(port, "/ws");
  26462. ASSERT_NE(INVALID_SOCKET, sock);
  26463. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26464. for (const auto &piece : pieces) {
  26465. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26466. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26467. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26468. }
  26469. for (int i = 0; i < 500 && !done; i++) {
  26470. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26471. }
  26472. ASSERT_TRUE(done);
  26473. EXPECT_EQ(expected, received);
  26474. // Far under the 200 ms between the pieces, however loaded the machine
  26475. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26476. }
  26477. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26478. // The header's first byte, then its second with half the mask key, then
  26479. // the rest: what a frame written in several writes may look like when
  26480. // Nagle's algorithm holds the later ones back for an ACK.
  26481. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26482. check_bounded_read_resumes(
  26483. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26484. }
  26485. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26486. check_bounded_read_resumes(
  26487. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26488. }
  26489. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26490. Server svr;
  26491. svr.set_websocket_ping_interval(0);
  26492. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26493. std::string msg;
  26494. while (ws.read(msg)) {}
  26495. });
  26496. auto port = svr.bind_to_any_port("127.0.0.1");
  26497. std::thread t([&]() { svr.listen_after_bind(); });
  26498. auto se = detail::scope_exit([&] {
  26499. svr.stop();
  26500. t.join();
  26501. });
  26502. svr.wait_until_ready();
  26503. // Each Close payload and the reply it should get: an echo when valid, 1002
  26504. // otherwise.
  26505. std::vector<std::pair<std::string, std::string>> cases = {
  26506. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26507. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26508. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26509. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26510. };
  26511. // Also between the fragments of a message.
  26512. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26513. for (const auto &c : cases) {
  26514. auto sock = connect_raw_websocket(port, "/ws");
  26515. ASSERT_NE(INVALID_SOCKET, sock);
  26516. auto frames = prefix + masked_frame(0x88, c.first);
  26517. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26518. std::string reply;
  26519. char buf[256];
  26520. while (reply.size() < 2 + c.second.size()) {
  26521. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26522. if (n <= 0) { break; }
  26523. reply.append(buf, static_cast<size_t>(n));
  26524. }
  26525. detail::close_socket(sock);
  26526. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26527. c.second,
  26528. reply);
  26529. }
  26530. }
  26531. }
  26532. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26533. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26534. protected:
  26535. void SetUp() override {
  26536. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26537. SERVER_PRIVATE_KEY_FILE);
  26538. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26539. std::string msg;
  26540. ws::ReadResult ret;
  26541. while ((ret = ws.read(msg))) {
  26542. if (ret == ws::Binary) {
  26543. ws.send(msg.data(), msg.size());
  26544. } else {
  26545. ws.send(msg);
  26546. }
  26547. }
  26548. });
  26549. port_ = server_->bind_to_any_port(HOST);
  26550. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26551. server_->wait_until_ready();
  26552. }
  26553. void TearDown() override {
  26554. server_->stop();
  26555. if (server_thread_.joinable()) { server_thread_.join(); }
  26556. }
  26557. std::unique_ptr<SSLServer> server_;
  26558. std::thread server_thread_;
  26559. int port_ = 0;
  26560. };
  26561. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26562. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26563. {
  26564. ws::WebSocketClient client(url);
  26565. client.enable_server_certificate_verification(false);
  26566. auto calls = 0;
  26567. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26568. calls++;
  26569. return false;
  26570. });
  26571. EXPECT_FALSE(client.connect());
  26572. EXPECT_GT(calls, 0);
  26573. }
  26574. {
  26575. ws::WebSocketClient client(url);
  26576. client.enable_server_certificate_verification(false);
  26577. client.set_session_verifier([](tls::session_t) {
  26578. return SSLVerifierResponse::CertificateRejected;
  26579. });
  26580. EXPECT_FALSE(client.connect());
  26581. }
  26582. {
  26583. ws::WebSocketClient client(url);
  26584. client.enable_server_certificate_verification(false);
  26585. client.set_session_verifier([](tls::session_t) {
  26586. return SSLVerifierResponse::CertificateAccepted;
  26587. });
  26588. EXPECT_TRUE(client.connect());
  26589. }
  26590. }
  26591. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26592. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26593. "/ws-echo");
  26594. client.enable_server_certificate_verification(false);
  26595. ASSERT_TRUE(client.connect());
  26596. ASSERT_TRUE(client.is_open());
  26597. ASSERT_TRUE(client.send("Hello WSS"));
  26598. std::string msg;
  26599. EXPECT_EQ(ws::Text, client.read(msg));
  26600. EXPECT_EQ("Hello WSS", msg);
  26601. client.close();
  26602. }
  26603. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26604. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26605. "/ws-echo");
  26606. client.enable_server_certificate_verification(false);
  26607. EXPECT_TRUE(client.connect());
  26608. }
  26609. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26610. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26611. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26612. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26613. // client (without calling close() first) is the only path that runs
  26614. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26615. // bug exactly.
  26616. //
  26617. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26618. // when linked against an instrumented libssl; run under Valgrind to catch it
  26619. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26620. // suite (the freed session otherwise stalls on the close handshake) — this test
  26621. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26622. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26623. {
  26624. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26625. "/ws-echo");
  26626. client.enable_server_certificate_verification(false);
  26627. client.set_read_timeout(2, 0);
  26628. client.set_write_timeout(2, 0);
  26629. ASSERT_TRUE(client.connect());
  26630. ASSERT_TRUE(client.is_open());
  26631. ASSERT_TRUE(client.send("still open"));
  26632. // Intentionally do NOT call client.close(): leaving scope runs
  26633. // shutdown_and_close() with the WebSocket still open, which must send the
  26634. // close frame while the TLS session is still alive.
  26635. }
  26636. }
  26637. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26638. // shutdown_and_close() at the start of connect(), reproducing the same
  26639. // use-after-free within the test body rather than at scope exit. The second
  26640. // connect must succeed and echo, proving the close handshake ran over a live
  26641. // session. See the note above about memory-tool requirements.
  26642. TEST_F(WebSocketSSLIntegrationTest,
  26643. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26644. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26645. "/ws-echo");
  26646. client.enable_server_certificate_verification(false);
  26647. client.set_read_timeout(2, 0);
  26648. client.set_write_timeout(2, 0);
  26649. ASSERT_TRUE(client.connect());
  26650. ASSERT_TRUE(client.is_open());
  26651. ASSERT_TRUE(client.send("still open"));
  26652. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26653. // the still-open connection, which must not touch a freed TLS session.
  26654. ASSERT_TRUE(client.connect());
  26655. ASSERT_TRUE(client.is_open());
  26656. ASSERT_TRUE(client.send("after reconnect"));
  26657. std::string msg;
  26658. EXPECT_EQ(ws::Text, client.read(msg));
  26659. EXPECT_EQ("after reconnect", msg);
  26660. client.close();
  26661. }
  26662. #endif
  26663. #ifdef CPPHTTPLIB_SSL_ENABLED
  26664. class WebSocketSSLCATest : public ::testing::Test {
  26665. protected:
  26666. void SetUp() override {
  26667. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26668. SERVER_PRIVATE_KEY_FILE);
  26669. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26670. std::string msg;
  26671. while (ws.read(msg)) {
  26672. ws.send(msg);
  26673. }
  26674. });
  26675. port_ = server_->bind_to_any_port("127.0.0.1");
  26676. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26677. server_->wait_until_ready();
  26678. }
  26679. void TearDown() override {
  26680. server_->stop();
  26681. if (server_thread_.joinable()) { server_thread_.join(); }
  26682. }
  26683. std::string url() const {
  26684. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26685. }
  26686. std::unique_ptr<SSLServer> server_;
  26687. std::thread server_thread_;
  26688. int port_ = 0;
  26689. };
  26690. // A custom CA loaded as PEM verifies the server with full certificate
  26691. // verification enabled
  26692. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26693. ws::WebSocketClient client(url());
  26694. std::string cert;
  26695. read_file(SERVER_CERT2_FILE, cert);
  26696. client.load_ca_cert_store(cert.c_str(), cert.size());
  26697. ASSERT_TRUE(client.connect());
  26698. ASSERT_TRUE(client.send("hello"));
  26699. std::string msg;
  26700. EXPECT_EQ(ws::Text, client.read(msg));
  26701. EXPECT_EQ("hello", msg);
  26702. client.close();
  26703. }
  26704. // A custom CA that does not cover the server must fail verification (the
  26705. // custom CA is exclusive; system certs are not loaded alongside it)
  26706. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26707. ws::WebSocketClient client(url());
  26708. std::string cert;
  26709. read_file(CLIENT_CA_CERT_FILE, cert);
  26710. client.load_ca_cert_store(cert.c_str(), cert.size());
  26711. auto res = client.connect();
  26712. ASSERT_FALSE(res);
  26713. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26714. EXPECT_EQ(-1, res.status());
  26715. EXPECT_NE(0u, res.ssl_backend_error());
  26716. }
  26717. // The same CA as a file path rather than PEM in memory
  26718. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26719. ws::WebSocketClient client(url());
  26720. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26721. ASSERT_TRUE(client.connect());
  26722. ASSERT_TRUE(client.send("hello"));
  26723. std::string msg;
  26724. EXPECT_EQ(ws::Text, client.read(msg));
  26725. EXPECT_EQ("hello", msg);
  26726. client.close();
  26727. }
  26728. // ...and a CA file that does not cover the server still fails, so it is the
  26729. // path above that decides the outcome
  26730. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26731. ws::WebSocketClient client(url());
  26732. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26733. ASSERT_FALSE(client.connect());
  26734. }
  26735. // Regression test: reconnecting with a native custom CA store used to reuse
  26736. // a store handle the previous TLS context had already freed (use-after-free
  26737. // under the OpenSSL backend). The context now lives as long as the client.
  26738. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26739. ws::WebSocketClient client(url());
  26740. std::string cert;
  26741. read_file(SERVER_CERT2_FILE, cert);
  26742. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26743. ASSERT_TRUE(client.connect());
  26744. client.close();
  26745. ASSERT_TRUE(client.connect());
  26746. ASSERT_TRUE(client.send("again"));
  26747. std::string msg;
  26748. EXPECT_EQ(ws::Text, client.read(msg));
  26749. EXPECT_EQ("again", msg);
  26750. client.close();
  26751. }
  26752. // Regression test: a certificate with a trusted chain but no identity match
  26753. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26754. // verification entirely for IP hosts, so this connection succeeded there.
  26755. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26756. // chain verification while the identity check must still fail.
  26757. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26759. ASSERT_TRUE(svr.is_valid());
  26760. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26761. std::string msg;
  26762. while (ws.read(msg)) {
  26763. ws.send(msg);
  26764. }
  26765. });
  26766. auto port = svr.bind_to_any_port("127.0.0.1");
  26767. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26768. auto se = detail::scope_exit([&] {
  26769. svr.stop();
  26770. t.join();
  26771. });
  26772. svr.wait_until_ready();
  26773. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26774. "/echo");
  26775. std::string cert;
  26776. read_file(SERVER_CERT_FILE, cert);
  26777. client.load_ca_cert_store(cert.c_str(), cert.size());
  26778. ASSERT_FALSE(client.connect());
  26779. }
  26780. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26781. // SNI, so nothing binds the host name to the TLS session. These bind the
  26782. // server to "localhost" instead, the only shape that exercises the SNI and
  26783. // hostname-verification path with certificate verification left enabled.
  26784. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26785. protected:
  26786. void Start(const char *cert_file) {
  26787. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26788. SERVER_PRIVATE_KEY_FILE);
  26789. ASSERT_TRUE(server_->is_valid());
  26790. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26791. std::string msg;
  26792. while (ws.read(msg)) {
  26793. ws.send(msg);
  26794. }
  26795. });
  26796. port_ = server_->bind_to_any_port("localhost");
  26797. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26798. server_->wait_until_ready();
  26799. }
  26800. void TearDown() override {
  26801. if (server_) { server_->stop(); }
  26802. if (server_thread_.joinable()) { server_thread_.join(); }
  26803. }
  26804. std::string url() const {
  26805. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26806. }
  26807. std::unique_ptr<SSLServer> server_;
  26808. std::thread server_thread_;
  26809. int port_ = 0;
  26810. };
  26811. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26812. // out and the connection is usable
  26813. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26814. Start(SERVER_CERT2_FILE);
  26815. ws::WebSocketClient client(url());
  26816. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26817. ASSERT_TRUE(client.connect());
  26818. ASSERT_TRUE(client.send("hello"));
  26819. std::string msg;
  26820. EXPECT_EQ(ws::Text, client.read(msg));
  26821. EXPECT_EQ("hello", msg);
  26822. client.close();
  26823. }
  26824. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26825. // while the identity check must still reject "localhost"
  26826. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26827. Start(SERVER_CERT_FILE);
  26828. ws::WebSocketClient client(url());
  26829. client.set_ca_cert_path(SERVER_CERT_FILE);
  26830. auto res = client.connect();
  26831. ASSERT_FALSE(res);
  26832. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26833. EXPECT_EQ(-1, res.status());
  26834. }
  26835. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26836. // disabled: the chain is still checked, only the identity check is skipped
  26837. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26838. Start(SERVER_CERT_FILE);
  26839. ws::WebSocketClient client(url());
  26840. client.set_ca_cert_path(SERVER_CERT_FILE);
  26841. client.enable_server_hostname_verification(false);
  26842. ASSERT_TRUE(client.connect());
  26843. ASSERT_TRUE(client.send("hello"));
  26844. std::string msg;
  26845. EXPECT_EQ(ws::Text, client.read(msg));
  26846. EXPECT_EQ("hello", msg);
  26847. client.close();
  26848. }
  26849. // A CA that did not sign the server certificate fails the chain, even though
  26850. // the name would match
  26851. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26852. Start(SERVER_CERT2_FILE);
  26853. ws::WebSocketClient client(url());
  26854. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26855. ASSERT_FALSE(client.connect());
  26856. }
  26857. // With verification disabled, neither the chain nor the name is checked
  26858. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26859. Start(SERVER_CERT_FILE);
  26860. ws::WebSocketClient client(url());
  26861. client.enable_server_certificate_verification(false);
  26862. ASSERT_TRUE(client.connect());
  26863. ASSERT_TRUE(client.send("hello"));
  26864. std::string msg;
  26865. EXPECT_EQ(ws::Text, client.read(msg));
  26866. EXPECT_EQ("hello", msg);
  26867. client.close();
  26868. }
  26869. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26870. protected:
  26871. void SetUp() override {
  26872. server_ = httplib::detail::make_unique<SSLServer>(
  26873. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26874. ASSERT_TRUE(server_->is_valid());
  26875. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26876. std::string msg;
  26877. while (ws.read(msg)) {
  26878. ws.send(msg);
  26879. }
  26880. });
  26881. port_ = server_->bind_to_any_port("localhost");
  26882. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26883. server_->wait_until_ready();
  26884. }
  26885. void TearDown() override {
  26886. server_->stop();
  26887. if (server_thread_.joinable()) { server_thread_.join(); }
  26888. }
  26889. std::string url() const {
  26890. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26891. }
  26892. void ConnectWithClientCert(const std::string &client_cert_file,
  26893. const std::string &client_private_key_file,
  26894. const char *private_key_password) {
  26895. std::string cert_pem, key_pem;
  26896. read_file(client_cert_file, cert_pem);
  26897. read_file(client_private_key_file, key_pem);
  26898. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26899. key_pem.c_str(), key_pem.size(),
  26900. private_key_password};
  26901. ConnectWithPem(pem);
  26902. }
  26903. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26904. ws::WebSocketClient client(url(), pem);
  26905. ASSERT_TRUE(client.is_valid());
  26906. client.enable_server_certificate_verification(false);
  26907. ASSERT_TRUE(client.connect());
  26908. ASSERT_TRUE(client.send("hello"));
  26909. std::string msg;
  26910. EXPECT_EQ(ws::Text, client.read(msg));
  26911. EXPECT_EQ("hello", msg);
  26912. client.close();
  26913. }
  26914. std::unique_ptr<SSLServer> server_;
  26915. std::thread server_thread_;
  26916. int port_ = 0;
  26917. };
  26918. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26919. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26920. }
  26921. // Control for the tests above: the fixture's server really does require a
  26922. // client certificate, so it is the PEM the constructor installed that decides
  26923. // the outcome.
  26924. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26925. ws::WebSocketClient client(url());
  26926. ASSERT_TRUE(client.is_valid());
  26927. client.enable_server_certificate_verification(false);
  26928. EXPECT_FALSE(client.connect());
  26929. }
  26930. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26931. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26932. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26933. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26934. }
  26935. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26936. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26937. std::string cert_pem, key_pem;
  26938. read_file(CLIENT_CERT_FILE, cert_pem);
  26939. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26940. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26941. std::vector<char> key(key_pem.begin(), key_pem.end());
  26942. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26943. key.size(), nullptr};
  26944. ConnectWithPem(pem);
  26945. }
  26946. #endif
  26947. #if !defined(_WIN32)
  26948. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26949. auto secret_dir = std::string("./symlink_test_secret");
  26950. auto served_dir = std::string("./symlink_test_served");
  26951. auto secret_file = secret_dir + "/secret.txt";
  26952. auto symlink_path = served_dir + "/escape";
  26953. // Setup: create directories and files
  26954. mkdir(secret_dir.c_str(), 0755);
  26955. mkdir(served_dir.c_str(), 0755);
  26956. {
  26957. std::ofstream ofs(secret_file);
  26958. ofs << "SECRET_DATA";
  26959. }
  26960. // Create symlink using absolute path so it resolves correctly
  26961. #ifdef PATH_MAX
  26962. char abs_secret[PATH_MAX];
  26963. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26964. #else
  26965. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26966. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26967. ASSERT_NE(nullptr, abs_secret);
  26968. #endif
  26969. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26970. auto se = detail::scope_exit([&] {
  26971. unlink(symlink_path.c_str());
  26972. unlink(secret_file.c_str());
  26973. rmdir(served_dir.c_str());
  26974. rmdir(secret_dir.c_str());
  26975. });
  26976. Server svr;
  26977. svr.set_mount_point("/", served_dir);
  26978. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26979. auto se2 = detail::scope_exit([&] {
  26980. svr.stop();
  26981. listen_thread.join();
  26982. });
  26983. svr.wait_until_ready();
  26984. Client cli("localhost", PORT);
  26985. // Symlink pointing outside base dir should be blocked
  26986. auto res = cli.Get("/escape/secret.txt");
  26987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26988. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26989. }
  26990. #else
  26991. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26992. auto secret_dir = std::string("junction_test_secret");
  26993. auto served_dir = std::string("junction_test_served");
  26994. auto secret_file = secret_dir + "\\secret.txt";
  26995. auto junction_path = served_dir + "\\escape";
  26996. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26997. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26998. {
  26999. std::ofstream ofs(secret_file);
  27000. ofs << "SECRET_DATA";
  27001. }
  27002. // A junction needs no privilege to create, unlike a symlink
  27003. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27004. ASSERT_EQ(0, std::system(cmd.c_str()));
  27005. auto se = detail::scope_exit([&] {
  27006. ::RemoveDirectoryA(junction_path.c_str());
  27007. std::remove(secret_file.c_str());
  27008. ::RemoveDirectoryA(served_dir.c_str());
  27009. ::RemoveDirectoryA(secret_dir.c_str());
  27010. });
  27011. Server svr;
  27012. svr.set_mount_point("/", served_dir);
  27013. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27014. auto se2 = detail::scope_exit([&] {
  27015. svr.stop();
  27016. listen_thread.join();
  27017. });
  27018. svr.wait_until_ready();
  27019. Client cli("localhost", PORT);
  27020. // Junction pointing outside base dir should be blocked
  27021. auto res = cli.Get("/escape/secret.txt");
  27022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27023. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27024. }
  27025. #endif
  27026. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27027. // "GET /smuggled" request), reads the first response, and only then sends the
  27028. // embedded request as the body. Returns how many times /smuggled ran.
  27029. //
  27030. // The body is sent AFTER receiving the first response (as in the original
  27031. // PoC) so that the stream_line_reader cannot buffer it together with the
  27032. // headers of the first request.
  27033. static int count_smuggled_requests(const std::string &outer_head,
  27034. std::string &first_response) {
  27035. Server svr;
  27036. svr.set_mount_point("/", "./www");
  27037. std::atomic<int> smuggled_count(0);
  27038. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27039. smuggled_count++;
  27040. res.set_content("oops", "text/plain");
  27041. });
  27042. svr.Post("/post", [&](const Request &req, Response &res) {
  27043. res.set_content(req.body, "text/plain");
  27044. });
  27045. auto port = svr.bind_to_any_port("localhost");
  27046. thread t = thread([&] { svr.listen_after_bind(); });
  27047. auto se = detail::scope_exit([&] {
  27048. svr.stop();
  27049. t.join();
  27050. });
  27051. svr.wait_until_ready();
  27052. auto error = Error::Success;
  27053. auto sock = detail::create_client_socket(
  27054. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27055. /*connection_timeout_sec=*/2, 0,
  27056. /*read_timeout_sec=*/2, 0,
  27057. /*write_timeout_sec=*/2, 0, std::string(), error);
  27058. EXPECT_NE(INVALID_SOCKET, sock);
  27059. if (sock == INVALID_SOCKET) { return -1; }
  27060. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27061. // The "smuggled" request will be sent as the body of the outer request
  27062. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27063. "Host: localhost\r\n"
  27064. "Connection: close\r\n"
  27065. "\r\n";
  27066. auto head = outer_head;
  27067. auto len = std::to_string(smuggled.size());
  27068. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27069. pos = head.find("{len}", pos + len.size())) {
  27070. head.replace(pos, 5, len);
  27071. }
  27072. // Step 1: Send only the outer request headers (no body yet)
  27073. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27074. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27075. // Step 2: Read the first response
  27076. char buf[4096];
  27077. for (;;) {
  27078. auto n = recv(sock, buf, sizeof(buf), 0);
  27079. if (n <= 0) break;
  27080. first_response.append(buf, static_cast<size_t>(n));
  27081. // Stop once we have a complete response (headers + body)
  27082. auto hdr_end = first_response.find("\r\n\r\n");
  27083. if (hdr_end != std::string::npos) {
  27084. // Check for Content-Length to know when the body is complete
  27085. auto cl_pos = first_response.find("Content-Length:");
  27086. if (cl_pos != std::string::npos) {
  27087. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27088. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27089. auto cl = std::stoul(
  27090. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27091. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27092. } else {
  27093. break; // No Content-Length, assume headers-only response
  27094. }
  27095. }
  27096. }
  27097. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27098. // vulnerable server the keep-alive loop reads this as a second request. The
  27099. // server may already have closed the connection, so the result is ignored.
  27100. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27101. // Half-close so that a server which drained the body sees EOF and closes,
  27102. // instead of the read below waiting for the read timeout.
  27103. #ifdef _WIN32
  27104. ::shutdown(sock, SD_SEND);
  27105. #else
  27106. ::shutdown(sock, SHUT_WR);
  27107. #endif
  27108. // Step 4: Read until the server closes the connection
  27109. for (;;) {
  27110. auto n = recv(sock, buf, sizeof(buf), 0);
  27111. if (n <= 0) break;
  27112. }
  27113. return smuggled_count.load();
  27114. }
  27115. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27116. // A GET request with Content-Length to a static file handler must have its
  27117. // body drained before the keep-alive connection is reused. Otherwise the
  27118. // unread body bytes are interpreted as the next HTTP request.
  27119. std::string first_response;
  27120. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27121. "Host: localhost\r\n"
  27122. "Content-Length: {len}\r\n"
  27123. "\r\n",
  27124. first_response));
  27125. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27126. }
  27127. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27128. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27129. // be answered with 400 and the connection closed. Treating it as "no body"
  27130. // leaves the body to be parsed as the next request.
  27131. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27132. const char *targets[] = {
  27133. "GET /file", // handler that never reads the body
  27134. "GET /not-found", // no handler matches (404)
  27135. "POST /post", // handler that reads the body
  27136. };
  27137. for (auto target : targets) {
  27138. for (auto value : values) {
  27139. std::string first_response;
  27140. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27141. " HTTP/1.1\r\n"
  27142. "Host: localhost\r\n"
  27143. "Content-Length: " +
  27144. value + "\r\n\r\n",
  27145. first_response))
  27146. << target << " with Content-Length: " << value;
  27147. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27148. << target << " with Content-Length: " << value;
  27149. }
  27150. }
  27151. }
  27152. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27153. // A 400 for an unparseable request line leaves the rest of the message
  27154. // unread, so the connection must be closed rather than reused.
  27155. std::string first_response;
  27156. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27157. "Host: localhost\r\n"
  27158. "Content-Length: {len}\r\n"
  27159. "\r\n",
  27160. first_response));
  27161. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27162. }
  27163. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27164. // Same as above for a header block that fails to parse.
  27165. std::string first_response;
  27166. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27167. "Host: localhost\r\n"
  27168. "Bad Header\r\n"
  27169. "Content-Length: {len}\r\n"
  27170. "\r\n",
  27171. first_response));
  27172. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27173. }
  27174. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27175. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27176. // server must not read another request on that connection, even when the
  27177. // request had no body to drain.
  27178. std::string first_response;
  27179. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27180. "Host: localhost\r\n"
  27181. "\r\n",
  27182. first_response));
  27183. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27184. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27185. }
  27186. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27187. // A content reader that stops early leaves the stream inside the body.
  27188. // Draining the whole Content-Length from there, or reading the body again,
  27189. // reads into the next request, and whatever follows is parsed as a request
  27190. // of its own.
  27191. Server svr;
  27192. std::atomic<int> smuggled_count(0);
  27193. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27194. svr.Post("/upload", [](const Request &req, Response &res,
  27195. const ContentReader &content_reader) {
  27196. // Stop at the last chunk, so the whole body has been read however it
  27197. // arrives.
  27198. auto length = req.get_header_value_u64("Content-Length");
  27199. size_t total = 0;
  27200. auto consumed = content_reader([&](const char *, size_t n) {
  27201. total += n;
  27202. return total < length;
  27203. });
  27204. EXPECT_FALSE(consumed);
  27205. if (req.has_param("retry")) {
  27206. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27207. }
  27208. // Replace the 400 the aborted read set, which would close the connection.
  27209. res.set_redirect("/done");
  27210. });
  27211. auto port = svr.bind_to_any_port(HOST);
  27212. thread t = thread([&] { svr.listen_after_bind(); });
  27213. auto se = detail::scope_exit([&] {
  27214. svr.stop();
  27215. t.join();
  27216. });
  27217. svr.wait_until_ready();
  27218. // A front end sees the second request as a POST whose body is the GET. The
  27219. // first body is as long as the POST's headers, so draining it again reads
  27220. // exactly those and leaves the GET to be parsed next.
  27221. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27222. "Host: localhost\r\n"
  27223. "\r\n";
  27224. std::string second_head = "POST /post HTTP/1.1\r\n"
  27225. "Host: localhost\r\n"
  27226. "Content-Length: " +
  27227. std::to_string(inner.size()) +
  27228. "\r\n"
  27229. "\r\n";
  27230. for (auto target : {"/upload", "/upload?retry"}) {
  27231. smuggled_count = 0;
  27232. std::string request = "POST " + std::string(target) +
  27233. " HTTP/1.1\r\n"
  27234. "Host: localhost\r\n"
  27235. "Content-Length: " +
  27236. std::to_string(second_head.size()) +
  27237. "\r\n"
  27238. "\r\n" +
  27239. std::string(second_head.size(), 'A') + second_head +
  27240. inner;
  27241. std::string response;
  27242. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27243. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27244. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27245. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27246. EXPECT_EQ(0, smuggled_count.load()) << target;
  27247. }
  27248. }
  27249. // An error response closes the connection anyway, so the body is left unread
  27250. // with a redirect, such as one to a login page.
  27251. static void serve_redirects(Server &svr,
  27252. const std::function<void(int)> &client) {
  27253. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27254. res.set_redirect("/login");
  27255. return Server::HandlerResponse::Handled;
  27256. });
  27257. auto port = svr.bind_to_any_port(HOST);
  27258. ASSERT_GT(port, 0);
  27259. thread t = thread([&] { svr.listen_after_bind(); });
  27260. auto se = detail::scope_exit([&] {
  27261. svr.stop();
  27262. t.join();
  27263. ASSERT_FALSE(svr.is_running());
  27264. });
  27265. svr.wait_until_ready();
  27266. client(port);
  27267. }
  27268. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27269. Server svr;
  27270. serve_redirects(svr, [](int port) {
  27271. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27272. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27273. std::to_string(body.size()) + "\r\n\r\n" + body +
  27274. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27275. std::string resp;
  27276. ASSERT_TRUE(send_request(1, req, &resp, port));
  27277. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27278. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27279. });
  27280. }
  27281. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27282. Server svr;
  27283. svr.set_read_timeout(0, 200000);
  27284. serve_redirects(svr, [](int port) {
  27285. // A byte every 100 ms keeps each read within the read timeout, but not the
  27286. // body as a whole, so the server closes and the bytes sent after that fail.
  27287. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27288. "Content-Length: 10\r\n\r\n"};
  27289. parts.resize(11, "x");
  27290. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27291. });
  27292. }
  27293. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27294. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27295. // must be rejected with 400 Bad Request.
  27296. Server svr;
  27297. svr.Post("/test", [&](const Request &, Response &res) {
  27298. res.set_content("ok", "text/plain");
  27299. });
  27300. thread t = thread([&] { svr.listen(HOST, PORT); });
  27301. auto se = detail::scope_exit([&] {
  27302. svr.stop();
  27303. t.join();
  27304. ASSERT_FALSE(svr.is_running());
  27305. });
  27306. svr.wait_until_ready();
  27307. // Exact "chunked"
  27308. {
  27309. auto req = "POST /test HTTP/1.1\r\n"
  27310. "Host: localhost\r\n"
  27311. "Content-Length: 5\r\n"
  27312. "Transfer-Encoding: chunked\r\n"
  27313. "Connection: close\r\n"
  27314. "\r\n"
  27315. "hello";
  27316. std::string response;
  27317. ASSERT_TRUE(send_request(1, req, &response));
  27318. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27319. response.substr(0, response.find("\r\n")));
  27320. }
  27321. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27322. {
  27323. auto req = "POST /test HTTP/1.1\r\n"
  27324. "Host: localhost\r\n"
  27325. "Content-Length: 5\r\n"
  27326. "Transfer-Encoding: gzip, chunked\r\n"
  27327. "Connection: close\r\n"
  27328. "\r\n"
  27329. "hello";
  27330. std::string response;
  27331. ASSERT_TRUE(send_request(1, req, &response));
  27332. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27333. response.substr(0, response.find("\r\n")));
  27334. }
  27335. }
  27336. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27337. Server svr;
  27338. svr.Post("/test", [&](const Request &, Response &res) {
  27339. res.set_content("ok", "text/plain");
  27340. });
  27341. thread t = thread([&] { svr.listen(HOST, PORT); });
  27342. auto se = detail::scope_exit([&] {
  27343. svr.stop();
  27344. t.join();
  27345. ASSERT_FALSE(svr.is_running());
  27346. });
  27347. svr.wait_until_ready();
  27348. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27349. // length cannot be determined, so the server must answer 400 and close
  27350. // rather than treat the request as bodyless and leave the body in the
  27351. // socket for the next request to pick up.
  27352. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27353. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27354. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27355. std::string response;
  27356. ASSERT_TRUE(send_request(1, req, &response));
  27357. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27358. response.substr(0, response.find("\r\n")))
  27359. << transfer_encoding;
  27360. }
  27361. // RFC 9110 5.3: the codings may also be split across several
  27362. // Transfer-Encoding lines, which combine in the order they were received.
  27363. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27364. // just like the single-line "chunked, gzip" above.
  27365. {
  27366. auto req = "POST /test HTTP/1.1\r\n"
  27367. "Host: localhost\r\n"
  27368. "Transfer-Encoding: chunked\r\n"
  27369. "Transfer-Encoding: gzip\r\n"
  27370. "\r\n"
  27371. "0\r\n\r\n";
  27372. std::string response;
  27373. ASSERT_TRUE(send_request(1, req, &response));
  27374. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27375. response.substr(0, response.find("\r\n")));
  27376. }
  27377. }
  27378. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27379. Server svr;
  27380. svr.Post("/test", [&](const Request &, Response &res) {
  27381. res.set_content("ok", "text/plain");
  27382. });
  27383. auto port = svr.bind_to_any_port(HOST);
  27384. ASSERT_GT(port, 0);
  27385. thread t = thread([&] { svr.listen_after_bind(); });
  27386. auto se = detail::scope_exit([&] {
  27387. svr.stop();
  27388. t.join();
  27389. ASSERT_FALSE(svr.is_running());
  27390. });
  27391. svr.wait_until_ready();
  27392. for (auto transfer_encoding :
  27393. {"Transfer-Encoding: gzip, chunked\r\n",
  27394. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27395. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27396. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27397. transfer_encoding + "\r\n0\r\n\r\n";
  27398. std::string response;
  27399. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27400. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27401. response.substr(0, response.find("\r\n")))
  27402. << transfer_encoding;
  27403. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27404. << transfer_encoding;
  27405. }
  27406. }
  27407. // Regression for issue #2450: a DELETE without Content-Length on a
  27408. // keep-alive connection must not let the post-response drain consume the
  27409. // next request's bytes.
  27410. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27411. Server svr;
  27412. std::atomic<int> delete_count(0);
  27413. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27414. delete_count++;
  27415. res.status = StatusCode::NoContent_204;
  27416. });
  27417. auto port = svr.bind_to_any_port(HOST);
  27418. thread t = thread([&] { svr.listen_after_bind(); });
  27419. auto se = detail::scope_exit([&] {
  27420. svr.stop();
  27421. t.join();
  27422. });
  27423. svr.wait_until_ready();
  27424. auto error = Error::Success;
  27425. auto sock = detail::create_client_socket(
  27426. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27427. /*connection_timeout_sec=*/2, 0,
  27428. /*read_timeout_sec=*/2, 0,
  27429. /*write_timeout_sec=*/2, 0, std::string(), error);
  27430. ASSERT_NE(INVALID_SOCKET, sock);
  27431. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27432. auto send_request_and_read_response = [&](const std::string &req,
  27433. std::string &out) -> bool {
  27434. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27435. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27436. char buf[4096];
  27437. for (;;) {
  27438. auto n = recv(sock, buf, sizeof(buf), 0);
  27439. if (n <= 0) { return !out.empty(); }
  27440. out.append(buf, static_cast<size_t>(n));
  27441. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27442. }
  27443. };
  27444. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27445. "Host: localhost\r\n"
  27446. "\r\n";
  27447. std::string resp1;
  27448. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27449. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27450. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27451. "Host: localhost\r\n"
  27452. "Connection: close\r\n"
  27453. "\r\n";
  27454. std::string resp2;
  27455. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27456. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27457. EXPECT_EQ(2, delete_count.load());
  27458. }
  27459. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27460. Server svr;
  27461. svr.Post("/ingest", [&](const Request &, Response &res,
  27462. const ContentReader &content_reader) {
  27463. auto consumed = content_reader([](const char *, size_t) { return false; });
  27464. EXPECT_FALSE(consumed);
  27465. res.status = StatusCode::Conflict_409;
  27466. res.set_header("Connection", "close");
  27467. });
  27468. auto port = svr.bind_to_any_port(HOST);
  27469. thread t = thread([&] { svr.listen_after_bind(); });
  27470. auto se = detail::scope_exit([&] {
  27471. svr.stop();
  27472. t.join();
  27473. });
  27474. svr.wait_until_ready();
  27475. auto error = Error::Success;
  27476. auto sock = detail::create_client_socket(
  27477. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27478. /*connection_timeout_sec=*/2, 0,
  27479. /*read_timeout_sec=*/1, 0,
  27480. /*write_timeout_sec=*/2, 0, std::string(), error);
  27481. ASSERT_NE(INVALID_SOCKET, sock);
  27482. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27483. std::string request = "POST /ingest HTTP/1.1\r\n"
  27484. "Host: localhost\r\n"
  27485. "Transfer-Encoding: chunked\r\n"
  27486. "\r\n"
  27487. "4\r\n"
  27488. "data\r\n";
  27489. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27490. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27491. std::string response;
  27492. ssize_t received = 0;
  27493. do {
  27494. char buf[4096];
  27495. received = recv(sock, buf, sizeof(buf), 0);
  27496. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27497. } while (received > 0);
  27498. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27499. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27500. EXPECT_EQ(0, received);
  27501. }
  27502. namespace no_proxy_test {
  27503. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27504. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27505. // calling listen().
  27506. class ScopedServer {
  27507. public:
  27508. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27509. ~ScopedServer() {
  27510. svr_.stop();
  27511. if (th_.joinable()) { th_.join(); }
  27512. }
  27513. Server &svr() { return svr_; }
  27514. int port() const { return port_; }
  27515. void listen() {
  27516. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27517. svr_.wait_until_ready();
  27518. }
  27519. private:
  27520. Server svr_;
  27521. std::thread th_;
  27522. int port_ = 0;
  27523. };
  27524. class ProxyAndTargetServers {
  27525. public:
  27526. ProxyAndTargetServers() {
  27527. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27528. proxy_hits_++;
  27529. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27530. res.set_content("via-proxy", "text/plain");
  27531. });
  27532. target_.Get(".*", [this](const Request &req, Response &res) {
  27533. target_hits_++;
  27534. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27535. res.set_content("direct", "text/plain");
  27536. });
  27537. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27538. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27539. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27540. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27541. proxy_mock_.wait_until_ready();
  27542. target_.wait_until_ready();
  27543. }
  27544. ~ProxyAndTargetServers() {
  27545. proxy_mock_.stop();
  27546. target_.stop();
  27547. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27548. if (target_thread_.joinable()) { target_thread_.join(); }
  27549. }
  27550. Server &proxy_mock() { return proxy_mock_; }
  27551. Server &target() { return target_; }
  27552. int proxy_port() const { return proxy_port_; }
  27553. int target_port() const { return target_port_; }
  27554. int proxy_hits() const { return proxy_hits_.load(); }
  27555. int target_hits() const { return target_hits_.load(); }
  27556. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27557. void reset_counters() {
  27558. proxy_hits_ = 0;
  27559. target_hits_ = 0;
  27560. last_had_proxy_authz_ = false;
  27561. }
  27562. private:
  27563. Server proxy_mock_;
  27564. Server target_;
  27565. std::thread proxy_thread_;
  27566. std::thread target_thread_;
  27567. int proxy_port_ = 0;
  27568. int target_port_ = 0;
  27569. std::atomic<int> proxy_hits_{0};
  27570. std::atomic<int> target_hits_{0};
  27571. std::atomic<bool> last_had_proxy_authz_{false};
  27572. };
  27573. inline std::unique_ptr<Client> make_client(const std::string &host,
  27574. ProxyAndTargetServers &s) {
  27575. auto cli = detail::make_unique<Client>(host, s.target_port());
  27576. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27577. cli->set_proxy("127.0.0.1", s.proxy_port());
  27578. return cli;
  27579. }
  27580. } // namespace no_proxy_test
  27581. using no_proxy_test::make_client;
  27582. using no_proxy_test::ProxyAndTargetServers;
  27583. // A stream request carries the credentials a buffered request does
  27584. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27585. no_proxy_test::ScopedServer origin;
  27586. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27587. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27588. });
  27589. origin.listen();
  27590. Client cli("127.0.0.1", origin.port());
  27591. cli.set_basic_auth("user", "pass");
  27592. auto handle = cli.open_stream("GET", "/x");
  27593. ASSERT_TRUE(handle.is_valid());
  27594. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27595. Client bearer("127.0.0.1", origin.port());
  27596. bearer.set_bearer_token_auth("tok");
  27597. auto handle2 = bearer.open_stream("GET", "/x");
  27598. ASSERT_TRUE(handle2.is_valid());
  27599. EXPECT_EQ("Bearer tok", read_all(handle2));
  27600. }
  27601. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27602. // takes its own credentials, as for a buffered request
  27603. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27604. std::string target, authz, proxy_authz;
  27605. no_proxy_test::ScopedServer proxy;
  27606. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27607. target = req.target;
  27608. authz = req.get_header_value("Authorization");
  27609. proxy_authz = req.get_header_value("Proxy-Authorization");
  27610. res.set_content("ok", "text/plain");
  27611. });
  27612. proxy.listen();
  27613. Client cli("origin.example", 8080);
  27614. cli.set_proxy("127.0.0.1", proxy.port());
  27615. cli.set_proxy_basic_auth("puser", "ppass");
  27616. cli.set_basic_auth("user", "pass");
  27617. auto handle = cli.open_stream("GET", "/x");
  27618. ASSERT_TRUE(handle.is_valid());
  27619. EXPECT_EQ("ok", read_all(handle));
  27620. EXPECT_EQ("http://origin.example:8080/x", target);
  27621. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27622. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27623. }
  27624. // In absolute-form the path follows the authority, so a path that does not
  27625. // begin with '/' would make the proxy connect to another host
  27626. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27627. std::vector<std::string> targets;
  27628. no_proxy_test::ScopedServer proxy;
  27629. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27630. targets.push_back(req.target);
  27631. res.set_content("ok", "text/plain");
  27632. });
  27633. proxy.listen();
  27634. Client cli("origin.example", 8080);
  27635. cli.set_proxy("127.0.0.1", proxy.port());
  27636. cli.set_basic_auth("user", "pass");
  27637. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27638. auto res = cli.Get(path);
  27639. EXPECT_FALSE(res) << path;
  27640. auto handle = cli.open_stream("GET", path);
  27641. EXPECT_FALSE(handle.is_valid()) << path;
  27642. }
  27643. EXPECT_TRUE(targets.empty());
  27644. auto res = cli.Get("/x");
  27645. ASSERT_TRUE(res);
  27646. ASSERT_EQ(1u, targets.size());
  27647. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27648. }
  27649. TEST(NoProxyTest, ExactHostnameBypasses) {
  27650. ProxyAndTargetServers s;
  27651. auto cli = make_client("example.com", s);
  27652. cli->set_no_proxy({"example.com"});
  27653. auto res = cli->Get("/");
  27654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27655. EXPECT_EQ(0, s.proxy_hits());
  27656. EXPECT_EQ(1, s.target_hits());
  27657. }
  27658. TEST(NoProxyTest, SubdomainBypasses) {
  27659. ProxyAndTargetServers s;
  27660. auto cli = make_client("foo.example.com", s);
  27661. cli->set_no_proxy({"example.com"});
  27662. auto res = cli->Get("/");
  27663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27664. EXPECT_EQ(0, s.proxy_hits());
  27665. EXPECT_EQ(1, s.target_hits());
  27666. }
  27667. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27668. // Regression guard: "evilexample.com" must not be considered a subdomain
  27669. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27670. // check would let traffic bypass the proxy and leak credentials direct
  27671. // to the attacker host.
  27672. ProxyAndTargetServers s;
  27673. auto cli = make_client("evilexample.com", s);
  27674. cli->set_no_proxy({"example.com"});
  27675. auto res = cli->Get("/");
  27676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27677. EXPECT_GE(s.proxy_hits(), 1);
  27678. EXPECT_EQ(0, s.target_hits());
  27679. }
  27680. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27681. ProxyAndTargetServers s;
  27682. auto cli = make_client("example.com.evil.com", s);
  27683. cli->set_no_proxy({"example.com"});
  27684. auto res = cli->Get("/");
  27685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27686. EXPECT_GE(s.proxy_hits(), 1);
  27687. EXPECT_EQ(0, s.target_hits());
  27688. }
  27689. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27690. ProxyAndTargetServers s;
  27691. auto cli = make_client("example.com", s);
  27692. cli->set_no_proxy({".example.com"});
  27693. auto res = cli->Get("/");
  27694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27695. EXPECT_EQ(0, s.proxy_hits());
  27696. EXPECT_EQ(1, s.target_hits());
  27697. }
  27698. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27699. ProxyAndTargetServers s;
  27700. auto cli = make_client("Example.COM", s);
  27701. cli->set_no_proxy({"EXAMPLE.com"});
  27702. auto res = cli->Get("/");
  27703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27704. EXPECT_EQ(0, s.proxy_hits());
  27705. EXPECT_EQ(1, s.target_hits());
  27706. }
  27707. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27708. ProxyAndTargetServers s;
  27709. auto cli = make_client("example.com.", s);
  27710. cli->set_no_proxy({"example.com"});
  27711. auto res = cli->Get("/");
  27712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27713. EXPECT_EQ(0, s.proxy_hits());
  27714. EXPECT_EQ(1, s.target_hits());
  27715. }
  27716. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27717. // Trailing dots must be normalized on BOTH sides — host and entry.
  27718. // An implementation that only strips the host-side trailing dot would
  27719. // fail to match host "example.com" against entry "example.com." because
  27720. // a literal substring search would compare 11 chars against 12.
  27721. ProxyAndTargetServers s;
  27722. auto cli = make_client("example.com", s);
  27723. cli->set_no_proxy({"example.com."});
  27724. auto res = cli->Get("/");
  27725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27726. EXPECT_EQ(0, s.proxy_hits());
  27727. EXPECT_EQ(1, s.target_hits());
  27728. }
  27729. TEST(NoProxyTest, WildcardBypassesEverything) {
  27730. ProxyAndTargetServers s;
  27731. auto cli = make_client("anything.invalid.test", s);
  27732. cli->set_no_proxy({"*"});
  27733. auto res = cli->Get("/");
  27734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27735. EXPECT_EQ(0, s.proxy_hits());
  27736. EXPECT_EQ(1, s.target_hits());
  27737. }
  27738. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27739. ProxyAndTargetServers s;
  27740. Client cli("127.0.0.1", s.target_port());
  27741. cli.set_proxy("127.0.0.1", s.proxy_port());
  27742. cli.set_no_proxy({"127.0.0.1"});
  27743. auto res = cli.Get("/");
  27744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27745. EXPECT_EQ(0, s.proxy_hits());
  27746. EXPECT_EQ(1, s.target_hits());
  27747. }
  27748. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27749. ProxyAndTargetServers s;
  27750. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27751. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27752. cli.set_proxy("127.0.0.1", s.proxy_port());
  27753. cli.set_no_proxy({"::1"});
  27754. auto res = cli.Get("/");
  27755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27756. EXPECT_EQ(0, s.proxy_hits());
  27757. EXPECT_EQ(1, s.target_hits());
  27758. }
  27759. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27760. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27761. // must still be recognized as IPv6 for CIDR matching. Implementations
  27762. // that detect IPv6 only when the host begins with '[' would parse the
  27763. // host as a hostname and miss the match.
  27764. ProxyAndTargetServers s;
  27765. Client cli("fe80::1", s.target_port());
  27766. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27767. cli.set_proxy("127.0.0.1", s.proxy_port());
  27768. cli.set_no_proxy({"fe80::/10"});
  27769. auto res = cli.Get("/");
  27770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27771. EXPECT_EQ(0, s.proxy_hits());
  27772. EXPECT_EQ(1, s.target_hits());
  27773. }
  27774. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27775. ProxyAndTargetServers s;
  27776. Client cli("::1", s.target_port());
  27777. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27778. cli.set_proxy("127.0.0.1", s.proxy_port());
  27779. cli.set_no_proxy({"[::1]"});
  27780. auto res = cli.Get("/");
  27781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27782. EXPECT_EQ(0, s.proxy_hits());
  27783. EXPECT_EQ(1, s.target_hits());
  27784. }
  27785. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27786. ProxyAndTargetServers s;
  27787. Client cli("fe80::1", s.target_port());
  27788. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27789. cli.set_proxy("127.0.0.1", s.proxy_port());
  27790. cli.set_no_proxy({"[fe80::]/10"});
  27791. auto res = cli.Get("/");
  27792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27793. EXPECT_EQ(0, s.proxy_hits());
  27794. EXPECT_EQ(1, s.target_hits());
  27795. }
  27796. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27797. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27798. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27799. // tricks via address-family conversion.
  27800. ProxyAndTargetServers s;
  27801. Client cli("::ffff:127.0.0.1", s.target_port());
  27802. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27803. cli.set_proxy("127.0.0.1", s.proxy_port());
  27804. cli.set_no_proxy({"127.0.0.1"});
  27805. auto res = cli.Get("/");
  27806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27807. EXPECT_GE(s.proxy_hits(), 1);
  27808. EXPECT_EQ(0, s.target_hits());
  27809. }
  27810. TEST(NoProxyTest, IPv4CidrMatch) {
  27811. ProxyAndTargetServers s;
  27812. Client cli("127.0.0.1", s.target_port());
  27813. cli.set_proxy("127.0.0.1", s.proxy_port());
  27814. cli.set_no_proxy({"127.0.0.0/8"});
  27815. auto res = cli.Get("/");
  27816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27817. EXPECT_EQ(0, s.proxy_hits());
  27818. EXPECT_EQ(1, s.target_hits());
  27819. }
  27820. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27821. ProxyAndTargetServers s;
  27822. Client cli("127.0.0.1", s.target_port());
  27823. cli.set_proxy("127.0.0.1", s.proxy_port());
  27824. cli.set_no_proxy({"10.0.0.0/8"});
  27825. auto res = cli.Get("/");
  27826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27827. EXPECT_GE(s.proxy_hits(), 1);
  27828. EXPECT_EQ(0, s.target_hits());
  27829. }
  27830. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27831. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27832. // IPv4 target matches.
  27833. ProxyAndTargetServers s;
  27834. Client cli("127.0.0.1", s.target_port());
  27835. cli.set_proxy("127.0.0.1", s.proxy_port());
  27836. cli.set_no_proxy({"0.0.0.0/0"});
  27837. auto res = cli.Get("/");
  27838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27839. EXPECT_EQ(0, s.proxy_hits());
  27840. EXPECT_EQ(1, s.target_hits());
  27841. }
  27842. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27843. ProxyAndTargetServers s;
  27844. Client cli("127.0.0.1", s.target_port());
  27845. cli.set_proxy("127.0.0.1", s.proxy_port());
  27846. cli.set_no_proxy({"127.0.0.1"});
  27847. auto res = cli.Get("/");
  27848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27849. EXPECT_EQ(0, s.proxy_hits());
  27850. EXPECT_EQ(1, s.target_hits());
  27851. }
  27852. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27853. ProxyAndTargetServers s;
  27854. Client cli("127.0.0.1", s.target_port());
  27855. cli.set_proxy("127.0.0.1", s.proxy_port());
  27856. cli.set_no_proxy({"127.0.0.0/33"});
  27857. auto res = cli.Get("/");
  27858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27859. EXPECT_GE(s.proxy_hits(), 1);
  27860. EXPECT_EQ(0, s.target_hits());
  27861. }
  27862. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27863. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27864. ProxyAndTargetServers s;
  27865. Client cli("127.0.0.1", s.target_port());
  27866. cli.set_proxy("127.0.0.1", s.proxy_port());
  27867. cli.set_no_proxy({"127.0.0.1/"});
  27868. auto res = cli.Get("/");
  27869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27870. EXPECT_GE(s.proxy_hits(), 1);
  27871. EXPECT_EQ(0, s.target_hits());
  27872. }
  27873. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27874. ProxyAndTargetServers s;
  27875. auto cli = make_client("internal.corp", s);
  27876. cli->set_proxy_basic_auth("u", "p");
  27877. cli->set_no_proxy({"internal.corp"});
  27878. auto res = cli->Get("/");
  27879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27880. EXPECT_EQ(1, s.target_hits());
  27881. EXPECT_EQ(0, s.proxy_hits());
  27882. EXPECT_FALSE(s.last_had_proxy_authz())
  27883. << "Proxy-Authorization must not be sent direct to the target";
  27884. }
  27885. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27886. ProxyAndTargetServers s;
  27887. auto cli = make_client("public.example", s);
  27888. cli->set_proxy_basic_auth("u", "p");
  27889. cli->set_no_proxy({"internal.corp"}); // does not match
  27890. auto res = cli->Get("/");
  27891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27892. EXPECT_GE(s.proxy_hits(), 1);
  27893. EXPECT_TRUE(s.last_had_proxy_authz());
  27894. }
  27895. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27896. std::atomic<int> hits{0};
  27897. std::atomic<int> hits_with_authz{0};
  27898. no_proxy_test::ScopedServer proxy_mock;
  27899. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27900. hits++;
  27901. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27902. if (req.target.find("/redir") != std::string::npos) {
  27903. res.set_redirect("http://other.example/landed");
  27904. } else {
  27905. res.set_content("via-proxy", "text/plain");
  27906. }
  27907. });
  27908. proxy_mock.listen();
  27909. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27910. hits = 0;
  27911. hits_with_authz = 0;
  27912. Client cli("public.example", 80);
  27913. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27914. cli.set_proxy_basic_auth(c.first, c.second);
  27915. cli.set_follow_location(true);
  27916. // The redirect to another host goes through the proxy as well
  27917. auto res = cli.Get("/redir");
  27918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27919. EXPECT_EQ(2, hits.load());
  27920. EXPECT_EQ(2, hits_with_authz.load());
  27921. }
  27922. }
  27923. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27924. ProxyAndTargetServers s;
  27925. auto cli = make_client("anything.test", s);
  27926. auto res = cli->Get("/");
  27927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27928. EXPECT_GE(s.proxy_hits(), 1);
  27929. EXPECT_EQ(0, s.target_hits());
  27930. }
  27931. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27932. ProxyAndTargetServers s;
  27933. auto cli = make_client("example.com", s);
  27934. cli->set_no_proxy({"example.com:8080"});
  27935. auto res = cli->Get("/");
  27936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27937. EXPECT_GE(s.proxy_hits(), 1);
  27938. EXPECT_EQ(0, s.target_hits());
  27939. }
  27940. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27941. ProxyAndTargetServers s;
  27942. auto cli = make_client("anything.test", s);
  27943. cli->set_no_proxy({"", " ", "\t"});
  27944. auto res = cli->Get("/");
  27945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27946. EXPECT_GE(s.proxy_hits(), 1);
  27947. EXPECT_EQ(0, s.target_hits());
  27948. }
  27949. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27950. // An entry with leading/trailing whitespace must still match — env-style
  27951. // values are commonly pasted with stray spaces and an implementation
  27952. // that feeds the raw token directly to inet_pton would fail to match
  27953. // valid CIDRs because of the spaces.
  27954. ProxyAndTargetServers s;
  27955. Client cli("127.0.0.1", s.target_port());
  27956. cli.set_proxy("127.0.0.1", s.proxy_port());
  27957. cli.set_no_proxy({" 127.0.0.0/8 "});
  27958. auto res = cli.Get("/");
  27959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27960. EXPECT_EQ(0, s.proxy_hits());
  27961. EXPECT_EQ(1, s.target_hits());
  27962. }
  27963. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27964. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27965. // go direct and must NOT carry Proxy-Authorization.
  27966. std::atomic<int> proxy_hits{0};
  27967. std::atomic<int> target_hits{0};
  27968. std::atomic<bool> target_saw_authz{false};
  27969. no_proxy_test::ScopedServer proxy_mock, target;
  27970. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27971. proxy_hits++;
  27972. res.status = 302;
  27973. res.set_header("Location", "http://127.0.0.1:" +
  27974. std::to_string(target.port()) + "/landed");
  27975. });
  27976. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27977. target_hits++;
  27978. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27979. res.set_content("direct", "text/plain");
  27980. });
  27981. proxy_mock.listen();
  27982. target.listen();
  27983. Client cli("public.example", target.port());
  27984. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27985. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27986. cli.set_proxy_basic_auth("u", "p");
  27987. cli.set_no_proxy({"127.0.0.1"});
  27988. cli.set_follow_location(true);
  27989. auto res = cli.Get("/redir");
  27990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27991. EXPECT_GE(proxy_hits.load(), 1);
  27992. EXPECT_GE(target_hits.load(), 1);
  27993. EXPECT_FALSE(target_saw_authz.load());
  27994. }
  27995. #ifdef CPPHTTPLIB_SSL_ENABLED
  27996. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27997. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27998. // proxy creds would be sent to the (possibly hostile) origin.
  27999. std::atomic<int> target_hits{0};
  28000. std::atomic<bool> target_saw_proxy_authz{false};
  28001. no_proxy_test::ScopedServer target;
  28002. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28003. target_hits++;
  28004. if (req.has_header("Proxy-Authorization")) {
  28005. target_saw_proxy_authz = true;
  28006. }
  28007. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28008. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28009. "nonce=\"abc\", algorithm=MD5");
  28010. });
  28011. target.listen();
  28012. // The proxy address is set to the target's port: the bypass MUST kick in;
  28013. // if it doesn't, the test still routes "via proxy" to the same server and
  28014. // the Proxy-Authorization assertion below catches the leak.
  28015. Client cli("evil.example", target.port());
  28016. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28017. cli.set_proxy("127.0.0.1", target.port());
  28018. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28019. cli.set_no_proxy({"evil.example"});
  28020. auto res = cli.Get("/x");
  28021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28022. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28023. EXPECT_EQ(1, target_hits.load());
  28024. EXPECT_FALSE(target_saw_proxy_authz.load());
  28025. }
  28026. #endif
  28027. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28028. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28029. std::atomic<int> proxy_hits{0};
  28030. std::atomic<int> bypass_hits{0};
  28031. std::atomic<bool> proxy_saw_c_url{false};
  28032. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28033. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28034. proxy_hits++;
  28035. if (req.path.find("/start") != std::string::npos) {
  28036. res.status = 302;
  28037. res.set_header("Location", "http://127.0.0.1:" +
  28038. std::to_string(bypass_server.port()) +
  28039. "/middle");
  28040. return;
  28041. }
  28042. if (req.path.find("/end") != std::string::npos) {
  28043. proxy_saw_c_url = true;
  28044. res.set_content("c-via-proxy", "text/plain");
  28045. return;
  28046. }
  28047. res.set_content("unexpected", "text/plain");
  28048. });
  28049. // public.example's "advertised" port is arbitrary (the request never lands
  28050. // there — it goes through the proxy), but use a dynamic value to stay
  28051. // friendly with sharded parallel runs.
  28052. int public_port = bypass_server.port();
  28053. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28054. bypass_hits++;
  28055. res.status = 302;
  28056. res.set_header("Location", "http://public.example:" +
  28057. std::to_string(public_port) + "/end");
  28058. });
  28059. proxy_mock.listen();
  28060. bypass_server.listen();
  28061. Client cli("public.example", public_port);
  28062. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28063. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28064. cli.set_no_proxy({"127.0.0.1"});
  28065. cli.set_follow_location(true);
  28066. auto res = cli.Get("/start");
  28067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28068. EXPECT_EQ(StatusCode::OK_200, res->status);
  28069. EXPECT_EQ("c-via-proxy", res->body);
  28070. EXPECT_GE(proxy_hits.load(), 2);
  28071. EXPECT_GE(bypass_hits.load(), 1);
  28072. EXPECT_TRUE(proxy_saw_c_url.load());
  28073. }
  28074. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28075. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28076. // request reconnects to the correct endpoint.
  28077. std::atomic<int> proxy_hits{0};
  28078. std::atomic<int> target_hits{0};
  28079. no_proxy_test::ScopedServer proxy_mock, target;
  28080. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28081. proxy_hits++;
  28082. res.set_content("via-proxy", "text/plain");
  28083. });
  28084. target.svr().Get(".*", [&](const Request &, Response &res) {
  28085. target_hits++;
  28086. res.set_content("direct", "text/plain");
  28087. });
  28088. proxy_mock.listen();
  28089. target.listen();
  28090. Client cli("public.example", target.port());
  28091. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28092. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28093. cli.set_keep_alive(true);
  28094. auto res1 = cli.Get("/a");
  28095. ASSERT_TRUE(res1);
  28096. EXPECT_EQ("via-proxy", res1->body);
  28097. EXPECT_EQ(1, proxy_hits.load());
  28098. EXPECT_EQ(0, target_hits.load());
  28099. cli.set_no_proxy({"public.example"});
  28100. auto res2 = cli.Get("/b");
  28101. ASSERT_TRUE(res2);
  28102. EXPECT_EQ("direct", res2->body);
  28103. EXPECT_EQ(1, proxy_hits.load());
  28104. EXPECT_EQ(1, target_hits.load());
  28105. }
  28106. // Forward declarations (see the base64_encode note).
  28107. namespace httplib {
  28108. namespace detail {
  28109. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28110. int shutdown_socket(socket_t sock) noexcept;
  28111. } // namespace detail
  28112. } // namespace httplib
  28113. namespace proxy_tunnel_test {
  28114. const char *const kTunnelEstablished =
  28115. "HTTP/1.1 200 Connection established\r\n\r\n";
  28116. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28117. using ConnectReply = std::function<std::string(const std::string &head)>;
  28118. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28119. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28120. class ScopedConnectProxy {
  28121. public:
  28122. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28123. : forward_port_(forward_port), reply_(std::move(reply)) {
  28124. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28125. if (listen_sock_ == INVALID_SOCKET) { return; }
  28126. auto a = loopback(0);
  28127. auto addr = reinterpret_cast<sockaddr *>(&a);
  28128. socklen_t alen = sizeof(a);
  28129. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28130. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28131. ::listen(listen_sock_, 4) != 0) {
  28132. return;
  28133. }
  28134. port_ = ntohs(a.sin_port);
  28135. th_ = std::thread([this] { run(); });
  28136. }
  28137. ~ScopedConnectProxy() {
  28138. if (th_.joinable()) {
  28139. stop_ = true;
  28140. auto wake = connect_to(port_);
  28141. th_.join();
  28142. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28143. }
  28144. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28145. }
  28146. int port() const { return port_; }
  28147. int connect_hits() const { return connect_hits_.load(); }
  28148. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28149. std::string connect_request() const {
  28150. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28151. return connect_request_;
  28152. }
  28153. private:
  28154. static sockaddr_in loopback(int port) {
  28155. sockaddr_in a{};
  28156. a.sin_family = AF_INET;
  28157. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28158. a.sin_port = htons(static_cast<unsigned short>(port));
  28159. return a;
  28160. }
  28161. static socket_t connect_to(int port) {
  28162. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28163. if (sock == INVALID_SOCKET) { return sock; }
  28164. auto a = loopback(port);
  28165. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28166. detail::close_socket(sock);
  28167. return INVALID_SOCKET;
  28168. }
  28169. return sock;
  28170. }
  28171. static bool send_all(socket_t sock, const char *data, size_t size) {
  28172. while (size > 0) {
  28173. auto n = detail::send_socket(sock, data, size, 0);
  28174. if (n <= 0) { return false; }
  28175. data += n;
  28176. size -= static_cast<size_t>(n);
  28177. }
  28178. return true;
  28179. }
  28180. void run() {
  28181. for (;;) {
  28182. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28183. if (stop_) {
  28184. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28185. return;
  28186. }
  28187. if (client == INVALID_SOCKET) { continue; }
  28188. serve(client);
  28189. detail::close_socket(client);
  28190. }
  28191. }
  28192. void serve(socket_t client) {
  28193. std::string head;
  28194. char buf[2048];
  28195. while (head.find("\r\n\r\n") == std::string::npos) {
  28196. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28197. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28198. if (n <= 0) { return; }
  28199. head.append(buf, static_cast<size_t>(n));
  28200. }
  28201. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28202. connect_hits_++;
  28203. {
  28204. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28205. connect_request_ = head;
  28206. }
  28207. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28208. if (!send_all(client, res.data(), res.size()) ||
  28209. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28210. return;
  28211. }
  28212. auto origin = connect_to(forward_port_);
  28213. if (origin == INVALID_SOCKET) { return; }
  28214. // When either side stops, shut both down so the other pump returns too.
  28215. auto pump = [&](socket_t from, socket_t to) {
  28216. char b[8192];
  28217. for (;;) {
  28218. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28219. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28220. }
  28221. detail::shutdown_socket(client);
  28222. detail::shutdown_socket(origin);
  28223. };
  28224. std::thread up([&] { pump(client, origin); });
  28225. pump(origin, client);
  28226. up.join();
  28227. detail::close_socket(origin);
  28228. }
  28229. int forward_port_;
  28230. ConnectReply reply_;
  28231. socket_t listen_sock_ = INVALID_SOCKET;
  28232. int port_ = 0;
  28233. std::thread th_;
  28234. std::atomic<bool> stop_{false};
  28235. std::atomic<int> connect_hits_{0};
  28236. mutable std::mutex connect_request_mutex_;
  28237. std::string connect_request_;
  28238. };
  28239. } // namespace proxy_tunnel_test
  28240. #ifdef CPPHTTPLIB_SSL_ENABLED
  28241. namespace proxy_tunnel_test {
  28242. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28243. class ScopedSSLServer {
  28244. public:
  28245. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28246. port_ = svr_.bind_to_any_port("127.0.0.1");
  28247. }
  28248. ~ScopedSSLServer() {
  28249. svr_.stop();
  28250. if (th_.joinable()) { th_.join(); }
  28251. }
  28252. SSLServer &svr() { return svr_; }
  28253. int port() const { return port_; }
  28254. void listen() {
  28255. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28256. svr_.wait_until_ready();
  28257. }
  28258. private:
  28259. SSLServer svr_;
  28260. std::thread th_;
  28261. int port_ = 0;
  28262. };
  28263. // Sends one request through the CONNECT proxy to the TLS origin with a
  28264. // credential configured for each hop, and checks that each credential reaches
  28265. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28266. // origin's (every header in origin_headers) on the tunnelled request.
  28267. void CredentialsStayWithTheirHop(
  28268. const std::function<void(SSLClient &)> &set_credentials,
  28269. const std::string &scheme,
  28270. const std::vector<std::string> &origin_headers = {"Authorization"},
  28271. bool stream = false) {
  28272. std::atomic<int> origin_hits{0};
  28273. std::atomic<bool> origin_saw_proxy_authz{false};
  28274. std::atomic<bool> origin_saw_headers{false};
  28275. ScopedSSLServer origin;
  28276. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28277. origin_hits++;
  28278. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28279. origin_saw_headers =
  28280. std::all_of(origin_headers.begin(), origin_headers.end(),
  28281. [&](const std::string &h) { return req.has_header(h); });
  28282. res.set_content("ok", "text/plain");
  28283. });
  28284. origin.listen();
  28285. ScopedConnectProxy proxy(origin.port());
  28286. ASSERT_NE(0, proxy.port());
  28287. // Pinned to 127.0.0.1 for the same reason as the test below.
  28288. SSLClient cli("127.0.0.1", origin.port());
  28289. cli.enable_server_certificate_verification(false);
  28290. cli.set_proxy("127.0.0.1", proxy.port());
  28291. set_credentials(cli);
  28292. if (stream) {
  28293. auto handle = cli.open_stream("GET", "/x");
  28294. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28295. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28296. } else {
  28297. auto res = cli.Get("/x");
  28298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28299. EXPECT_EQ(StatusCode::OK_200, res->status);
  28300. }
  28301. EXPECT_EQ(1, origin_hits.load());
  28302. EXPECT_EQ(1, proxy.connect_hits());
  28303. EXPECT_TRUE(origin_saw_headers.load());
  28304. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28305. << "Proxy-Authorization must not be sent inside the tunnel";
  28306. auto connect_req = proxy.connect_request();
  28307. EXPECT_NE(std::string::npos,
  28308. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28309. for (const auto &h : origin_headers) {
  28310. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28311. << h << " must not be sent to the proxy on CONNECT";
  28312. }
  28313. }
  28314. } // namespace proxy_tunnel_test
  28315. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28316. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28317. [](SSLClient &cli) {
  28318. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28319. cli.set_basic_auth("origin-user", "origin-pass");
  28320. },
  28321. "Basic");
  28322. }
  28323. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28324. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28325. [](SSLClient &cli) {
  28326. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28327. cli.set_basic_auth("origin-user", "origin-pass");
  28328. },
  28329. "Basic", {"Authorization"}, true);
  28330. }
  28331. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28332. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28333. [](SSLClient &cli) {
  28334. cli.set_proxy_bearer_token_auth("proxy-token");
  28335. cli.set_bearer_token_auth("origin-token");
  28336. },
  28337. "Bearer");
  28338. }
  28339. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28340. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28341. [](SSLClient &cli) {
  28342. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28343. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28344. {"Cookie", "sid=origin-session"},
  28345. {"X-Api-Key", "origin-key"}});
  28346. },
  28347. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28348. }
  28349. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28350. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28351. // retry; otherwise proxy creds would be sent to the origin.
  28352. std::atomic<int> origin_hits{0};
  28353. std::atomic<bool> origin_saw_proxy_authz{false};
  28354. proxy_tunnel_test::ScopedSSLServer origin;
  28355. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28356. origin_hits++;
  28357. if (req.has_header("Proxy-Authorization")) {
  28358. origin_saw_proxy_authz = true;
  28359. }
  28360. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28361. res.set_header("Proxy-Authenticate",
  28362. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28363. "algorithm=MD5");
  28364. });
  28365. origin.listen();
  28366. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28367. ASSERT_NE(0, proxy.port());
  28368. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28369. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28370. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28371. // and answer with its own status, making this test flaky.
  28372. SSLClient cli("127.0.0.1", origin.port());
  28373. cli.enable_server_certificate_verification(false);
  28374. cli.set_proxy("127.0.0.1", proxy.port());
  28375. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28376. auto res = cli.Get("/x");
  28377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28378. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28379. EXPECT_EQ(1, origin_hits.load());
  28380. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28381. EXPECT_EQ(1, proxy.connect_hits());
  28382. }
  28383. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28384. std::string origin_sni;
  28385. std::string origin_host;
  28386. proxy_tunnel_test::ScopedSSLServer origin;
  28387. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28388. origin_sni = req.sni();
  28389. origin_host = req.get_header_value("Host");
  28390. res.set_content("ok", "text/plain");
  28391. });
  28392. origin.listen();
  28393. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28394. ASSERT_NE(0, proxy.port());
  28395. SSLClient cli("origin.example", origin.port());
  28396. cli.enable_server_certificate_verification(false);
  28397. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28398. cli.set_proxy("127.0.0.1", proxy.port());
  28399. auto res = cli.Get("/x");
  28400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28401. EXPECT_EQ(StatusCode::OK_200, res->status);
  28402. auto port = std::to_string(origin.port());
  28403. auto target = "127.0.0.1:" + port;
  28404. auto connect_req = proxy.connect_request();
  28405. EXPECT_EQ(1, proxy.connect_hits());
  28406. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28407. EXPECT_NE(std::string::npos,
  28408. connect_req.find("\r\nHost: " + target + "\r\n"));
  28409. EXPECT_EQ("origin.example", origin_sni);
  28410. EXPECT_EQ("origin.example:" + port, origin_host);
  28411. }
  28412. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28413. proxy_tunnel_test::ScopedSSLServer origin;
  28414. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28415. res.set_content("ok", "text/plain");
  28416. });
  28417. origin.listen();
  28418. proxy_tunnel_test::ScopedConnectProxy proxy(
  28419. origin.port(), [](const std::string &head) -> std::string {
  28420. if (head.find(
  28421. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28422. std::string::npos) {
  28423. return proxy_tunnel_test::kTunnelEstablished;
  28424. }
  28425. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28426. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28427. "nonce=\"abc\", algorithm=MD5\r\n"
  28428. "Content-Length: 0\r\n\r\n";
  28429. });
  28430. ASSERT_NE(0, proxy.port());
  28431. SSLClient cli("origin.example", origin.port());
  28432. cli.enable_server_certificate_verification(false);
  28433. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28434. cli.set_proxy("127.0.0.1", proxy.port());
  28435. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28436. auto res = cli.Get("/x");
  28437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28438. EXPECT_EQ(StatusCode::OK_200, res->status);
  28439. // The retried CONNECT is the one the proxy saw last.
  28440. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28441. auto connect_req = proxy.connect_request();
  28442. EXPECT_EQ(2, proxy.connect_hits());
  28443. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28444. EXPECT_NE(std::string::npos,
  28445. connect_req.find("\r\nHost: " + target + "\r\n"));
  28446. }
  28447. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28448. proxy_tunnel_test::ScopedSSLServer origin;
  28449. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28450. res.set_content("ok", "text/plain");
  28451. });
  28452. origin.listen();
  28453. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28454. ASSERT_NE(0, proxy.port());
  28455. SSLClient cli("origin.example", origin.port());
  28456. cli.enable_server_certificate_verification(false);
  28457. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28458. cli.set_proxy("127.0.0.1", proxy.port());
  28459. auto res = cli.Get("/x");
  28460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28461. EXPECT_EQ(StatusCode::OK_200, res->status);
  28462. auto target = "origin.example:" + std::to_string(origin.port());
  28463. auto connect_req = proxy.connect_request();
  28464. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28465. EXPECT_NE(std::string::npos,
  28466. connect_req.find("\r\nHost: " + target + "\r\n"));
  28467. }
  28468. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28469. proxy_tunnel_test::ScopedSSLServer origin;
  28470. auto port = std::to_string(origin.port());
  28471. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28472. res.set_redirect("https://next.example:" + port + "/y");
  28473. });
  28474. origin.svr().Get("/y", [](const Request &, Response &res) {
  28475. res.set_content("ok", "text/plain");
  28476. });
  28477. origin.listen();
  28478. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28479. ASSERT_NE(0, proxy.port());
  28480. SSLClient cli("origin.example", origin.port());
  28481. cli.enable_server_certificate_verification(false);
  28482. cli.set_tunnel_hostname_addr_map(
  28483. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28484. cli.set_proxy("127.0.0.1", proxy.port());
  28485. cli.set_follow_location(true);
  28486. auto res = cli.Get("/x");
  28487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28488. EXPECT_EQ("ok", res->body);
  28489. // The last CONNECT is the redirect client's.
  28490. ASSERT_EQ(2, proxy.connect_hits());
  28491. auto target = "127.0.0.1:" + port;
  28492. auto connect_req = proxy.connect_request();
  28493. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28494. EXPECT_NE(std::string::npos,
  28495. connect_req.find("\r\nHost: " + target + "\r\n"));
  28496. }
  28497. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28498. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28499. std::atomic<int> origin_hits{0};
  28500. proxy_tunnel_test::ScopedSSLServer origin;
  28501. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28502. origin_hits++;
  28503. res.set_content("ok", "text/plain");
  28504. });
  28505. origin.listen();
  28506. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28507. ASSERT_NE(0, proxy.port());
  28508. SSLClient cli("127.0.0.1", origin.port());
  28509. cli.enable_server_certificate_verification(false);
  28510. cli.set_proxy("127.0.0.1", proxy.port());
  28511. cli.set_keep_alive(true);
  28512. cli.set_session_verifier(
  28513. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28514. auto res = cli.Get("/x");
  28515. EXPECT_FALSE(res);
  28516. ASSERT_FALSE(cli.is_socket_open());
  28517. res = cli.Get("/x");
  28518. EXPECT_FALSE(res);
  28519. EXPECT_EQ(2, proxy.connect_hits());
  28520. auto handle = cli.open_stream("GET", "/x");
  28521. EXPECT_FALSE(handle.is_valid());
  28522. EXPECT_EQ(3, proxy.connect_hits());
  28523. EXPECT_EQ(0, origin_hits.load());
  28524. }
  28525. #endif
  28526. namespace proxy_tunnel_test {
  28527. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28528. // anything else gets a 407 with `challenge`.
  28529. ConnectReply require_proxy_auth(const std::string &expected,
  28530. const std::string &challenge) {
  28531. return [=](const std::string &head) -> std::string {
  28532. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28533. std::string::npos) {
  28534. return kTunnelEstablished;
  28535. }
  28536. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28537. "Proxy-Authenticate: " +
  28538. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28539. };
  28540. }
  28541. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28542. // request, then echoes.
  28543. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28544. ws.send(
  28545. "authorization:" + req.get_header_value("Authorization") +
  28546. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28547. std::string msg;
  28548. while (ws.read(msg)) {
  28549. ws.send(msg);
  28550. }
  28551. }
  28552. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28553. class ScopedWebSocketOrigin {
  28554. public:
  28555. ScopedWebSocketOrigin() {
  28556. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28557. server_.listen();
  28558. }
  28559. int port() const { return server_.port(); }
  28560. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28561. std::string url() const {
  28562. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28563. }
  28564. private:
  28565. no_proxy_test::ScopedServer server_;
  28566. };
  28567. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28568. // passed as a constructor header, and checks that each reaches only its hop.
  28569. void WebSocketCredentialsStayWithTheirHop(
  28570. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28571. const std::string &proxy_authz, const std::string &origin_authz) {
  28572. ScopedWebSocketOrigin origin;
  28573. ScopedConnectProxy proxy(
  28574. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28575. ASSERT_NE(0, proxy.port());
  28576. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28577. client.set_proxy("127.0.0.1", proxy.port());
  28578. set_proxy_credentials(client);
  28579. auto res = client.connect();
  28580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28581. std::string msg;
  28582. ASSERT_TRUE(client.read(msg));
  28583. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28584. client.close();
  28585. EXPECT_EQ(1, proxy.connect_hits());
  28586. EXPECT_EQ(std::string::npos,
  28587. proxy.connect_request().find("\r\nAuthorization: "))
  28588. << "origin credentials must not be sent to the proxy";
  28589. }
  28590. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28591. void WebSocketSetterCredentialsStayWithTheirHop(
  28592. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28593. const std::string &proxy_authz, const std::string &origin_authz) {
  28594. ScopedWebSocketOrigin origin;
  28595. ScopedConnectProxy proxy(
  28596. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28597. ASSERT_NE(0, proxy.port());
  28598. ws::WebSocketClient client(origin.url());
  28599. client.set_proxy("127.0.0.1", proxy.port());
  28600. set_credentials(client);
  28601. auto res = client.connect();
  28602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28603. std::string msg;
  28604. ASSERT_TRUE(client.read(msg));
  28605. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28606. client.close();
  28607. EXPECT_EQ(1, proxy.connect_hits());
  28608. EXPECT_EQ(std::string::npos,
  28609. proxy.connect_request().find("\r\nAuthorization: "))
  28610. << "origin credentials must not be sent to the proxy";
  28611. }
  28612. } // namespace proxy_tunnel_test
  28613. namespace {
  28614. // Connects `client` and returns the Authorization header its upgrade
  28615. // request carried, or "<failed>" when the connection could not be opened.
  28616. std::string websocket_authorization(ws::WebSocketClient &client) {
  28617. if (!client.connect()) { return "<failed>"; }
  28618. std::string msg;
  28619. if (!client.read(msg)) { return "<failed>"; }
  28620. client.close();
  28621. auto prefix = std::string("authorization:");
  28622. auto end = msg.find("|proxy-authorization:");
  28623. return msg.substr(prefix.size(), end - prefix.size());
  28624. }
  28625. } // namespace
  28626. TEST(WebSocketClientAuthTest, BasicAuth) {
  28627. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28628. ws::WebSocketClient client(origin.url());
  28629. client.set_basic_auth("user", "pass");
  28630. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28631. websocket_authorization(client));
  28632. }
  28633. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28634. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28635. ws::WebSocketClient client(origin.url());
  28636. client.set_basic_auth("user", "");
  28637. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28638. websocket_authorization(client));
  28639. }
  28640. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28641. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28642. ws::WebSocketClient client(origin.url());
  28643. client.set_bearer_token_auth("token123");
  28644. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28645. }
  28646. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28647. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28648. ws::WebSocketClient client(origin.url());
  28649. client.set_bearer_token_auth("token123");
  28650. client.set_basic_auth("user", "pass");
  28651. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28652. websocket_authorization(client));
  28653. }
  28654. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28655. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28656. ws::WebSocketClient client(origin.url(),
  28657. {{"Authorization", "Bearer from-header"}});
  28658. client.set_bearer_token_auth("from-setter");
  28659. client.set_basic_auth("user", "pass");
  28660. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28661. }
  28662. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28663. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28664. ws::WebSocketClient client(origin.url());
  28665. EXPECT_EQ("", websocket_authorization(client));
  28666. client.set_bearer_token_auth("first");
  28667. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28668. client.set_bearer_token_auth("second");
  28669. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28670. client.set_bearer_token_auth("");
  28671. EXPECT_EQ("", websocket_authorization(client));
  28672. }
  28673. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28674. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28675. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28676. ASSERT_NE(0, proxy.port());
  28677. ws::WebSocketClient client(origin.url());
  28678. client.set_proxy("127.0.0.1", proxy.port());
  28679. auto res = client.connect();
  28680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28681. std::string msg;
  28682. ASSERT_TRUE(client.read(msg));
  28683. ASSERT_TRUE(client.send("hello"));
  28684. ASSERT_TRUE(client.read(msg));
  28685. EXPECT_EQ("hello", msg);
  28686. client.close();
  28687. EXPECT_EQ(1, proxy.connect_hits());
  28688. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28689. auto connect_req = proxy.connect_request();
  28690. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28691. EXPECT_NE(std::string::npos,
  28692. connect_req.find("\r\nHost: " + target + "\r\n"));
  28693. }
  28694. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28695. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28696. [](ws::WebSocketClient &cli) {
  28697. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28698. },
  28699. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28700. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28701. }
  28702. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28703. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28704. [](ws::WebSocketClient &cli) {
  28705. cli.set_proxy_bearer_token_auth("proxy-token");
  28706. },
  28707. "Bearer proxy-token", "Bearer origin-token");
  28708. }
  28709. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28710. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28711. [](ws::WebSocketClient &cli) {
  28712. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28713. cli.set_basic_auth("origin-user", "origin-pass");
  28714. },
  28715. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28716. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28717. }
  28718. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28719. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28720. [](ws::WebSocketClient &cli) {
  28721. cli.set_proxy_bearer_token_auth("proxy-token");
  28722. cli.set_bearer_token_auth("origin-token");
  28723. },
  28724. "Bearer proxy-token", "Bearer origin-token");
  28725. }
  28726. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28727. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28728. proxy_tunnel_test::ScopedConnectProxy proxy(
  28729. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28730. "Basic " + detail::base64_encode("proxy-user:"),
  28731. "Basic realm=\"proxy\""));
  28732. ASSERT_NE(0, proxy.port());
  28733. ws::WebSocketClient client(origin.url());
  28734. client.set_proxy("127.0.0.1", proxy.port());
  28735. client.set_proxy_basic_auth("proxy-user", "");
  28736. auto res = client.connect();
  28737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28738. client.close();
  28739. EXPECT_EQ(1, proxy.connect_hits());
  28740. }
  28741. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28742. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28743. proxy_tunnel_test::ScopedConnectProxy proxy(
  28744. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28745. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28746. ASSERT_NE(0, proxy.port());
  28747. ws::WebSocketClient client(origin.url());
  28748. client.set_proxy("127.0.0.1", proxy.port());
  28749. auto res = client.connect();
  28750. EXPECT_FALSE(res);
  28751. EXPECT_EQ(Error::ProxyConnection, res.error());
  28752. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28753. EXPECT_EQ("Basic realm=\"proxy\"",
  28754. res.get_header_value("Proxy-Authenticate"));
  28755. EXPECT_FALSE(client.is_open());
  28756. }
  28757. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28758. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28759. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28760. ASSERT_NE(0, proxy.port());
  28761. ws::WebSocketClient client(origin.url());
  28762. client.set_proxy("127.0.0.1", proxy.port());
  28763. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28764. client.set_no_proxy({"127.0.0.1"});
  28765. auto res = client.connect();
  28766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28767. std::string msg;
  28768. ASSERT_TRUE(client.read(msg));
  28769. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28770. << "proxy credentials must not reach a bypassed origin";
  28771. client.close();
  28772. EXPECT_EQ(0, proxy.connect_hits());
  28773. }
  28774. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28775. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28776. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28777. ASSERT_NE(0, proxy.port());
  28778. ws::WebSocketClient client(origin.url());
  28779. client.set_proxy("127.0.0.1", proxy.port());
  28780. ASSERT_TRUE(client.connect());
  28781. ASSERT_TRUE(client.connect());
  28782. client.close();
  28783. EXPECT_EQ(2, proxy.connect_hits());
  28784. }
  28785. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28786. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28787. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28788. ASSERT_NE(0, proxy.port());
  28789. auto port = std::to_string(origin.port());
  28790. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28791. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28792. client.set_proxy("127.0.0.1", proxy.port());
  28793. auto res = client.connect();
  28794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28795. std::string msg;
  28796. ASSERT_TRUE(client.read(msg));
  28797. client.close();
  28798. EXPECT_EQ(1, proxy.connect_hits());
  28799. auto target = "127.0.0.1:" + port;
  28800. auto connect_req = proxy.connect_request();
  28801. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28802. EXPECT_NE(std::string::npos,
  28803. connect_req.find("\r\nHost: " + target + "\r\n"));
  28804. }
  28805. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28806. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28807. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28808. ASSERT_NE(0, proxy.port());
  28809. auto port = std::to_string(origin.port());
  28810. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28811. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28812. client.set_proxy("127.0.0.1", proxy.port());
  28813. auto res = client.connect();
  28814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28815. client.close();
  28816. auto target = "origin.example:" + port;
  28817. auto connect_req = proxy.connect_request();
  28818. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28819. EXPECT_NE(std::string::npos,
  28820. connect_req.find("\r\nHost: " + target + "\r\n"));
  28821. }
  28822. #ifdef CPPHTTPLIB_SSL_ENABLED
  28823. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28824. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28825. proxy_tunnel_test::ScopedConnectProxy proxy(
  28826. origin.port(), [](const std::string &head) -> std::string {
  28827. if (head.find(
  28828. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28829. std::string::npos) {
  28830. return proxy_tunnel_test::kTunnelEstablished;
  28831. }
  28832. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28833. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28834. "nonce=\"abc\", algorithm=MD5\r\n"
  28835. "Content-Length: 0\r\n\r\n";
  28836. });
  28837. ASSERT_NE(0, proxy.port());
  28838. ws::WebSocketClient client(origin.url());
  28839. client.set_proxy("127.0.0.1", proxy.port());
  28840. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28841. auto res = client.connect();
  28842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28843. std::string msg;
  28844. ASSERT_TRUE(client.read(msg));
  28845. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28846. client.close();
  28847. EXPECT_EQ(2, proxy.connect_hits());
  28848. }
  28849. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28850. proxy_tunnel_test::ScopedSSLServer origin;
  28851. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28852. origin.listen();
  28853. proxy_tunnel_test::ScopedConnectProxy proxy(
  28854. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28855. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28856. ASSERT_NE(0, proxy.port());
  28857. ws::WebSocketClient client(
  28858. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28859. client.enable_server_certificate_verification(false);
  28860. client.set_proxy("127.0.0.1", proxy.port());
  28861. client.set_proxy_bearer_token_auth("proxy-token");
  28862. auto res = client.connect();
  28863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28864. std::string msg;
  28865. ASSERT_TRUE(client.read(msg));
  28866. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28867. << "Proxy-Authorization must not be sent inside the tunnel";
  28868. client.close();
  28869. EXPECT_EQ(1, proxy.connect_hits());
  28870. }
  28871. #endif
  28872. // ---------------------------------------------------------------------------
  28873. // Poller
  28874. // ---------------------------------------------------------------------------
  28875. namespace poller_test {
  28876. struct PollerBackend {
  28877. const char *name;
  28878. std::unique_ptr<detail::Poller> (*create)();
  28879. };
  28880. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28881. *os << backend.name;
  28882. }
  28883. // Every backend runs the same contract tests. A new one is added here only.
  28884. std::vector<PollerBackend> poller_backends() {
  28885. return {
  28886. {"poll", &detail::PollPoller::create},
  28887. #ifdef __linux__
  28888. {"epoll", &detail::EpollPoller::create},
  28889. #endif
  28890. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28891. {"kqueue", &detail::KqueuePoller::create},
  28892. #endif
  28893. };
  28894. }
  28895. // A descriptor whose readability the test controls.
  28896. struct TestSocketPair {
  28897. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28898. TestSocketPair() { detail::create_socket_pair(fd); }
  28899. ~TestSocketPair() {
  28900. for (auto s : fd) {
  28901. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28902. }
  28903. }
  28904. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28905. socket_t reader() const { return fd[0]; }
  28906. void make_readable() {
  28907. const char c = 1;
  28908. detail::send_socket(fd[1], &c, 1, 0);
  28909. }
  28910. void close_writer() {
  28911. detail::close_socket(fd[1]);
  28912. fd[1] = INVALID_SOCKET;
  28913. }
  28914. };
  28915. using Tokens = std::vector<detail::Poller::Token>;
  28916. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28917. protected:
  28918. void SetUp() override {
  28919. poller_ = GetParam().create();
  28920. ASSERT_TRUE(poller_ != nullptr);
  28921. }
  28922. Tokens wait_for(int timeout_ms) {
  28923. Tokens ready;
  28924. poller_->wait(timeout_ms, ready);
  28925. std::sort(ready.begin(), ready.end());
  28926. return ready;
  28927. }
  28928. std::unique_ptr<detail::Poller> poller_;
  28929. };
  28930. } // namespace poller_test
  28931. using poller_test::PollerTest;
  28932. using poller_test::TestSocketPair;
  28933. using poller_test::Tokens;
  28934. INSTANTIATE_TEST_SUITE_P(
  28935. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28936. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28937. return std::string(p.param.name);
  28938. });
  28939. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28940. TestSocketPair sp;
  28941. ASSERT_TRUE(sp.ok());
  28942. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28943. EXPECT_EQ(Tokens{}, wait_for(0));
  28944. sp.make_readable();
  28945. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28946. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28947. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28948. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28949. }
  28950. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28951. TestSocketPair sp;
  28952. ASSERT_TRUE(sp.ok());
  28953. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28954. poller_->disarm(sp.reader());
  28955. poller_->disarm(sp.reader()); // disarming twice is harmless
  28956. sp.make_readable();
  28957. EXPECT_EQ(Tokens{}, wait_for(0));
  28958. }
  28959. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28960. TestSocketPair sp;
  28961. ASSERT_TRUE(sp.ok());
  28962. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28963. auto start = std::chrono::steady_clock::now();
  28964. EXPECT_EQ(Tokens{}, wait_for(30));
  28965. auto elapsed = std::chrono::steady_clock::now() - start;
  28966. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28967. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28968. }
  28969. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28970. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28971. for (detail::Poller::Token i = 0; i < 8; i++) {
  28972. sps.emplace_back(new TestSocketPair());
  28973. ASSERT_TRUE(sps.back()->ok());
  28974. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28975. }
  28976. sps[0]->make_readable();
  28977. sps[3]->make_readable();
  28978. sps[7]->make_readable();
  28979. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28980. // The others are still armed, the delivered ones are not.
  28981. sps[1]->make_readable();
  28982. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28983. EXPECT_EQ(Tokens{}, wait_for(0));
  28984. }
  28985. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28986. TestSocketPair s0, s1, s2;
  28987. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28988. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28989. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28990. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28991. // A delivery may move another entry inside the poller.
  28992. s0.make_readable();
  28993. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28994. // The entries left must still be found by descriptor.
  28995. poller_->disarm(s2.reader());
  28996. s1.make_readable();
  28997. s2.make_readable();
  28998. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28999. }
  29000. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29001. TestSocketPair sp;
  29002. ASSERT_TRUE(sp.ok());
  29003. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29004. sp.close_writer();
  29005. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29006. char c;
  29007. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29008. }
  29009. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29010. std::thread waker([&] {
  29011. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29012. poller_->wake();
  29013. });
  29014. Tokens ready;
  29015. auto start = std::chrono::steady_clock::now();
  29016. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29017. waker.join();
  29018. EXPECT_TRUE(ready.empty());
  29019. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29020. }
  29021. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29022. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29023. Tokens ready;
  29024. EXPECT_TRUE(poller_->wait(1000, ready));
  29025. }
  29026. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29027. for (int i = 0; i < 1000; i++) {
  29028. poller_->wake();
  29029. }
  29030. Tokens ready;
  29031. EXPECT_TRUE(poller_->wait(0, ready));
  29032. EXPECT_FALSE(poller_->wait(0, ready));
  29033. poller_->wake();
  29034. EXPECT_TRUE(poller_->wait(0, ready));
  29035. }
  29036. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29037. // Two threads publish changes and wake() after each, as a reactor's workers
  29038. // do. Every change must be seen without a wait() timing out. A lost wake()
  29039. // needs an unlucky interleaving, hence the rounds.
  29040. for (int round = 0; round < 5; round++) {
  29041. SCOPED_TRACE(round);
  29042. const int per_thread = 20000;
  29043. std::atomic<int> posted{0};
  29044. auto post = [&] {
  29045. for (int i = 0; i < per_thread; i++) {
  29046. posted++;
  29047. poller_->wake();
  29048. }
  29049. };
  29050. std::thread t1(post), t2(post);
  29051. auto lost = false;
  29052. Tokens ready;
  29053. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29054. if (!poller_->wait(1000, ready)) {
  29055. lost = true;
  29056. break;
  29057. }
  29058. }
  29059. t1.join();
  29060. t2.join();
  29061. ASSERT_FALSE(lost);
  29062. }
  29063. }
  29064. TEST(PollerFactoryTest, MakePollerWorks) {
  29065. auto poller = detail::make_poller();
  29066. ASSERT_TRUE(poller != nullptr);
  29067. poller->wake();
  29068. std::vector<detail::Poller::Token> ready;
  29069. EXPECT_TRUE(poller->wait(1000, ready));
  29070. }
  29071. // ---------------------------------------------------------------------------
  29072. // Keep-alive parking
  29073. // ---------------------------------------------------------------------------
  29074. namespace parking_test {
  29075. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29076. // runs once the port is bound and listening, before the server accepts.
  29077. struct RunningServer {
  29078. explicit RunningServer(
  29079. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29080. : svr_(svr) {
  29081. port = svr_.bind_to_any_port("127.0.0.1");
  29082. if (before_listen) { before_listen(port); }
  29083. thread = std::thread([this] { svr_.listen_after_bind(); });
  29084. svr_.wait_until_ready();
  29085. }
  29086. ~RunningServer() {
  29087. svr_.stop();
  29088. if (thread.joinable()) { thread.join(); }
  29089. }
  29090. Server &svr_;
  29091. int port = 0;
  29092. std::thread thread;
  29093. };
  29094. struct Sockets {
  29095. std::vector<socket_t> socks;
  29096. ~Sockets() {
  29097. for (auto s : socks) {
  29098. detail::close_socket(s);
  29099. }
  29100. }
  29101. socket_t connect(int port) {
  29102. auto error = Error::Success;
  29103. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29104. false, false, nullptr, 2, 0, 2, 0, 2,
  29105. 0, std::string(), error);
  29106. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29107. return s;
  29108. }
  29109. };
  29110. std::chrono::steady_clock::time_point in_ms(int ms) {
  29111. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29112. }
  29113. bool readable_by(socket_t sock,
  29114. std::chrono::steady_clock::time_point deadline) {
  29115. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29116. deadline - std::chrono::steady_clock::now())
  29117. .count();
  29118. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29119. }
  29120. bool send_get(socket_t sock, const std::string &path = "/") {
  29121. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29122. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29123. static_cast<ssize_t>(req.size());
  29124. }
  29125. // Reads one response whose body is "ok".
  29126. bool receives_ok(socket_t sock, int timeout_ms) {
  29127. auto deadline = in_ms(timeout_ms);
  29128. std::string buf;
  29129. while (readable_by(sock, deadline)) {
  29130. char tmp[1024];
  29131. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29132. if (n <= 0) { return false; }
  29133. buf.append(tmp, static_cast<size_t>(n));
  29134. auto end = buf.find("\r\n\r\n");
  29135. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29136. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29137. buf.compare(end + 4, 2, "ok") == 0;
  29138. }
  29139. }
  29140. return false;
  29141. }
  29142. bool get_ok(socket_t sock, int timeout_ms) {
  29143. return send_get(sock) && receives_ok(sock, timeout_ms);
  29144. }
  29145. // Whether the server closes `sock` by `deadline`.
  29146. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29147. char c;
  29148. return readable_by(sock, deadline) &&
  29149. detail::read_socket(sock, &c, 1, 0) <= 0;
  29150. }
  29151. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29152. auto deadline = in_ms(timeout_ms);
  29153. while (!cond()) {
  29154. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29155. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29156. }
  29157. return true;
  29158. }
  29159. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29160. svr.new_task_queue = std::move(new_task_queue);
  29161. svr.set_keep_alive_parking(true);
  29162. svr.Get("/", [](const Request &, Response &res) {
  29163. res.set_content("ok", "text/plain");
  29164. });
  29165. }
  29166. std::function<TaskQueue *(void)> threads(size_t n) {
  29167. return [n] { return new ThreadPool(n); };
  29168. }
  29169. // Counts what the event loop managed to queue, so that a test can wait for it.
  29170. class CountingTaskQueue final : public TaskQueue {
  29171. public:
  29172. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29173. std::atomic<int> &full)
  29174. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29175. bool enqueue(std::function<void()> fn) override {
  29176. auto queued = pool_.enqueue([this, fn]() {
  29177. fn();
  29178. // Holds the worker back from taking the next job.
  29179. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29180. });
  29181. (queued ? ok_ : full_)++;
  29182. return queued;
  29183. }
  29184. void shutdown() override { pool_.shutdown(); }
  29185. std::atomic<int> pause_after_ms{0};
  29186. private:
  29187. ThreadPool pool_;
  29188. std::atomic<int> &ok_;
  29189. std::atomic<int> &full_;
  29190. };
  29191. // Holds handlers until it opens, or for 3 seconds at most.
  29192. class Gate {
  29193. public:
  29194. void wait() {
  29195. std::unique_lock<std::mutex> lock(m_);
  29196. entered_++;
  29197. cv_.notify_all();
  29198. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29199. }
  29200. void open() {
  29201. std::lock_guard<std::mutex> guard(m_);
  29202. open_ = true;
  29203. cv_.notify_all();
  29204. }
  29205. int entered() {
  29206. std::lock_guard<std::mutex> guard(m_);
  29207. return entered_;
  29208. }
  29209. private:
  29210. std::mutex m_;
  29211. std::condition_variable cv_;
  29212. bool open_ = false;
  29213. int entered_ = 0;
  29214. };
  29215. } // namespace parking_test
  29216. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29217. using namespace parking_test;
  29218. Server svr;
  29219. serve_ok(svr, threads(1));
  29220. RunningServer running(svr);
  29221. Sockets socks;
  29222. // One kept-alive connection that has been served, and many that have not
  29223. // sent anything yet. None of them may keep the only worker.
  29224. auto served = socks.connect(running.port);
  29225. ASSERT_TRUE(get_ok(served, 2000));
  29226. for (int i = 0; i < 49; i++) {
  29227. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29228. }
  29229. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29230. EXPECT_TRUE(get_ok(served, 1000));
  29231. }
  29232. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29233. using namespace parking_test;
  29234. Server svr;
  29235. serve_ok(svr, threads(1));
  29236. svr.set_keep_alive_timeout(1);
  29237. RunningServer running(svr);
  29238. Sockets socks;
  29239. for (int i = 0; i < 3; i++) {
  29240. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29241. }
  29242. // One worker waiting on each in turn would take about 3 seconds.
  29243. auto deadline = in_ms(2000);
  29244. for (auto s : socks.socks) {
  29245. EXPECT_TRUE(sees_eof(s, deadline));
  29246. }
  29247. }
  29248. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29249. using namespace parking_test;
  29250. std::atomic<int> queued{0}, full{0};
  29251. Server svr;
  29252. // One worker and room for one queued task.
  29253. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29254. Gate gate;
  29255. svr.Get("/block", [&](const Request &, Response &res) {
  29256. gate.wait();
  29257. res.set_content("ok", "text/plain");
  29258. });
  29259. RunningServer running(svr);
  29260. // Before the server stops, so that a failed run does not wait for the
  29261. // handler's timeout.
  29262. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29263. Sockets socks;
  29264. auto a = socks.connect(running.port);
  29265. ASSERT_TRUE(get_ok(a, 2000));
  29266. // B keeps the only worker busy.
  29267. auto b = socks.connect(running.port);
  29268. ASSERT_TRUE(send_get(b, "/block"));
  29269. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29270. // A new connection C fills the queue.
  29271. auto c = socks.connect(running.port);
  29272. ASSERT_TRUE(send_get(c));
  29273. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29274. // A's next request finds the queue full, but A has been served before, so it
  29275. // waits instead of being cut off.
  29276. ASSERT_TRUE(send_get(a));
  29277. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29278. gate.open();
  29279. EXPECT_TRUE(receives_ok(b, 2000));
  29280. EXPECT_TRUE(receives_ok(c, 2000));
  29281. EXPECT_TRUE(receives_ok(a, 2000));
  29282. }
  29283. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29284. using namespace parking_test;
  29285. std::atomic<int> queued{0}, full{0};
  29286. CountingTaskQueue *queue = nullptr;
  29287. Server svr;
  29288. // Two workers and room for one queued task.
  29289. serve_ok(svr,
  29290. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29291. Gate first, second;
  29292. svr.Get("/first", [&](const Request &, Response &res) {
  29293. first.wait();
  29294. res.set_content("ok", "text/plain");
  29295. });
  29296. svr.Get("/second", [&](const Request &, Response &res) {
  29297. second.wait();
  29298. res.set_content("ok", "text/plain");
  29299. });
  29300. RunningServer running(svr);
  29301. auto open_gates = detail::scope_exit([&] {
  29302. first.open();
  29303. second.open();
  29304. });
  29305. Sockets socks;
  29306. auto a = socks.connect(running.port);
  29307. ASSERT_TRUE(get_ok(a, 2000));
  29308. // B and D take both workers, and C fills the queue. One at a time: the
  29309. // queue has room for one job only until a worker takes it.
  29310. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29311. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29312. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29313. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29314. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29315. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29316. // A's next request waits in the backlog.
  29317. ASSERT_TRUE(send_get(a));
  29318. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29319. // B's worker finishes, then takes C off the queue only later, which makes
  29320. // room for A.
  29321. queue->pause_after_ms = 200;
  29322. first.open();
  29323. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29324. queue->pause_after_ms = 0;
  29325. second.open();
  29326. EXPECT_TRUE(receives_ok(a, 2000));
  29327. }
  29328. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29329. using namespace parking_test;
  29330. Server svr;
  29331. serve_ok(svr, threads(1));
  29332. svr.set_keep_alive_timeout(0);
  29333. // The request is on the socket before the server accepts the connection,
  29334. // so it does not race the 10 ms floor. Without the floor the connection is
  29335. // closed unread.
  29336. Sockets socks;
  29337. auto sock = INVALID_SOCKET;
  29338. RunningServer running(svr, [&](int port) {
  29339. sock = socks.connect(port);
  29340. send_get(sock);
  29341. });
  29342. EXPECT_TRUE(receives_ok(sock, 1000));
  29343. }
  29344. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29345. using namespace parking_test;
  29346. for (int round = 0; round < 5; round++) {
  29347. SCOPED_TRACE(round);
  29348. Server svr;
  29349. serve_ok(svr, threads(2));
  29350. RunningServer running(svr);
  29351. Sockets socks;
  29352. for (int i = 0; i < 20; i++) {
  29353. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29354. }
  29355. auto start = std::chrono::steady_clock::now();
  29356. svr.stop();
  29357. running.thread.join();
  29358. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29359. std::chrono::milliseconds(500));
  29360. auto deadline = in_ms(1000);
  29361. for (auto s : socks.socks) {
  29362. EXPECT_TRUE(sees_eof(s, deadline));
  29363. }
  29364. }
  29365. }
  29366. #ifdef CPPHTTPLIB_SSL_ENABLED
  29367. namespace parking_test {
  29368. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29369. // that has opened a connection ahead of time. Freeing the session sends no
  29370. // close_notify, so the connection stays quiet.
  29371. bool handshake_only(socket_t sock) {
  29372. auto ctx = tls::create_client_context();
  29373. tls::set_verify_client(ctx, false);
  29374. auto session = tls::create_session(ctx, sock);
  29375. auto se = detail::scope_exit([&] {
  29376. tls::free_session(session);
  29377. tls::free_context(ctx);
  29378. });
  29379. tls::TlsError err;
  29380. return session &&
  29381. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29382. }
  29383. Client tls_client(int port) {
  29384. Client cli("https://127.0.0.1:" + std::to_string(port));
  29385. cli.enable_server_certificate_verification(false);
  29386. cli.set_keep_alive(true);
  29387. cli.set_connection_timeout(1);
  29388. cli.set_read_timeout(1);
  29389. return cli;
  29390. }
  29391. bool tls_get_ok(Client &cli) {
  29392. auto res = cli.Get("/");
  29393. return res && res->body == "ok";
  29394. }
  29395. } // namespace parking_test
  29396. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29397. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29398. struct {
  29399. unsigned long version;
  29400. bool safe;
  29401. } cases[] = {
  29402. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29403. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29404. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29405. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29406. };
  29407. for (const auto &c : cases) {
  29408. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29409. << std::hex << c.version;
  29410. }
  29411. }
  29412. #endif
  29413. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29414. using namespace parking_test;
  29415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29416. ASSERT_TRUE(svr.is_valid());
  29417. serve_ok(svr, threads(1));
  29418. svr.set_read_timeout(1); // so that a failing run does not take long
  29419. RunningServer running(svr);
  29420. Sockets socks;
  29421. // One served connection, some that have not started their handshake, and
  29422. // one that has finished it and gone quiet. None may keep the only worker.
  29423. auto served = tls_client(running.port);
  29424. ASSERT_TRUE(tls_get_ok(served));
  29425. for (int i = 0; i < 10; i++) {
  29426. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29427. }
  29428. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29429. auto other = tls_client(running.port);
  29430. EXPECT_TRUE(tls_get_ok(other));
  29431. EXPECT_TRUE(tls_get_ok(served));
  29432. }
  29433. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29434. using namespace parking_test;
  29435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29436. ASSERT_TRUE(svr.is_valid());
  29437. serve_ok(svr, threads(1));
  29438. RunningServer running(svr);
  29439. Sockets socks;
  29440. auto plain = socks.connect(running.port);
  29441. ASSERT_TRUE(send_get(plain));
  29442. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29443. EXPECT_NE(0, svr.ssl_last_error());
  29444. }
  29445. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29446. using namespace parking_test;
  29447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29448. ASSERT_TRUE(svr.is_valid());
  29449. serve_ok(svr, threads(2));
  29450. RunningServer running(svr);
  29451. std::vector<Client> clients;
  29452. for (int i = 0; i < 5; i++) {
  29453. clients.push_back(tls_client(running.port));
  29454. ASSERT_TRUE(tls_get_ok(clients.back()));
  29455. }
  29456. auto start = std::chrono::steady_clock::now();
  29457. svr.stop();
  29458. running.thread.join();
  29459. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29460. std::chrono::milliseconds(500));
  29461. }
  29462. #endif