test.cc 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402
  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. // Failures of the services that the *_Online tests reach, unrelated to the
  145. // client under test: httpbingo.org intermittently answers with gateway errors,
  146. // and badssl.com drops connections from CI runners before it sends its
  147. // certificate. A handshake that fails before any verdict on the certificate is
  148. // left to the tests against local servers.
  149. static bool is_service_failure(const Result &res) {
  150. if (res) {
  151. return res->status == StatusCode::BadGateway_502 ||
  152. res->status == StatusCode::ServiceUnavailable_503 ||
  153. res->status == StatusCode::GatewayTimeout_504;
  154. }
  155. return res.error() == Error::SSLConnection;
  156. }
  157. template <typename F> static Result retry_service_failures(F &&send) {
  158. auto res = send();
  159. for (auto wait : {1, 2}) {
  160. if (!is_service_failure(res)) { break; }
  161. std::this_thread::sleep_for(std::chrono::seconds(wait));
  162. res = send();
  163. }
  164. return res;
  165. }
  166. #define SKIP_ON_SERVICE_FAILURE(res) \
  167. do { \
  168. if (is_service_failure(res)) { \
  169. if (res) { \
  170. GTEST_SKIP() << "service failure: status " << (res)->status; \
  171. } else { \
  172. GTEST_SKIP() << "service failure: " << to_string((res).error()); \
  173. } \
  174. } \
  175. } while (0)
  176. class UnixSocketTest : public ::testing::Test {
  177. protected:
  178. void TearDown() override { std::remove(pathname_.c_str()); }
  179. void client_GET(const std::string &addr) {
  180. httplib::Client cli{addr};
  181. cli.set_address_family(AF_UNIX);
  182. ASSERT_TRUE(cli.is_valid());
  183. const auto &result = cli.Get(pattern_);
  184. ASSERT_TRUE(result) << "error: " << result.error();
  185. const auto &resp = result.value();
  186. EXPECT_EQ(resp.status, StatusCode::OK_200);
  187. EXPECT_EQ(resp.body, content_);
  188. }
  189. static std::string make_sock_path() {
  190. const char *shard = getenv("GTEST_SHARD_INDEX");
  191. return shard ? std::string("./httplib-server-") + shard + ".sock"
  192. : "./httplib-server.sock";
  193. }
  194. const std::string pathname_{make_sock_path()};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. // ".//x.sock", which is not taken for a URL
  215. client_GET("./" + pathname_.substr(1));
  216. }
  217. #if defined(__linux__) || \
  218. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  219. TEST_F(UnixSocketTest, PeerPid) {
  220. httplib::Server svr;
  221. std::string remote_port_val;
  222. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  223. res.set_content(content_, "text/plain");
  224. remote_port_val = std::to_string(req.remote_port);
  225. });
  226. std::thread t{[&] {
  227. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  228. }};
  229. auto se = detail::scope_exit([&] {
  230. svr.stop();
  231. t.join();
  232. ASSERT_FALSE(svr.is_running());
  233. });
  234. svr.wait_until_ready();
  235. ASSERT_TRUE(svr.is_running());
  236. client_GET(pathname_);
  237. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  238. }
  239. #endif
  240. #ifdef __linux__
  241. TEST_F(UnixSocketTest, abstract) {
  242. constexpr char svr_path[]{"\x00httplib-server.sock"};
  243. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  244. httplib::Server svr;
  245. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  246. res.set_content(content_, "text/plain");
  247. });
  248. std::thread t{[&] {
  249. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  250. }};
  251. auto se = detail::scope_exit([&] {
  252. svr.stop();
  253. t.join();
  254. ASSERT_FALSE(svr.is_running());
  255. });
  256. svr.wait_until_ready();
  257. ASSERT_TRUE(svr.is_running());
  258. client_GET(abstract_addr);
  259. }
  260. #endif
  261. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  262. httplib::Server svr;
  263. std::string received_host_header;
  264. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  265. // Capture the Host header sent by the client
  266. auto host_iter = req.headers.find("Host");
  267. if (host_iter != req.headers.end()) {
  268. received_host_header = host_iter->second;
  269. }
  270. res.set_content(content_, "text/plain");
  271. });
  272. std::thread t{[&] {
  273. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  274. }};
  275. auto se = detail::scope_exit([&] {
  276. svr.stop();
  277. t.join();
  278. ASSERT_FALSE(svr.is_running());
  279. });
  280. svr.wait_until_ready();
  281. ASSERT_TRUE(svr.is_running());
  282. // Test that Host header is automatically set to "localhost" for Unix socket
  283. // connections
  284. httplib::Client cli{pathname_};
  285. cli.set_address_family(AF_UNIX);
  286. ASSERT_TRUE(cli.is_valid());
  287. const auto &result = cli.Get(pattern_);
  288. ASSERT_TRUE(result) << "error: " << result.error();
  289. const auto &resp = result.value();
  290. EXPECT_EQ(resp.status, StatusCode::OK_200);
  291. EXPECT_EQ(resp.body, content_);
  292. // Verify that Host header was automatically set to "localhost"
  293. EXPECT_EQ(received_host_header, "localhost");
  294. }
  295. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  296. // Another socket in the working directory, which a Location can name as
  297. // its host
  298. const auto other_path = "other-" + pathname_.substr(2);
  299. httplib::Server svr;
  300. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  301. // An absolute Location naming the Host this client sends
  302. res.set_redirect("http://localhost" + pattern_);
  303. });
  304. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_redirect("http://" + other_path + pattern_);
  306. });
  307. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  308. res.set_redirect("http://mapped.test" + pattern_);
  309. });
  310. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  311. res.set_header("X-Auth", req.get_header_value("Authorization"));
  312. res.set_content(content_, "text/plain");
  313. });
  314. httplib::Server other;
  315. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  316. res.set_content("other", "text/plain");
  317. });
  318. std::thread t{[&] {
  319. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  320. }};
  321. std::thread t2{[&] {
  322. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  323. }};
  324. auto se = detail::scope_exit([&] {
  325. svr.stop();
  326. other.stop();
  327. t.join();
  328. t2.join();
  329. std::remove(other_path.c_str());
  330. });
  331. svr.wait_until_ready();
  332. other.wait_until_ready();
  333. httplib::Client cli{pathname_};
  334. cli.set_address_family(AF_UNIX);
  335. cli.set_follow_location(true);
  336. cli.set_bearer_token_auth("token");
  337. // Another host: the same socket, without the credentials
  338. auto res = cli.Get("/cross");
  339. ASSERT_TRUE(res) << "error: " << res.error();
  340. EXPECT_EQ(StatusCode::OK_200, res->status);
  341. EXPECT_EQ(content_, res->body);
  342. EXPECT_EQ("", res->get_header_value("X-Auth"));
  343. // localhost is this client's own host
  344. res = cli.Get("/redirect");
  345. ASSERT_TRUE(res) << "error: " << res.error();
  346. EXPECT_EQ(StatusCode::OK_200, res->status);
  347. EXPECT_EQ(content_, res->body);
  348. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  349. // A host the caller mapped to a socket goes there
  350. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  351. res = cli.Get("/mapped");
  352. ASSERT_TRUE(res) << "error: " << res.error();
  353. EXPECT_EQ(StatusCode::OK_200, res->status);
  354. EXPECT_EQ("other", res->body);
  355. }
  356. #ifndef _WIN32
  357. TEST(SocketStream, wait_writable_UNIX) {
  358. int fds[2];
  359. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  360. const auto asSocketStream = [&](socket_t fd,
  361. std::function<bool(Stream &)> func) {
  362. return detail::process_client_socket(
  363. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  364. };
  365. asSocketStream(fds[0], [&](Stream &s0) {
  366. EXPECT_EQ(s0.socket(), fds[0]);
  367. EXPECT_TRUE(s0.wait_writable());
  368. EXPECT_TRUE(s0.is_peer_alive());
  369. EXPECT_EQ(0, close(fds[1]));
  370. EXPECT_FALSE(s0.is_peer_alive());
  371. return true;
  372. });
  373. EXPECT_EQ(0, close(fds[0]));
  374. }
  375. TEST(SocketStream, wait_writable_INET) {
  376. sockaddr_in addr;
  377. memset(&addr, 0, sizeof(addr));
  378. addr.sin_family = AF_INET;
  379. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  380. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  381. int disconnected_svr_sock = -1;
  382. std::thread svr{[&] {
  383. const int s = socket(AF_INET, SOCK_STREAM, 0);
  384. ASSERT_LE(0, s);
  385. // PORT + 1 is shared with the SSL redirect tests and with
  386. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  387. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  388. // because that happens on a worker thread the ASSERT does not stop the
  389. // test: it runs on and fails at the disconnected_svr_sock check instead.
  390. default_socket_options(s);
  391. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  392. ASSERT_EQ(0, listen(s, 1));
  393. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  394. ASSERT_EQ(0, close(s));
  395. }};
  396. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  397. std::thread cli{[&] {
  398. const int s = socket(AF_INET, SOCK_STREAM, 0);
  399. ASSERT_LE(0, s);
  400. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  401. ASSERT_EQ(0, close(s));
  402. }};
  403. cli.join();
  404. svr.join();
  405. ASSERT_NE(disconnected_svr_sock, -1);
  406. const auto asSocketStream = [&](socket_t fd,
  407. std::function<bool(Stream &)> func) {
  408. return detail::process_client_socket(
  409. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  410. };
  411. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  412. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  413. // wait_writable() returns true because select_write() only checks if the
  414. // send buffer has space. Peer disconnection is detected later by send().
  415. EXPECT_TRUE(ss.wait_writable());
  416. return true;
  417. });
  418. ASSERT_EQ(0, close(disconnected_svr_sock));
  419. }
  420. #endif // #ifndef _WIN32
  421. TEST(SetSocketOptTest, TcpNoDelay) {
  422. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  423. ASSERT_NE(sock, INVALID_SOCKET);
  424. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  425. int val = 0;
  426. socklen_t len = sizeof(val);
  427. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  428. reinterpret_cast<char *>(&val), &len));
  429. EXPECT_NE(val, 0);
  430. detail::close_socket(sock);
  431. }
  432. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  433. // accept() reports failures through WSAGetLastError() on Windows and through
  434. // errno everywhere else. Asking the wrong one is what made the accept loop
  435. // treat every recoverable failure as fatal on Windows.
  436. struct Classification {
  437. bool resource;
  438. bool transient;
  439. };
  440. auto classify = [](int err) {
  441. #ifdef _WIN32
  442. WSASetLastError(err);
  443. #else
  444. errno = err;
  445. #endif
  446. // Read both before asserting: an assertion may clobber the error slot.
  447. Classification c;
  448. c.resource = detail::is_accept_resource_error();
  449. c.transient = detail::is_accept_transient_error();
  450. return c;
  451. };
  452. #ifdef _WIN32
  453. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  454. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  455. WSAECONNRESET, WSAECONNABORTED};
  456. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  457. #else
  458. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  459. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  460. ECONNABORTED};
  461. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  462. #endif
  463. for (auto err : resource_errors) {
  464. const auto c = classify(err);
  465. EXPECT_TRUE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. for (auto err : transient_errors) {
  469. const auto c = classify(err);
  470. EXPECT_TRUE(c.transient) << "error " << err;
  471. EXPECT_FALSE(c.resource) << "error " << err;
  472. }
  473. for (auto err : fatal_errors) {
  474. const auto c = classify(err);
  475. EXPECT_FALSE(c.resource) << "error " << err;
  476. EXPECT_FALSE(c.transient) << "error " << err;
  477. }
  478. #ifdef _WIN32
  479. WSASetLastError(0);
  480. #else
  481. errno = 0;
  482. #endif
  483. }
  484. TEST(ClientTest, MoveConstructible) {
  485. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  486. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  487. }
  488. TEST(ClientTest, MoveAssignable) {
  489. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  490. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  491. }
  492. #ifdef _WIN32
  493. TEST(StartupTest, WSAStartup) {
  494. WSADATA wsaData;
  495. int ret = WSAStartup(0x0002, &wsaData);
  496. ASSERT_EQ(0, ret);
  497. }
  498. #endif
  499. TEST(DecodePathTest, PercentCharacter) {
  500. EXPECT_EQ(
  501. decode_path_component(
  502. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  503. U8("descrip=Gastos áéíóúñÑ 6"));
  504. }
  505. TEST(DecodePathTest, PercentCharacterNUL) {
  506. string expected;
  507. expected.push_back('x');
  508. expected.push_back('\0');
  509. expected.push_back('x');
  510. EXPECT_EQ(decode_path_component("x%00x"), expected);
  511. }
  512. TEST(DecodePathTest, UnicodeEncoding) {
  513. // %u0041 = 'A' (1-byte UTF-8)
  514. EXPECT_EQ("A", decode_path_component("%u0041"));
  515. // %u00E9 = 'é' (2-byte UTF-8)
  516. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  517. // %u3042 = 'あ' (3-byte UTF-8)
  518. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  519. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  520. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  521. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  522. // neighbours)
  523. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  524. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  525. }
  526. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  527. // A sign or whitespace inside the two-character escape window must not be
  528. // accepted as a valid percent-encoding; the sequence is passed through
  529. // literally, matching decode_uri_component / decode_path_component.
  530. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  531. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  532. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  533. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  534. // Well-formed escapes still decode.
  535. EXPECT_EQ("-", decode_query_component("%2D", false));
  536. EXPECT_EQ("A", decode_query_component("%41", false));
  537. }
  538. TEST(SanitizeFilenameTest, VariousPatterns) {
  539. // Path traversal
  540. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  541. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  542. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  543. // Normal and edge cases
  544. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  545. EXPECT_EQ("filename.txt",
  546. httplib::sanitize_filename("/path/to/filename.txt"));
  547. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  548. EXPECT_EQ("", httplib::sanitize_filename(".."));
  549. EXPECT_EQ("", httplib::sanitize_filename(""));
  550. // Null bytes stripped
  551. EXPECT_EQ("safe.txt",
  552. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  553. // Whitespace-only rejected
  554. EXPECT_EQ("", httplib::sanitize_filename(" "));
  555. }
  556. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  557. // before it is dropped; anywhere else it is an ordinary file name character.
  558. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  559. #ifdef _WIN32
  560. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  561. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  562. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  563. #else
  564. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  565. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  566. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  567. #endif
  568. }
  569. // Forward declaration (see the base64_encode note below): split builds move the
  570. // definition into httplib.cc, so re-declaring it here lets the test link.
  571. namespace httplib {
  572. namespace detail {
  573. bool is_chunked_transfer_encoding(const Headers &headers);
  574. } // namespace detail
  575. } // namespace httplib
  576. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  577. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  578. auto make = [](std::initializer_list<const char *> lines) {
  579. Headers h;
  580. for (auto te : lines) {
  581. if (te) { h.emplace("Transfer-Encoding", te); }
  582. }
  583. return h;
  584. };
  585. // Sole coding, matched case-insensitively.
  586. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  587. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  588. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  589. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  590. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  593. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  595. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  596. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  597. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  598. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  599. // were received, into one list. Headers preserves that order, so the answer
  600. // is decided by the last coding of the last line and the order the lines
  601. // arrived in is significant.
  602. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  603. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  604. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  605. // The split can fall anywhere in the list.
  606. EXPECT_TRUE(
  607. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  608. EXPECT_FALSE(
  609. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  610. // A trailing line naming no coding leaves the list ending in nothing, so it
  611. // must not inherit the chunked from the line before it.
  612. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  613. }
  614. // Forward declarations (see the base64_encode note below).
  615. namespace httplib {
  616. namespace detail {
  617. bool parse_status_line(const char *line, std::string &version, int &status,
  618. std::string &reason);
  619. std::string file_extension(const std::string &path);
  620. std::string
  621. find_content_type(const std::string &path,
  622. const std::map<std::string, std::string> &user_data,
  623. const std::string &default_content_type);
  624. bool can_compress_content_type(const std::string &content_type);
  625. bool is_prohibited_header_name(const std::string &name);
  626. bool is_valid_path(const std::string &path);
  627. #ifdef CPPHTTPLIB_SSL_ENABLED
  628. bool match_hostname(const std::string &pattern, const std::string &hostname);
  629. #endif
  630. } // namespace detail
  631. } // namespace httplib
  632. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  633. struct {
  634. const char *line;
  635. const char *version;
  636. int status;
  637. const char *reason;
  638. } cases[] = {
  639. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  640. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  641. // The reason phrase may be empty, or left out along with its space.
  642. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  643. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  644. };
  645. for (const auto &c : cases) {
  646. std::string version;
  647. int status = 0;
  648. std::string reason = "unset";
  649. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  650. << c.line;
  651. EXPECT_EQ(c.version, version);
  652. EXPECT_EQ(c.status, status);
  653. EXPECT_EQ(c.reason, reason);
  654. }
  655. }
  656. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  657. const char *lines[] = {
  658. "HTTP/2 200 OK\r\n",
  659. "HTTP/1.2 200 OK\r\n",
  660. "HTTP/1.1 20 OK\r\n",
  661. "HTTP/1.1 2000 OK\r\n",
  662. "HTTP/1.1 2x0 OK\r\n",
  663. "HTTP/1.1 200 OK\r\n",
  664. "HTTP/1.1 200OK\r\n",
  665. "HTTP/1.1 200 O\rK\r\n",
  666. "HTTP/1.1 200 OK",
  667. "HTTP/1.1 200 OK\r\nX",
  668. "",
  669. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  670. "HTTP/1.1 200 OK\n",
  671. #endif
  672. };
  673. for (auto line : lines) {
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  678. << line;
  679. }
  680. }
  681. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  682. // Long enough to overflow the stack when matched with std::regex.
  683. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  684. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  685. std::string version;
  686. int status = 0;
  687. std::string reason;
  688. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  689. EXPECT_EQ(200, status);
  690. EXPECT_EQ(long_reason, reason);
  691. }
  692. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  693. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  694. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  695. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  696. EXPECT_EQ("", detail::file_extension("noext"));
  697. EXPECT_EQ("", detail::file_extension("a."));
  698. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  699. EXPECT_EQ("", detail::file_extension("a.b-c"));
  700. // Long enough to overflow the stack when matched with std::regex.
  701. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  702. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  703. }
  704. #ifdef CPPHTTPLIB_SSL_ENABLED
  705. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  706. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  707. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  708. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  709. // A wildcard needs two labels after it, in the leftmost label only
  710. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  711. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  712. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  713. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  714. EXPECT_FALSE(
  715. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  716. // No name may have an empty label
  717. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  718. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  719. }
  720. #endif
  721. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  722. detail::case_ignore::hash hash;
  723. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  724. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  725. // Long enough to overflow the stack if hashed one call per character.
  726. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  727. }
  728. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  729. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  730. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  731. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  732. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  733. // Same 26-bit hash as html, svg and js.
  734. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  735. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  736. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  737. }
  738. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  739. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  740. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  741. }
  742. }
  743. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  744. // name anywhere else.
  745. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  746. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  747. #ifdef _WIN32
  748. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  749. #else
  750. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  751. #endif
  752. }
  753. }
  754. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  755. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  756. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  757. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  758. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  759. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  760. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  761. // Same 26-bit hash as application/json.
  762. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  763. }
  764. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  765. Request req;
  766. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  767. EXPECT_TRUE(req.is_multipart_form_data());
  768. std::string boundary;
  769. EXPECT_TRUE(detail::parse_multipart_boundary(
  770. req.get_header_value("Content-Type"), boundary));
  771. EXPECT_EQ("x", boundary);
  772. }
  773. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  774. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  775. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  776. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  777. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  778. // Same 26-bit hash as REMOTE_ADDR.
  779. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  780. }
  781. // Forward declaration: in split builds split.py strips `inline` and moves the
  782. // definition into httplib.cc, so detail::base64_encode is not visible from the
  783. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  784. // in both header-only and split builds.
  785. namespace httplib {
  786. namespace detail {
  787. std::string base64_encode(const std::string &in);
  788. } // namespace detail
  789. } // namespace httplib
  790. TEST(Base64EncodeTest, KnownAnswers) {
  791. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  792. // where the accumulator's top bit is already set before the next shift.
  793. EXPECT_EQ("", detail::base64_encode(""));
  794. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  795. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  796. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  797. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  798. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  799. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  800. // High bytes keep the top bit set across several rounds.
  801. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  802. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  803. }
  804. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  805. string unescapedCharacters = "-_.!~*'()";
  806. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  807. }
  808. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  809. string reservedCharacters = ";,/?:@&=+$";
  810. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  811. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  812. }
  813. TEST(ClientQueryOrder, PreserveOrder) {
  814. // This test reproduces Issue #2259: client may reorder query parameters
  815. // when sending a GET request. The expected behavior is that the client
  816. // preserves the original query string order when the caller supplied it
  817. // as part of the path.
  818. Server svr;
  819. svr.Get("/", [&](const Request &req, Response &res) {
  820. // Echo back the raw target so the test can assert ordering
  821. res.set_content(req.target, "text/plain");
  822. });
  823. std::thread t{[&] { svr.listen(HOST, PORT); }};
  824. auto se = detail::scope_exit([&] {
  825. svr.stop();
  826. t.join();
  827. ASSERT_FALSE(svr.is_running());
  828. });
  829. svr.wait_until_ready();
  830. Client cli(HOST, PORT);
  831. ASSERT_TRUE(cli.is_valid());
  832. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  833. auto res = cli.Get(original);
  834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  835. // Expect the echoed target to exactly match the original path (order
  836. // preserved)
  837. EXPECT_EQ(res->body, original);
  838. }
  839. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  846. "%D0%B4%D0%BE%D0%BC");
  847. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  848. }
  849. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  850. string unescapedCharacters = "-_.!~*'()";
  851. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  852. }
  853. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  854. string reservedCharacters = ";,/?:@&=+$";
  855. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  856. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  857. }
  858. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  859. string chineseCharacters = U8("中国語");
  860. string russianCharacters = U8("дом");
  861. string brazilianCharacters = U8("óculos");
  862. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  863. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  864. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  865. "%D0%B4%D0%BE%D0%BC");
  866. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  867. }
  868. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  869. // Issue #2082 use case: encoding path component with ampersand
  870. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  871. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  872. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  873. }
  874. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  875. string unescapedCharacters = "-_.!~*'()";
  876. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  877. }
  878. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  879. string reservedCharacters = ";,/?:@&=+$#";
  880. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  881. }
  882. TEST(EncodeUriTest, TestUTF8Characters) {
  883. string chineseCharacters = U8("中国語");
  884. string russianCharacters = U8("дом");
  885. string brazilianCharacters = U8("óculos");
  886. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  887. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  888. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  889. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  890. }
  891. TEST(EncodeUriTest, TestCompleteUri) {
  892. string uri =
  893. "https://example.com/path/to/resource?query=value&param=test#fragment";
  894. EXPECT_EQ(
  895. httplib::encode_uri(uri),
  896. "https://example.com/path/to/resource?query=value&param=test#fragment");
  897. }
  898. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  899. string uri =
  900. "https://example.com/path with spaces/file name.html?q=hello world";
  901. EXPECT_EQ(httplib::encode_uri(uri),
  902. "https://example.com/path%20with%20spaces/"
  903. "file%20name.html?q=hello%20world");
  904. }
  905. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  906. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  908. }
  909. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  910. string unescapedCharacters = "-_.!~*'()";
  911. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  912. }
  913. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  914. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  915. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  916. string encodedBrazilian = "%C3%B3culos";
  917. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  918. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  919. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  920. }
  921. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  922. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  923. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  924. "Piri Tommy Villiers - on & on");
  925. }
  926. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  927. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  928. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  929. }
  930. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  931. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  932. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  933. }
  934. TEST(DecodeUriTest, TestUTF8Characters) {
  935. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  936. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  937. string encodedBrazilian = "%C3%B3culos";
  938. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  939. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  940. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  941. }
  942. TEST(DecodeUriTest, TestCompleteUri) {
  943. string encodedUri = "https://example.com/path%20with%20spaces/"
  944. "file%20name.html?q=hello%20world";
  945. EXPECT_EQ(
  946. httplib::decode_uri(encodedUri),
  947. "https://example.com/path with spaces/file name.html?q=hello world");
  948. }
  949. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  950. string original =
  951. "https://example.com/path with spaces/file name.html?q=hello world";
  952. string encoded = httplib::encode_uri(original);
  953. string decoded = httplib::decode_uri(encoded);
  954. EXPECT_EQ(decoded, original);
  955. }
  956. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  957. // decode_uri is the inverse of encode_uri: an escaped reserved character
  958. // stays encoded so it is not promoted into a real delimiter, while
  959. // non-reserved escapes still decode (like JS decodeURI).
  960. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  961. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  962. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  963. "%3F%3A%40%26%3D%2B%24%2C%3B");
  964. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  965. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  966. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  967. "http://example.com/a%2Fb");
  968. // decode_uri_component still decodes the reserved character.
  969. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  970. }
  971. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  972. string original = "Piri Tommy Villiers - on & on";
  973. string encoded = httplib::encode_uri_component(original);
  974. string decoded = httplib::decode_uri_component(encoded);
  975. EXPECT_EQ(decoded, original);
  976. }
  977. TEST(TrimTests, TrimStringTests) {
  978. EXPECT_EQ("abc", detail::trim_copy("abc"));
  979. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  980. EXPECT_TRUE(detail::trim_copy("").empty());
  981. }
  982. TEST(AsciiTest, LocaleIndependentClassification) {
  983. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  984. // which consult the global C locale: std::isalnum(0xC5) can return true
  985. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  986. // helpers must classify every byte by the ASCII grammar alone.
  987. for (int i = 0; i < 256; i++) {
  988. auto c = static_cast<char>(i);
  989. auto is_digit = i >= '0' && i <= '9';
  990. auto is_upper = i >= 'A' && i <= 'Z';
  991. auto is_lower = i >= 'a' && i <= 'z';
  992. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  993. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  994. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  995. << "byte " << i;
  996. }
  997. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  998. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  999. // Non-ASCII bytes must be percent-encoded, never passed through as
  1000. // alphanumeric.
  1001. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  1002. }
  1003. TEST(FromCharsTest, Double) {
  1004. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  1005. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  1006. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  1007. auto parse = [](const std::string &s, double &v) {
  1008. return detail::from_chars(s.data(), s.data() + s.size(), v);
  1009. };
  1010. double v = -1.0;
  1011. // Representative quality values.
  1012. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.0);
  1014. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 1.0);
  1016. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1017. EXPECT_DOUBLE_EQ(v, 0.8);
  1018. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 0.001);
  1020. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1021. EXPECT_DOUBLE_EQ(v, 1.0);
  1022. // A missing integer or fractional part is tolerated.
  1023. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.5);
  1025. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1026. EXPECT_DOUBLE_EQ(v, 5.0);
  1027. // Values outside [0, 1] still parse; the caller range-checks them.
  1028. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1029. EXPECT_DOUBLE_EQ(v, 123.456);
  1030. // Stops at the first byte that is not part of the number and reports where.
  1031. std::string trailing = "0.9, text/html";
  1032. auto r = parse(trailing, v);
  1033. EXPECT_EQ(r.ec, std::errc{});
  1034. EXPECT_DOUBLE_EQ(v, 0.9);
  1035. EXPECT_EQ(*r.ptr, ',');
  1036. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1037. // outright, and an 'e'/'E' simply ends the number.
  1038. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1040. std::string exp_input = "1.5e3";
  1041. r = parse(exp_input, v);
  1042. EXPECT_EQ(r.ec, std::errc{});
  1043. EXPECT_DOUBLE_EQ(v, 1.5);
  1044. EXPECT_EQ(*r.ptr, 'e');
  1045. // Invalid inputs.
  1046. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1047. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1048. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1049. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1050. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1051. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1052. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1053. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1054. std::errc{});
  1055. EXPECT_DOUBLE_EQ(v, 0.0);
  1056. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1057. std::errc{});
  1058. EXPECT_GE(v, 0.0);
  1059. EXPECT_LE(v, 1.0);
  1060. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1061. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1062. }
  1063. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1064. // Simple case without quality values
  1065. std::vector<std::string> result1;
  1066. EXPECT_TRUE(detail::parse_accept_header(
  1067. "text/html,application/json,text/plain", result1));
  1068. EXPECT_EQ(result1.size(), 3U);
  1069. EXPECT_EQ(result1[0], "text/html");
  1070. EXPECT_EQ(result1[1], "application/json");
  1071. EXPECT_EQ(result1[2], "text/plain");
  1072. // With quality values
  1073. std::vector<std::string> result2;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1076. EXPECT_EQ(result2.size(), 3U);
  1077. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1078. EXPECT_EQ(result2[1], "text/html");
  1079. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1080. }
  1081. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1082. // Mixed with and without quality values
  1083. std::vector<std::string> result;
  1084. EXPECT_TRUE(detail::parse_accept_header(
  1085. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1086. EXPECT_EQ(result.size(), 3U);
  1087. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1088. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1089. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1090. }
  1091. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1092. // Empty header
  1093. std::vector<std::string> empty_result;
  1094. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1095. EXPECT_TRUE(empty_result.empty());
  1096. // Single type
  1097. std::vector<std::string> single_result;
  1098. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1099. EXPECT_EQ(single_result.size(), 1U);
  1100. EXPECT_EQ(single_result[0], "application/json");
  1101. // Wildcard types
  1102. std::vector<std::string> wildcard_result;
  1103. EXPECT_TRUE(detail::parse_accept_header(
  1104. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1105. EXPECT_EQ(wildcard_result.size(), 3U);
  1106. EXPECT_EQ(wildcard_result[0], "application/json");
  1107. EXPECT_EQ(wildcard_result[1], "text/*");
  1108. EXPECT_EQ(wildcard_result[2], "*/*");
  1109. }
  1110. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1111. // Common browser Accept header
  1112. std::vector<std::string> browser_result;
  1113. EXPECT_TRUE(
  1114. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1115. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1116. browser_result));
  1117. EXPECT_EQ(browser_result.size(), 6U);
  1118. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1119. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1120. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1121. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1122. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1123. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1124. // API client header
  1125. std::vector<std::string> api_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1128. api_result));
  1129. EXPECT_EQ(api_result.size(), 3U);
  1130. EXPECT_EQ(api_result[0], "application/json");
  1131. EXPECT_EQ(api_result[1], "application/xml");
  1132. EXPECT_EQ(api_result[2], "text/plain");
  1133. }
  1134. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1135. // Quality value with 3 decimal places
  1136. std::vector<std::string> decimal_result;
  1137. EXPECT_TRUE(detail::parse_accept_header(
  1138. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1139. EXPECT_EQ(decimal_result.size(), 2U);
  1140. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1141. EXPECT_EQ(decimal_result[1], "text/html");
  1142. // Zero quality (should still be included but with lowest priority)
  1143. std::vector<std::string> zero_q_result;
  1144. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1145. zero_q_result));
  1146. EXPECT_EQ(zero_q_result.size(), 2U);
  1147. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1148. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1149. // No spaces around commas
  1150. std::vector<std::string> no_space_result;
  1151. EXPECT_TRUE(detail::parse_accept_header(
  1152. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1153. no_space_result));
  1154. EXPECT_EQ(no_space_result.size(), 3U);
  1155. EXPECT_EQ(no_space_result[0], "text/html");
  1156. EXPECT_EQ(no_space_result[1], "application/json");
  1157. EXPECT_EQ(no_space_result[2], "text/plain");
  1158. }
  1159. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1160. // Quality values always use '.' as the decimal separator, so parsing must
  1161. // not depend on the process locale. An embedding application may have
  1162. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1163. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1164. std::string saved = cur ? cur : "C";
  1165. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1166. "fr_FR.UTF-8"};
  1167. bool switched = false;
  1168. for (const auto loc : comma_locales) {
  1169. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1170. std::localeconv()->decimal_point[0] == ',') {
  1171. switched = true;
  1172. break;
  1173. }
  1174. }
  1175. if (!switched) {
  1176. std::setlocale(LC_NUMERIC, saved.c_str());
  1177. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1178. }
  1179. // The higher-weighted type appears later in the list, so a correct parse
  1180. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1181. // sensitive parse reads both weights as 0 and leaves the original order.
  1182. std::vector<std::string> result;
  1183. EXPECT_TRUE(detail::parse_accept_header(
  1184. "application/json;q=0.1,text/html;q=0.9", result));
  1185. ASSERT_EQ(result.size(), 2U);
  1186. EXPECT_EQ(result[0], "text/html");
  1187. EXPECT_EQ(result[1], "application/json");
  1188. std::setlocale(LC_NUMERIC, saved.c_str());
  1189. }
  1190. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1191. std::vector<std::string> result;
  1192. // Invalid quality value (> 1.0)
  1193. EXPECT_FALSE(
  1194. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1195. // Invalid quality value (< 0.0)
  1196. EXPECT_FALSE(
  1197. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1198. // Invalid quality value (not a number)
  1199. EXPECT_FALSE(detail::parse_accept_header(
  1200. "text/html;q=invalid,application/json", result));
  1201. // A valid numeric prefix does not make the entire quality value valid.
  1202. EXPECT_FALSE(detail::parse_accept_header(
  1203. "text/html;q=0.5junk,application/json", result));
  1204. // Empty quality value
  1205. EXPECT_FALSE(
  1206. detail::parse_accept_header("text/html;q=,application/json", result));
  1207. // Invalid media type format (no slash and not wildcard)
  1208. EXPECT_FALSE(
  1209. detail::parse_accept_header("invalidtype,application/json", result));
  1210. // Valid cases should still work
  1211. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1212. EXPECT_EQ(result.size(), 1U);
  1213. EXPECT_EQ(result[0], "*/*");
  1214. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1215. EXPECT_EQ(result.size(), 1U);
  1216. EXPECT_EQ(result[0], "*");
  1217. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1218. EXPECT_EQ(result.size(), 1U);
  1219. EXPECT_EQ(result[0], "text/*");
  1220. }
  1221. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1222. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1223. // and must not be answered with 400 Bad Request.
  1224. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1225. struct {
  1226. const char *value;
  1227. std::vector<std::string> expected;
  1228. } cases[] = {
  1229. {",application/json", {"application/json"}},
  1230. {"text/html,", {"text/html"}},
  1231. {"text/html,,*/*", {"text/html", "*/*"}},
  1232. // An empty element may be spelled with whitespace in it
  1233. {"text/html, , application/json", {"text/html", "application/json"}},
  1234. // Nothing but empty elements is an empty list, which means the same
  1235. // thing as no Accept header at all
  1236. {",,,", {}},
  1237. // Quality values still apply across ignored empty elements
  1238. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1239. };
  1240. for (const auto &c : cases) {
  1241. std::vector<std::string> result;
  1242. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1243. << "value: " << c.value;
  1244. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1245. }
  1246. // An invalid entry is still rejected when empty elements surround it
  1247. std::vector<std::string> result;
  1248. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1249. }
  1250. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1251. // or ';' inside one does not end the list element or the parameter. Section
  1252. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1253. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1254. struct {
  1255. const char *value;
  1256. std::vector<std::string> expected;
  1257. } cases[] = {
  1258. {"text/html;profile=\"a,b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // A "q=" inside a quoted value is not the weight
  1261. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1262. {"text/html", "application/json"}},
  1263. // The weight after a quoted value still applies
  1264. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1265. {"application/json", "text/html"}},
  1266. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1267. {"application/json", "text/html"}},
  1268. {"text/html;profile=\"a\\\"b\",application/json",
  1269. {"text/html", "application/json"}},
  1270. // An escaped backslash does not escape the '"' after it
  1271. {"text/html;profile=\"a\\\\\",application/json",
  1272. {"text/html", "application/json"}},
  1273. };
  1274. for (const auto &c : cases) {
  1275. std::vector<std::string> result;
  1276. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1277. << "value: " << c.value;
  1278. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1279. }
  1280. }
  1281. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1282. Server svr;
  1283. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1284. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1285. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1286. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1287. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1291. EXPECT_TRUE(false);
  1292. res.set_content("bad request", "text/plain");
  1293. });
  1294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. listen_thread.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. Client cli("localhost", PORT);
  1302. {
  1303. auto res = cli.Get(
  1304. "/accept_ok",
  1305. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1307. EXPECT_EQ(StatusCode::OK_200, res->status);
  1308. }
  1309. {
  1310. auto res = cli.Get("/accept_bad_request",
  1311. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1313. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1314. }
  1315. }
  1316. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1317. Server svr;
  1318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1319. res.set_content("ok", "text/plain");
  1320. });
  1321. std::atomic<int> start_count{0};
  1322. std::atomic<bool> running_when_called{false};
  1323. svr.set_start_handler([&]() {
  1324. running_when_called = svr.is_running();
  1325. start_count++;
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. std::thread t([&]() { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. // A successful request proves the accept loop is running, which the start
  1336. // handler precedes; so by now the handler must have run exactly once.
  1337. Client cli(HOST, port);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res = cli.Get("/");
  1340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(1, start_count.load());
  1343. EXPECT_TRUE(running_when_called.load());
  1344. }
  1345. TEST(DivideTest, DivideStringTests) {
  1346. auto divide = [](const std::string &str, char d) {
  1347. std::string lhs;
  1348. std::string rhs;
  1349. detail::divide(str, d,
  1350. [&](const char *lhs_data, std::size_t lhs_size,
  1351. const char *rhs_data, std::size_t rhs_size) {
  1352. lhs.assign(lhs_data, lhs_size);
  1353. rhs.assign(rhs_data, rhs_size);
  1354. });
  1355. return std::make_pair(std::move(lhs), std::move(rhs));
  1356. };
  1357. {
  1358. const auto res = divide("", '=');
  1359. EXPECT_EQ(res.first, "");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("=", '=');
  1364. EXPECT_EQ(res.first, "");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide(" ", '=');
  1369. EXPECT_EQ(res.first, " ");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("a", '=');
  1374. EXPECT_EQ(res.first, "a");
  1375. EXPECT_EQ(res.second, "");
  1376. }
  1377. {
  1378. const auto res = divide("a=", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "");
  1381. }
  1382. {
  1383. const auto res = divide("=b", '=');
  1384. EXPECT_EQ(res.first, "");
  1385. EXPECT_EQ(res.second, "b");
  1386. }
  1387. {
  1388. const auto res = divide("a=b", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b");
  1391. }
  1392. {
  1393. const auto res = divide("a=b=", '=');
  1394. EXPECT_EQ(res.first, "a");
  1395. EXPECT_EQ(res.second, "b=");
  1396. }
  1397. {
  1398. const auto res = divide("a=b=c", '=');
  1399. EXPECT_EQ(res.first, "a");
  1400. EXPECT_EQ(res.second, "b=c");
  1401. }
  1402. }
  1403. TEST(SplitTest, ParseQueryString) {
  1404. string s = "key1=val1&key2=val2&key3=val3";
  1405. Params dic;
  1406. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1407. [&](const char *b, const char *e) {
  1408. string key, val;
  1409. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1410. if (key.empty()) {
  1411. key.assign(b2, e2);
  1412. } else {
  1413. val.assign(b2, e2);
  1414. }
  1415. });
  1416. dic.emplace(key, val);
  1417. });
  1418. EXPECT_EQ("val1", dic.find("key1")->second);
  1419. EXPECT_EQ("val2", dic.find("key2")->second);
  1420. EXPECT_EQ("val3", dic.find("key3")->second);
  1421. }
  1422. TEST(SplitTest, ParseInvalidQueryTests) {
  1423. {
  1424. string s = " ";
  1425. Params dict;
  1426. detail::parse_query_text(s, dict);
  1427. EXPECT_TRUE(dict.empty());
  1428. }
  1429. {
  1430. string s = " = =";
  1431. Params dict;
  1432. detail::parse_query_text(s, dict);
  1433. EXPECT_TRUE(dict.empty());
  1434. }
  1435. }
  1436. TEST(ParseQueryTest, ParseQueryString) {
  1437. {
  1438. std::string s = "key1=val1&key2=val2&key3=val3";
  1439. Params dic;
  1440. detail::parse_query_text(s, dic);
  1441. EXPECT_EQ("val1", dic.find("key1")->second);
  1442. EXPECT_EQ("val2", dic.find("key2")->second);
  1443. EXPECT_EQ("val3", dic.find("key3")->second);
  1444. }
  1445. {
  1446. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1447. Params dic;
  1448. detail::parse_query_text(s, dic);
  1449. EXPECT_EQ("", dic.find("key1")->second);
  1450. EXPECT_EQ("val1", dic.find("key2")->second);
  1451. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1452. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1453. }
  1454. }
  1455. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1456. Params dic;
  1457. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1458. dic.emplace("key1", "val1");
  1459. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1460. dic.emplace("key2", "val2");
  1461. dic.emplace("key3", "val3");
  1462. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1463. }
  1464. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1465. Params params;
  1466. params.emplace("a", "1");
  1467. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1468. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1469. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1470. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1471. // Long enough to overflow the stack when matched with std::regex.
  1472. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1473. EXPECT_EQ("/p?" + long_query + "&a=1",
  1474. append_query_params("/p?" + long_query, params));
  1475. }
  1476. // Joins every entry of a Headers or Params into "key=value " so a whole
  1477. // traversal can be compared in one assertion. Both are instantiations of the
  1478. // same insertion-ordered container, so one helper serves both.
  1479. template <typename Map> static std::string entries_to_string(const Map &m) {
  1480. std::string s;
  1481. for (const auto &entry : m) {
  1482. s += entry.first + "=" + entry.second + " ";
  1483. }
  1484. return s;
  1485. }
  1486. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1487. // Params used to be a std::multimap, which sorted by name and handed the
  1488. // caller's query back alphabetised. A client signing its query string could
  1489. // not reproduce the order it asked for.
  1490. Params dic;
  1491. dic.emplace("zulu", "1");
  1492. dic.emplace("alpha", "2");
  1493. dic.emplace("mike", "3");
  1494. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1495. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1496. }
  1497. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1498. Params dic;
  1499. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1500. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1501. }
  1502. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1503. Request req;
  1504. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1505. req.params);
  1506. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1507. EXPECT_EQ("first", req.get_param_value("tag"));
  1508. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1509. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1510. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1511. EXPECT_EQ("", req.get_param_value("tag", 3));
  1512. }
  1513. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1514. // Params shares its container with Headers, which matches field names
  1515. // case-insensitively. Parameter names must not pick that up.
  1516. Params dic;
  1517. dic.emplace("Key", "upper");
  1518. dic.emplace("key", "lower");
  1519. EXPECT_EQ(2U, dic.size());
  1520. EXPECT_EQ(1U, dic.count("Key"));
  1521. EXPECT_EQ(1U, dic.count("key"));
  1522. EXPECT_EQ("upper", dic.find("Key")->second);
  1523. EXPECT_EQ("lower", dic.find("key")->second);
  1524. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1525. }
  1526. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1527. Server svr;
  1528. std::string order;
  1529. svr.Get("/order", [&](const Request &req, Response &res) {
  1530. order = entries_to_string(req.params);
  1531. res.set_content("ok", "text/plain");
  1532. });
  1533. auto port = svr.bind_to_any_port(HOST);
  1534. thread t = thread([&] { svr.listen_after_bind(); });
  1535. auto se = detail::scope_exit([&] {
  1536. svr.stop();
  1537. t.join();
  1538. ASSERT_FALSE(svr.is_running());
  1539. });
  1540. svr.wait_until_ready();
  1541. Client cli(HOST, port);
  1542. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1543. ASSERT_TRUE(res);
  1544. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1545. }
  1546. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1547. Server svr;
  1548. std::string field_order, file_order;
  1549. svr.Post("/order", [&](const Request &req, Response &res) {
  1550. for (const auto &field : req.form.fields) {
  1551. field_order += field.first + "=" + field.second.content + " ";
  1552. }
  1553. for (const auto &file : req.form.files) {
  1554. file_order += file.first + "=" + file.second.filename + " ";
  1555. }
  1556. res.set_content("ok", "text/plain");
  1557. });
  1558. auto port = svr.bind_to_any_port(HOST);
  1559. thread t = thread([&] { svr.listen_after_bind(); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. t.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. UploadFormDataItems items = {
  1567. {"zulu", "1", "", ""},
  1568. {"alpha", "2", "", ""},
  1569. {"mike", "3", "", ""},
  1570. {"zebra", "z", "z.txt", "text/plain"},
  1571. {"apple", "a", "a.txt", "text/plain"},
  1572. };
  1573. Client cli(HOST, port);
  1574. auto res = cli.Post("/order", items);
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1577. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1578. }
  1579. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1580. Server svr;
  1581. std::vector<std::string> values;
  1582. std::string first, second, out_of_range, order;
  1583. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1584. values = req.form.get_fields("tag");
  1585. first = req.form.get_field("tag", 0);
  1586. second = req.form.get_field("tag", 1);
  1587. out_of_range = req.form.get_field("tag", 2);
  1588. for (const auto &field : req.form.fields) {
  1589. order += field.first + "=" + field.second.content + " ";
  1590. }
  1591. res.set_content("ok", "text/plain");
  1592. });
  1593. auto port = svr.bind_to_any_port(HOST);
  1594. thread t = thread([&] { svr.listen_after_bind(); });
  1595. auto se = detail::scope_exit([&] {
  1596. svr.stop();
  1597. t.join();
  1598. ASSERT_FALSE(svr.is_running());
  1599. });
  1600. svr.wait_until_ready();
  1601. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1602. // not adjacent in the container.
  1603. UploadFormDataItems items = {
  1604. {"tag", "first", "", ""},
  1605. {"other", "x", "", ""},
  1606. {"tag", "second", "", ""},
  1607. };
  1608. Client cli(HOST, port);
  1609. auto res = cli.Post("/repeated", items);
  1610. ASSERT_TRUE(res);
  1611. ASSERT_EQ(2U, values.size());
  1612. EXPECT_EQ("first", values[0]);
  1613. EXPECT_EQ("second", values[1]);
  1614. EXPECT_EQ("first", first);
  1615. EXPECT_EQ("second", second);
  1616. // std::multimap already kept entries sharing a name in insertion order, so
  1617. // everything above passes without this change too. The whole traversal is
  1618. // what tells the two apart: sorting by name would hoist "other" to the front
  1619. // and the two "tag" parts would end up adjacent.
  1620. EXPECT_EQ("tag=first other=x tag=second ", order);
  1621. // Advancing past the last entry of a name used to run off the container;
  1622. // the container's saturating increment makes it return the default instead.
  1623. EXPECT_EQ("", out_of_range);
  1624. }
  1625. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1626. Server svr;
  1627. std::string file_names;
  1628. svr.Post("/upload", [&](const Request &req, Response &res) {
  1629. for (const auto &file : req.form.files) {
  1630. file_names += file.first + "|" + file.second.filename + " ";
  1631. }
  1632. res.set_content("ok", "text/plain");
  1633. });
  1634. auto port = svr.bind_to_any_port(HOST);
  1635. thread t = thread([&] { svr.listen_after_bind(); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. t.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. // A trailing backslash would otherwise escape the closing quote.
  1643. UploadFormDataItems items = {
  1644. {"dir\\", "x", "a.txt", "text/plain"},
  1645. {"b", "y", "a\\\\b.txt", "text/plain"},
  1646. };
  1647. Client cli(HOST, port);
  1648. auto res = cli.Post("/upload", items);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1651. }
  1652. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1653. // Server::read_content() keeps a FormFields::iterator alive across the
  1654. // content callbacks that fill the part it points at. The container is
  1655. // vector-backed, so a later emplace can reallocate and invalidate an older
  1656. // iterator; 64 parts grow the vector through seven reallocations, which
  1657. // checks that every part's content still lands in its own entry.
  1658. const size_t part_count = 64;
  1659. // One formula for both the parts sent and the values expected back, so the
  1660. // two cannot drift apart.
  1661. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1662. auto content_of = [](size_t i) {
  1663. return std::string(64, static_cast<char>('a' + (i % 26)));
  1664. };
  1665. Server svr;
  1666. std::vector<std::pair<std::string, std::string>> received;
  1667. svr.Post("/many", [&](const Request &req, Response &res) {
  1668. for (const auto &field : req.form.fields) {
  1669. received.emplace_back(field.first, field.second.content);
  1670. }
  1671. res.set_content("ok", "text/plain");
  1672. });
  1673. auto port = svr.bind_to_any_port(HOST);
  1674. thread t = thread([&] { svr.listen_after_bind(); });
  1675. auto se = detail::scope_exit([&] {
  1676. svr.stop();
  1677. t.join();
  1678. ASSERT_FALSE(svr.is_running());
  1679. });
  1680. svr.wait_until_ready();
  1681. UploadFormDataItems items;
  1682. for (size_t i = 0; i < part_count; i++) {
  1683. items.push_back({name_of(i), content_of(i), "", ""});
  1684. }
  1685. Client cli(HOST, port);
  1686. auto res = cli.Post("/many", items);
  1687. ASSERT_TRUE(res);
  1688. ASSERT_EQ(part_count, received.size());
  1689. for (size_t i = 0; i < part_count; i++) {
  1690. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1691. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1692. }
  1693. }
  1694. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1695. string content_type = "multipart/form-data; boundary=something";
  1696. string boundary;
  1697. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1698. EXPECT_TRUE(ret);
  1699. EXPECT_EQ(boundary, "something");
  1700. }
  1701. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1702. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1703. string boundary;
  1704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1705. EXPECT_TRUE(ret);
  1706. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1709. string content_type =
  1710. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1711. string boundary;
  1712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1713. EXPECT_TRUE(ret);
  1714. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1715. }
  1716. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1717. string content_type =
  1718. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1719. string boundary;
  1720. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1723. }
  1724. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1725. const string boundary(70, 'a');
  1726. string content_type = "multipart/form-data; boundary=" + boundary;
  1727. string parsed;
  1728. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1729. EXPECT_TRUE(ret);
  1730. EXPECT_EQ(parsed, boundary);
  1731. }
  1732. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1733. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1734. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1735. string parsed;
  1736. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1737. EXPECT_FALSE(ret);
  1738. }
  1739. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1740. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1741. // is 72 characters on the wire and still valid.
  1742. const string boundary(70, 'a');
  1743. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1744. string parsed;
  1745. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1746. EXPECT_EQ(parsed, boundary);
  1747. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1748. parsed.clear();
  1749. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1752. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1753. // The parameter parser must not treat that '=' as the key/value separator.
  1754. string content_type =
  1755. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1756. "charset=UTF-8";
  1757. string parsed;
  1758. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1759. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1760. }
  1761. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1762. // A ';' inside the quoted-string is part of the value, not a parameter
  1763. // separator, so it must not truncate the boundary.
  1764. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1765. string parsed;
  1766. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1767. EXPECT_EQ(parsed, "a;b");
  1768. }
  1769. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1770. string parsed;
  1771. EXPECT_TRUE(detail::parse_multipart_boundary(
  1772. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1773. EXPECT_EQ("a\\b", parsed);
  1774. EXPECT_TRUE(detail::parse_multipart_boundary(
  1775. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1776. EXPECT_EQ("a\"b", parsed);
  1777. }
  1778. TEST(ParseDispositionParamsTest, QuotedValues) {
  1779. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1780. // ';' and '=' are ordinary characters inside one.
  1781. struct {
  1782. const char *value;
  1783. std::vector<std::pair<const char *, const char *>> expected;
  1784. } cases[] = {
  1785. {"name=\"file1\"; filename=\"a.txt\"",
  1786. {{"name", "file1"}, {"filename", "a.txt"}}},
  1787. // MIME parameter names are case-insensitive, but their values are not.
  1788. {"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
  1789. {{"name", "Upload"}, {"filename", "Report.TXT"}}},
  1790. // Whitespace around '=' and ';' is still trimmed
  1791. {"name=\"file2\" ;filename = \"a.html\"",
  1792. {{"name", "file2"}, {"filename", "a.html"}}},
  1793. // '=' inside the value used to leave only the text after the last one
  1794. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1795. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1796. {"name=\"x=y\"", {{"name", "x=y"}}},
  1797. // ';' inside the value used to truncate the pair and leave a bogus one
  1798. {"name=\"file3\"; filename=\"a;b.txt\"",
  1799. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1800. // An unquoted value keeps working, and so does filename*
  1801. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1802. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1803. // A parameter with no key is dropped rather than turned into one whose
  1804. // key is the value
  1805. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1806. // An escaped quote does not end the value
  1807. {"name=\"a\\\"; filename=evil.php\"",
  1808. {{"name", "a\"; filename=evil.php"}}},
  1809. // Other backslashes, as in a Windows path, are kept
  1810. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1811. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1812. };
  1813. for (const auto &c : cases) {
  1814. Params params;
  1815. detail::parse_disposition_params(c.value, params);
  1816. for (const auto &kv : c.expected) {
  1817. auto it = params.find(kv.first);
  1818. ASSERT_NE(it, params.end())
  1819. << "value: " << c.value << ", key: " << kv.first;
  1820. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1821. }
  1822. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1823. }
  1824. }
  1825. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1826. Server svr;
  1827. std::string filename;
  1828. std::string content;
  1829. svr.Post("/upload", [&](const Request &req, Response &) {
  1830. const auto &file = req.form.get_file("file");
  1831. filename = file.filename;
  1832. content = file.content;
  1833. });
  1834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1835. auto se = detail::scope_exit([&] {
  1836. svr.stop();
  1837. thread.join();
  1838. ASSERT_FALSE(svr.is_running());
  1839. });
  1840. svr.wait_until_ready();
  1841. std::string body = "--B\r\n"
  1842. "Content-Disposition: form-data; name=\"file\"; "
  1843. "filename=\"a.txt\"\r\n"
  1844. "Content-Type: text/plain\r\n"
  1845. "\r\n"
  1846. "hello\r\n"
  1847. "--B--\r\n";
  1848. Client cli(HOST, PORT);
  1849. auto res = cli.Post(
  1850. "/upload",
  1851. [&](size_t offset, DataSink &sink) {
  1852. if (offset < body.size()) {
  1853. sink.write(&body[offset], 1);
  1854. } else {
  1855. sink.done();
  1856. }
  1857. return true;
  1858. },
  1859. "multipart/form-data; boundary=B");
  1860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1861. EXPECT_EQ(StatusCode::OK_200, res->status);
  1862. EXPECT_EQ("a.txt", filename);
  1863. EXPECT_EQ("hello", content);
  1864. }
  1865. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1866. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1867. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1868. Server svr;
  1869. std::string field_value, file_name, file_filename;
  1870. bool has_field = false, has_file = false;
  1871. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1872. has_field = req.form.has_field("x=y");
  1873. field_value = req.form.get_field("x=y");
  1874. has_file = req.form.has_file("file1");
  1875. const auto &file = req.form.get_file("file1");
  1876. file_name = file.name;
  1877. file_filename = file.filename;
  1878. res.set_content("ok", "text/plain");
  1879. });
  1880. auto port = svr.bind_to_any_port(HOST);
  1881. thread t = thread([&] { svr.listen_after_bind(); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. t.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. UploadFormDataItems items = {
  1889. {"x=y", "field-value", "", ""},
  1890. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1891. };
  1892. Client cli(HOST, port);
  1893. auto res = cli.Post("/quoted", items);
  1894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1895. ASSERT_EQ(StatusCode::OK_200, res->status);
  1896. EXPECT_TRUE(has_field);
  1897. EXPECT_EQ("field-value", field_value);
  1898. EXPECT_TRUE(has_file);
  1899. EXPECT_EQ("file1", file_name);
  1900. EXPECT_EQ("a;b=report.pdf", file_filename);
  1901. }
  1902. TEST(GetHeaderValueTest, DefaultValue) {
  1903. Headers headers = {{"Dummy", "Dummy"}};
  1904. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1905. EXPECT_STREQ("text/plain", val);
  1906. }
  1907. TEST(GetHeaderValueTest, DefaultValueInt) {
  1908. Headers headers = {{"Dummy", "Dummy"}};
  1909. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1910. EXPECT_EQ(100ull, val);
  1911. }
  1912. TEST(GetHeaderValueTest, RegularValue) {
  1913. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1914. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1915. EXPECT_STREQ("text/html", val);
  1916. }
  1917. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1918. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1919. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1920. EXPECT_STREQ("text/html", val);
  1921. }
  1922. TEST(GetHeaderValueTest, SetContent) {
  1923. Response res;
  1924. res.set_content("html", "text/html");
  1925. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1926. res.set_content("text", "text/plain");
  1927. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1928. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1929. }
  1930. TEST(GetHeaderValueTest, RegularValueInt) {
  1931. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1932. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1933. EXPECT_EQ(100ull, val);
  1934. }
  1935. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1936. Headers headers = {{"Content-Length", "x"}};
  1937. auto is_invalid_value = false;
  1938. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1939. is_invalid_value);
  1940. EXPECT_EQ(0ull, val);
  1941. EXPECT_TRUE(is_invalid_value);
  1942. }
  1943. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1944. // An all-digit value that overflows size_t must be reported as invalid, not
  1945. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1946. // a large length to a small one on 32-bit builds, leaving the framing length
  1947. // wrong while is_invalid_value stayed false.
  1948. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1949. auto is_invalid_value = false;
  1950. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1951. is_invalid_value);
  1952. EXPECT_TRUE(is_invalid_value);
  1953. // A well-formed length is unaffected.
  1954. Headers ok = {{"Content-Length", "1234"}};
  1955. is_invalid_value = false;
  1956. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1957. is_invalid_value);
  1958. EXPECT_EQ(1234ull, val);
  1959. EXPECT_FALSE(is_invalid_value);
  1960. }
  1961. TEST(GetHeaderValueTest, Range) {
  1962. {
  1963. Headers headers = {make_range_header({{1, -1}})};
  1964. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1965. EXPECT_STREQ("bytes=1-", val);
  1966. }
  1967. {
  1968. Headers headers = {make_range_header({{-1, 1}})};
  1969. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1970. EXPECT_STREQ("bytes=-1", val);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, 10}})};
  1974. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1975. EXPECT_STREQ("bytes=1-10", val);
  1976. }
  1977. {
  1978. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1979. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1980. EXPECT_STREQ("bytes=1-10, 100-", val);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1984. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1985. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1986. }
  1987. {
  1988. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1989. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1990. EXPECT_STREQ("bytes=0-0, -1", val);
  1991. }
  1992. }
  1993. TEST(BearerTokenAuthTest, SchemeValidation) {
  1994. // A value shorter than "Bearer " must not throw from the fixed-length
  1995. // substr, and a non-Bearer scheme must not be reported as a token.
  1996. struct {
  1997. const char *value;
  1998. const char *expected;
  1999. } cases[] = {
  2000. {"x", ""},
  2001. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  2002. {"Bearer abc123", "abc123"},
  2003. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  2004. {"Bearer abc123", "abc123"}, // 1*SP after the scheme
  2005. };
  2006. for (const auto &c : cases) {
  2007. Request req;
  2008. req.set_header("Authorization", c.value);
  2009. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  2010. }
  2011. }
  2012. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  2013. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2014. // to depend on the standard library (libstdc++ handed back duplicates in
  2015. // reverse insertion order, libc++ in insertion order).
  2016. Request req;
  2017. req.set_header("Accept-Encoding", "gzip");
  2018. req.set_header("Accept-Encoding", "deflate");
  2019. req.set_header("Accept-Encoding", "br");
  2020. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2021. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2022. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2023. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2024. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2025. }
  2026. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2027. Request req;
  2028. req.set_header("X-Test", "only");
  2029. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2030. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2031. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2032. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2033. }
  2034. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2035. Request req;
  2036. req.set_header("X-First", "1");
  2037. req.set_header("X-Test", "2");
  2038. req.params.emplace("first", "1");
  2039. req.params.emplace("test", "2");
  2040. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2041. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2042. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2043. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2044. // The second one is negative when read as a signed value
  2045. const auto max_id = (std::numeric_limits<size_t>::max)();
  2046. for (auto id : {max_id / 2, max_id}) {
  2047. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2048. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2049. EXPECT_EQ("", req.get_param_value("test", id));
  2050. EXPECT_EQ("", req.form.get_field("test", id));
  2051. EXPECT_EQ("", req.form.get_file("test", id).content);
  2052. }
  2053. }
  2054. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2055. Headers headers;
  2056. headers.emplace("Host", "example.com");
  2057. headers.emplace("Accept-Encoding", "gzip");
  2058. headers.emplace("User-Agent", "test");
  2059. headers.emplace("Accept-Encoding", "deflate");
  2060. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2061. "Accept-Encoding=deflate ",
  2062. entries_to_string(headers));
  2063. }
  2064. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2065. Headers headers = {{"Content-Type", "text/html"},
  2066. {"CONTENT-TYPE", "text/xml"}};
  2067. EXPECT_EQ(2U, headers.count("content-type"));
  2068. auto it = headers.find("content-type");
  2069. ASSERT_TRUE(it != headers.end());
  2070. EXPECT_EQ("text/html", it->second);
  2071. }
  2072. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2073. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2074. // drop only those fields and leave everything positioned between them.
  2075. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2076. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2077. auto rng = headers.equal_range("a");
  2078. headers.erase(rng.first, rng.second);
  2079. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2080. }
  2081. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2082. Headers headers = {
  2083. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2084. EXPECT_EQ(3U, headers.erase("A"));
  2085. EXPECT_EQ(0U, headers.count("A"));
  2086. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2087. }
  2088. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2089. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2090. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2091. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2092. }
  2093. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2094. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2095. headers.emplace_front("Host", "example.com");
  2096. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2097. entries_to_string(headers));
  2098. }
  2099. TEST(ParseHeaderValueTest, Range) {
  2100. {
  2101. Ranges ranges;
  2102. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2103. EXPECT_TRUE(ret);
  2104. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2105. }
  2106. {
  2107. Ranges ranges;
  2108. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2109. EXPECT_TRUE(ret);
  2110. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2111. }
  2112. {
  2113. Ranges ranges;
  2114. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2115. EXPECT_TRUE(ret);
  2116. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2117. }
  2118. {
  2119. Ranges ranges;
  2120. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2121. EXPECT_FALSE(ret);
  2122. }
  2123. {
  2124. Ranges ranges;
  2125. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2126. EXPECT_TRUE(ret);
  2127. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2128. }
  2129. {
  2130. Ranges ranges;
  2131. auto ret =
  2132. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2133. EXPECT_TRUE(ret);
  2134. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2135. }
  2136. {
  2137. Ranges ranges;
  2138. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2139. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2140. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2141. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2142. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2143. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2144. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2145. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2146. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2147. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2148. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2149. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2150. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2151. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2152. EXPECT_FALSE(
  2153. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2154. EXPECT_TRUE(ranges.empty());
  2155. }
  2156. {
  2157. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2158. // remainder of the representation, so it stays accepted.
  2159. Ranges ranges;
  2160. auto ret =
  2161. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2162. EXPECT_TRUE(ret);
  2163. ASSERT_EQ(1u, ranges.size());
  2164. EXPECT_EQ(0, ranges[0].first);
  2165. EXPECT_EQ(-1, ranges[0].second);
  2166. }
  2167. // RFC 9110 14.1: range unit names are case-insensitive.
  2168. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2169. Ranges ranges;
  2170. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2171. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2172. }
  2173. }
  2174. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2175. Request req;
  2176. req.set_header("Accept-Encoding", "gzip");
  2177. Response res;
  2178. res.set_header("Content-Type", "text/plain");
  2179. auto ret = detail::encoding_type(req, res);
  2180. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2181. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2182. #else
  2183. EXPECT_TRUE(ret == detail::EncodingType::None);
  2184. #endif
  2185. }
  2186. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2187. Request req;
  2188. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2189. Response res;
  2190. res.set_header("Content-Type", "text/plain");
  2191. auto ret = detail::encoding_type(req, res);
  2192. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2193. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2194. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2195. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2196. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2197. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2198. #else
  2199. EXPECT_TRUE(ret == detail::EncodingType::None);
  2200. #endif
  2201. }
  2202. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2203. Request req;
  2204. req.set_header("Accept-Encoding",
  2205. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2206. Response res;
  2207. res.set_header("Content-Type", "text/plain");
  2208. auto ret = detail::encoding_type(req, res);
  2209. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2210. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2211. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2212. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2213. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2214. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2215. #else
  2216. EXPECT_TRUE(ret == detail::EncodingType::None);
  2217. #endif
  2218. }
  2219. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2220. // All supported encodings rejected with q=0 should return None
  2221. Request req;
  2222. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2223. Response res;
  2224. res.set_header("Content-Type", "text/plain");
  2225. auto ret = detail::encoding_type(req, res);
  2226. EXPECT_TRUE(ret == detail::EncodingType::None);
  2227. }
  2228. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2229. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2230. Request req;
  2231. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2232. Response res;
  2233. res.set_header("Content-Type", "text/plain");
  2234. auto ret = detail::encoding_type(req, res);
  2235. EXPECT_TRUE(ret == detail::EncodingType::None);
  2236. }
  2237. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2238. Request req;
  2239. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2240. Response res;
  2241. res.set_header("Content-Type", "text/plain");
  2242. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2243. }
  2244. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2245. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2246. Request req;
  2247. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2248. Response res;
  2249. res.set_header("Content-Type", "text/plain");
  2250. auto ret = detail::encoding_type(req, res);
  2251. EXPECT_TRUE(ret == detail::EncodingType::None);
  2252. }
  2253. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2254. // RFC 7231: Accept-Encoding values are case-insensitive
  2255. Request req;
  2256. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2257. Response res;
  2258. res.set_header("Content-Type", "text/plain");
  2259. auto ret = detail::encoding_type(req, res);
  2260. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2261. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2262. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2263. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2264. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2265. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2266. #else
  2267. EXPECT_TRUE(ret == detail::EncodingType::None);
  2268. #endif
  2269. }
  2270. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2271. // q value should determine priority, not hardcoded order
  2272. Request req;
  2273. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2274. Response res;
  2275. res.set_header("Content-Type", "text/plain");
  2276. auto ret = detail::encoding_type(req, res);
  2277. // gzip has highest q=1.0, so it should be selected even though
  2278. // br and zstd are also supported
  2279. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2280. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2281. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2282. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2283. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2284. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2285. #else
  2286. EXPECT_TRUE(ret == detail::EncodingType::None);
  2287. #endif
  2288. }
  2289. TEST(BufferStreamTest, read) {
  2290. detail::BufferStream strm1;
  2291. Stream &strm = strm1;
  2292. EXPECT_EQ(5, strm.write("hello"));
  2293. char buf[512];
  2294. EXPECT_EQ(2, strm.read(buf, 2));
  2295. EXPECT_EQ('h', buf[0]);
  2296. EXPECT_EQ('e', buf[1]);
  2297. EXPECT_EQ(2, strm.read(buf, 2));
  2298. EXPECT_EQ('l', buf[0]);
  2299. EXPECT_EQ('l', buf[1]);
  2300. EXPECT_EQ(1, strm.read(buf, 1));
  2301. EXPECT_EQ('o', buf[0]);
  2302. EXPECT_EQ(0, strm.read(buf, 1));
  2303. }
  2304. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2305. auto host = "www.httpwatch.com";
  2306. auto ip = hosted_at(host);
  2307. EXPECT_EQ("23.96.13.243", ip);
  2308. std::vector<std::string> addrs;
  2309. hosted_at(host, addrs);
  2310. EXPECT_EQ(1u, addrs.size());
  2311. }
  2312. #if 0 // It depends on each test environment...
  2313. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2314. auto host = "www.youtube.com";
  2315. std::vector<std::string> addrs;
  2316. hosted_at(host, addrs);
  2317. EXPECT_EQ(20u, addrs.size());
  2318. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2319. EXPECT_TRUE(it != addrs.end());
  2320. }
  2321. #endif
  2322. class ChunkedEncodingTest : public ::testing::Test {
  2323. protected:
  2324. ChunkedEncodingTest()
  2325. : cli_(HOST, PORT)
  2326. #ifdef CPPHTTPLIB_SSL_ENABLED
  2327. ,
  2328. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2329. #endif
  2330. {
  2331. cli_.set_connection_timeout(2);
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. cli_.enable_server_certificate_verification(false);
  2334. #endif
  2335. }
  2336. virtual void SetUp() {
  2337. read_file("./image.jpg", image_data_);
  2338. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2339. res.set_content("Hello World!", "text/plain");
  2340. });
  2341. svr_.Get(
  2342. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2343. res.set_chunked_content_provider(
  2344. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2345. size_t remaining = image_data_.size() - offset;
  2346. if (remaining == 0) {
  2347. sink.done();
  2348. } else {
  2349. constexpr size_t CHUNK_SIZE = 1024;
  2350. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2351. sink.write(&image_data_[offset], send_size);
  2352. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2353. }
  2354. return true;
  2355. });
  2356. });
  2357. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2358. svr_.wait_until_ready();
  2359. }
  2360. virtual void TearDown() {
  2361. svr_.stop();
  2362. if (!request_threads_.empty()) {
  2363. std::this_thread::sleep_for(std::chrono::seconds(1));
  2364. for (auto &t : request_threads_) {
  2365. t.join();
  2366. }
  2367. }
  2368. t_.join();
  2369. }
  2370. #ifdef CPPHTTPLIB_SSL_ENABLED
  2371. SSLClient cli_;
  2372. SSLServer svr_;
  2373. #else
  2374. Client cli_;
  2375. Server svr_;
  2376. #endif
  2377. thread t_;
  2378. std::vector<thread> request_threads_;
  2379. std::string image_data_;
  2380. };
  2381. TEST_F(ChunkedEncodingTest, NormalGet) {
  2382. auto res = cli_.Get("/chunked");
  2383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2384. std::string out;
  2385. read_file("./image.jpg", out);
  2386. EXPECT_EQ(StatusCode::OK_200, res->status);
  2387. EXPECT_EQ(out, res->body);
  2388. }
  2389. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2390. std::string body;
  2391. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2392. body.append(data, data_length);
  2393. return true;
  2394. });
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. std::string out;
  2397. read_file("./image.jpg", out);
  2398. EXPECT_EQ(StatusCode::OK_200, res->status);
  2399. EXPECT_EQ(out, body);
  2400. }
  2401. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2402. std::string body;
  2403. auto res = cli_.Get(
  2404. "/chunked",
  2405. [&](const Response &response) {
  2406. EXPECT_EQ(StatusCode::OK_200, response.status);
  2407. return true;
  2408. },
  2409. [&](const char *data, size_t data_length) {
  2410. body.append(data, data_length);
  2411. return true;
  2412. });
  2413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2414. std::string out;
  2415. read_file("./image.jpg", out);
  2416. EXPECT_EQ(StatusCode::OK_200, res->status);
  2417. EXPECT_EQ(out, body);
  2418. }
  2419. TEST(RangeTest, FromHTTPBin_Online) {
  2420. auto host = "httpbingo.org";
  2421. auto path = std::string{"/range/32"};
  2422. #ifdef CPPHTTPLIB_SSL_ENABLED
  2423. auto port = 443;
  2424. SSLClient cli(host, port);
  2425. #else
  2426. auto port = 80;
  2427. Client cli(host, port);
  2428. #endif
  2429. cli.set_connection_timeout(5);
  2430. {
  2431. auto res = retry_service_failures([&] { return cli.Get(path); });
  2432. SKIP_ON_SERVICE_FAILURE(res);
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2435. EXPECT_EQ(StatusCode::OK_200, res->status);
  2436. }
  2437. {
  2438. Headers headers = {make_range_header({{1, -1}})};
  2439. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2440. SKIP_ON_SERVICE_FAILURE(res);
  2441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2442. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2444. }
  2445. {
  2446. Headers headers = {make_range_header({{1, 10}})};
  2447. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2448. SKIP_ON_SERVICE_FAILURE(res);
  2449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2450. EXPECT_EQ("bcdefghijk", res->body);
  2451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2452. }
  2453. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2454. // entire resource, while the original httpbin returned 200. Both are
  2455. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2456. {
  2457. Headers headers = {make_range_header({{0, 31}})};
  2458. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2459. SKIP_ON_SERVICE_FAILURE(res);
  2460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2461. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2462. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2463. res->status == StatusCode::PartialContent_206);
  2464. }
  2465. {
  2466. Headers headers = {make_range_header({{0, -1}})};
  2467. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2468. SKIP_ON_SERVICE_FAILURE(res);
  2469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2470. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2471. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2472. res->status == StatusCode::PartialContent_206);
  2473. }
  2474. // go-httpbin returns 206 with clamped range for over-range requests,
  2475. // while the original httpbin returned 416. Both behaviors are observed
  2476. // in real servers, so we only verify the request succeeds.
  2477. {
  2478. Headers headers = {make_range_header({{0, 32}})};
  2479. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2480. SKIP_ON_SERVICE_FAILURE(res);
  2481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2482. }
  2483. }
  2484. TEST(RangeTest, IgnoredForPost) {
  2485. Server svr;
  2486. svr.Post("/", [](const Request &, Response &res) {
  2487. res.set_content("abcdefg", "text/plain");
  2488. });
  2489. auto port = svr.bind_to_any_port(HOST);
  2490. ASSERT_GT(port, 0);
  2491. thread t = thread([&] { svr.listen_after_bind(); });
  2492. auto se = detail::scope_exit([&] {
  2493. svr.stop();
  2494. t.join();
  2495. ASSERT_FALSE(svr.is_running());
  2496. });
  2497. svr.wait_until_ready();
  2498. Client cli(HOST, port);
  2499. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2500. auto res = cli.Post("/", Headers{{"Range", range}});
  2501. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2502. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2503. EXPECT_EQ("abcdefg", res->body) << range;
  2504. }
  2505. }
  2506. TEST(RangeTest, IgnoredForUnknownUnit) {
  2507. Server svr;
  2508. svr.Get("/", [](const Request &, Response &res) {
  2509. res.set_content("abcdefg", "text/plain");
  2510. });
  2511. auto port = svr.bind_to_any_port(HOST);
  2512. ASSERT_GT(port, 0);
  2513. thread t = thread([&] { svr.listen_after_bind(); });
  2514. auto se = detail::scope_exit([&] {
  2515. svr.stop();
  2516. t.join();
  2517. ASSERT_FALSE(svr.is_running());
  2518. });
  2519. svr.wait_until_ready();
  2520. Client cli(HOST, port);
  2521. for (auto range : {"items=1-2", "none=x"}) {
  2522. auto res = cli.Get("/", Headers{{"Range", range}});
  2523. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2524. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2525. EXPECT_EQ("abcdefg", res->body) << range;
  2526. }
  2527. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2528. ASSERT_TRUE(res) << to_string(res.error());
  2529. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2530. }
  2531. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2532. auto host = "unresolvableaddress.local";
  2533. auto path = std::string{"/"};
  2534. #ifdef CPPHTTPLIB_SSL_ENABLED
  2535. auto port = 443;
  2536. SSLClient cli(host, port);
  2537. #else
  2538. auto port = 80;
  2539. Client cli(host, port);
  2540. #endif
  2541. cli.set_connection_timeout(1);
  2542. {
  2543. auto res = cli.Get(path);
  2544. ASSERT_FALSE(res);
  2545. }
  2546. std::this_thread::sleep_for(std::chrono::seconds(8));
  2547. }
  2548. #if defined(__linux__) && defined(__GLIBC__) && \
  2549. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2550. // Forward declaration: in split builds split.py strips `inline` and moves the
  2551. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2552. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2553. // against the symbol in both header-only and split builds.
  2554. namespace httplib {
  2555. namespace detail {
  2556. int getaddrinfo_with_timeout(const char *node, const char *service,
  2557. const struct addrinfo *hints,
  2558. struct addrinfo **res, time_t timeout_sec);
  2559. } // namespace detail
  2560. } // namespace httplib
  2561. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2562. //
  2563. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2564. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2565. // gai_suspend() call hits the connection timeout the function calls
  2566. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2567. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2568. // still alive and still references the now-destroyed stack frame.
  2569. //
  2570. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2571. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2572. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2573. // and runs them in a container.
  2574. namespace {
  2575. bool should_run_issue_2431_tests() {
  2576. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2577. return v && *v && std::string(v) != "0";
  2578. }
  2579. std::string unique_unresolvable_host(int n) {
  2580. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2581. // glibc still asks the configured nameserver — which is exactly the path
  2582. // we want to exercise. A unique label per call avoids the resolver cache.
  2583. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2584. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2585. std::to_string(n) + ".invalid";
  2586. }
  2587. } // namespace
  2588. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2589. if (!should_run_issue_2431_tests()) {
  2590. GTEST_SKIP()
  2591. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2592. }
  2593. for (int i = 0; i < 8; ++i) {
  2594. struct addrinfo hints;
  2595. memset(&hints, 0, sizeof(hints));
  2596. hints.ai_family = AF_UNSPEC;
  2597. hints.ai_socktype = SOCK_STREAM;
  2598. auto host = unique_unresolvable_host(i);
  2599. struct addrinfo *result = nullptr;
  2600. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2601. &result, /*timeout_sec=*/1);
  2602. if (rc == 0 && result) { freeaddrinfo(result); }
  2603. }
  2604. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2605. // stack region they still believe holds their gaicb.
  2606. std::this_thread::sleep_for(std::chrono::seconds(3));
  2607. }
  2608. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2609. if (!should_run_issue_2431_tests()) {
  2610. GTEST_SKIP()
  2611. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2612. }
  2613. std::atomic<bool> stop{false};
  2614. std::vector<std::thread> threads;
  2615. for (int t = 0; t < 8; ++t) {
  2616. threads.emplace_back([t, &stop] {
  2617. int i = 0;
  2618. while (!stop.load(std::memory_order_relaxed)) {
  2619. struct addrinfo hints;
  2620. memset(&hints, 0, sizeof(hints));
  2621. hints.ai_family = AF_UNSPEC;
  2622. hints.ai_socktype = SOCK_STREAM;
  2623. auto host = unique_unresolvable_host(t * 100000 + i++);
  2624. struct addrinfo *result = nullptr;
  2625. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2626. &result, /*timeout_sec=*/1);
  2627. if (rc == 0 && result) { freeaddrinfo(result); }
  2628. }
  2629. });
  2630. }
  2631. std::this_thread::sleep_for(std::chrono::seconds(8));
  2632. stop.store(true, std::memory_order_relaxed);
  2633. for (auto &th : threads) {
  2634. th.join();
  2635. }
  2636. std::this_thread::sleep_for(std::chrono::seconds(3));
  2637. }
  2638. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2639. if (!should_run_issue_2431_tests()) {
  2640. GTEST_SKIP()
  2641. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2642. }
  2643. std::atomic<bool> stop{false};
  2644. std::vector<std::thread> threads;
  2645. for (int t = 0; t < 8; ++t) {
  2646. threads.emplace_back([t, &stop] {
  2647. int i = 0;
  2648. while (!stop.load(std::memory_order_relaxed)) {
  2649. auto host = unique_unresolvable_host(t * 100000 + i++);
  2650. Client cli(host, 80);
  2651. cli.set_connection_timeout(1, 0);
  2652. cli.set_read_timeout(1, 0);
  2653. cli.set_write_timeout(1, 0);
  2654. (void)cli.Get("/");
  2655. }
  2656. });
  2657. }
  2658. std::this_thread::sleep_for(std::chrono::seconds(8));
  2659. stop.store(true, std::memory_order_relaxed);
  2660. for (auto &th : threads) {
  2661. th.join();
  2662. }
  2663. std::this_thread::sleep_for(std::chrono::seconds(3));
  2664. }
  2665. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2666. TEST(ConnectionErrorTest, InvalidHost) {
  2667. auto host = "-abcde.com";
  2668. #ifdef CPPHTTPLIB_SSL_ENABLED
  2669. auto port = 443;
  2670. SSLClient cli(host, port);
  2671. #else
  2672. auto port = 80;
  2673. Client cli(host, port);
  2674. #endif
  2675. cli.set_connection_timeout(std::chrono::seconds(2));
  2676. auto res = cli.Get("/");
  2677. ASSERT_TRUE(!res);
  2678. EXPECT_EQ(Error::Connection, res.error());
  2679. }
  2680. TEST(ConnectionErrorTest, InvalidHost2) {
  2681. auto host = "httpcan.org/";
  2682. #ifdef CPPHTTPLIB_SSL_ENABLED
  2683. SSLClient cli(host);
  2684. #else
  2685. Client cli(host);
  2686. #endif
  2687. cli.set_connection_timeout(std::chrono::seconds(2));
  2688. auto res = cli.Get("/");
  2689. ASSERT_TRUE(!res);
  2690. EXPECT_EQ(Error::Connection, res.error());
  2691. }
  2692. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2693. auto host = "httpcan.org/";
  2694. #ifdef CPPHTTPLIB_SSL_ENABLED
  2695. SSLClient cli(host);
  2696. #else
  2697. Client cli(host);
  2698. #endif
  2699. cli.set_connection_timeout(std::chrono::seconds(2));
  2700. auto res = cli.Get("/");
  2701. ASSERT_TRUE(!res);
  2702. stringstream s;
  2703. s << "error code: " << res.error();
  2704. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2705. }
  2706. TEST(ConnectionErrorTest, InvalidPort) {
  2707. auto host = "localhost";
  2708. auto port = 44380;
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host, port);
  2711. #else
  2712. Client cli(host, port);
  2713. #endif
  2714. cli.set_connection_timeout(std::chrono::seconds(2));
  2715. auto res = cli.Get("/");
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_TRUE(Error::Connection == res.error() ||
  2718. Error::ConnectionTimeout == res.error());
  2719. }
  2720. TEST(ConnectionErrorTest, Timeout_Online) {
  2721. auto host = "google.com";
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. auto port = 44380;
  2724. SSLClient cli(host, port);
  2725. #else
  2726. auto port = 8080;
  2727. Client cli(host, port);
  2728. #endif
  2729. cli.set_connection_timeout(std::chrono::seconds(2));
  2730. // only probe one address type so that the error reason
  2731. // correlates to the timed-out IPv4, not the unsupported
  2732. // IPv6 connection attempt
  2733. cli.set_address_family(AF_INET);
  2734. auto res = cli.Get("/");
  2735. ASSERT_TRUE(!res);
  2736. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2737. }
  2738. TEST(CancelTest, NoCancel_Online) {
  2739. auto host = "httpbingo.org";
  2740. auto path = std::string{"/range/32"};
  2741. #ifdef CPPHTTPLIB_SSL_ENABLED
  2742. auto port = 443;
  2743. SSLClient cli(host, port);
  2744. #else
  2745. auto port = 80;
  2746. Client cli(host, port);
  2747. #endif
  2748. cli.set_connection_timeout(std::chrono::seconds(5));
  2749. auto res = retry_service_failures(
  2750. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2751. SKIP_ON_SERVICE_FAILURE(res);
  2752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2753. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2754. EXPECT_EQ(StatusCode::OK_200, res->status);
  2755. }
  2756. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2757. // Use /bytes with a large payload so that the DownloadProgress callback
  2758. // (which only fires for Content-Length responses) is invoked before the
  2759. // entire body is received, giving cancellation a chance to fire.
  2760. auto host = "httpbingo.org";
  2761. auto path = std::string{"/bytes/524288"};
  2762. #ifdef CPPHTTPLIB_SSL_ENABLED
  2763. auto port = 443;
  2764. SSLClient cli(host, port);
  2765. #else
  2766. auto port = 80;
  2767. Client cli(host, port);
  2768. #endif
  2769. auto res = retry_service_failures(
  2770. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2771. SKIP_ON_SERVICE_FAILURE(res);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, WithCancelLargePayload_Online) {
  2777. auto host = "httpbingo.org";
  2778. auto path = std::string{"/bytes/524288"};
  2779. #ifdef CPPHTTPLIB_SSL_ENABLED
  2780. auto port = 443;
  2781. SSLClient cli(host, port);
  2782. #else
  2783. auto port = 80;
  2784. Client cli(host, port);
  2785. #endif
  2786. cli.set_connection_timeout(std::chrono::seconds(5));
  2787. auto res = retry_service_failures([&] {
  2788. auto count = 0;
  2789. return cli.Get(path,
  2790. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2791. });
  2792. SKIP_ON_SERVICE_FAILURE(res);
  2793. ASSERT_TRUE(!res);
  2794. EXPECT_EQ(Error::Canceled, res.error());
  2795. }
  2796. TEST(CancelTest, NoCancelPost) {
  2797. Server svr;
  2798. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2799. res.set_content("Hello World!", "text/plain");
  2800. });
  2801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2802. auto se = detail::scope_exit([&] {
  2803. svr.stop();
  2804. thread.join();
  2805. ASSERT_FALSE(svr.is_running());
  2806. });
  2807. svr.wait_until_ready();
  2808. Client cli(HOST, PORT);
  2809. cli.set_connection_timeout(std::chrono::seconds(5));
  2810. auto res =
  2811. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2812. "application/json", [](uint64_t, uint64_t) { return true; });
  2813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. EXPECT_EQ(StatusCode::OK_200, res->status);
  2816. }
  2817. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2818. Server svr;
  2819. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2820. res.set_content("Hello World!", "text/plain");
  2821. });
  2822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2823. auto se = detail::scope_exit([&] {
  2824. svr.stop();
  2825. thread.join();
  2826. ASSERT_FALSE(svr.is_running());
  2827. });
  2828. svr.wait_until_ready();
  2829. Client cli(HOST, PORT);
  2830. cli.set_connection_timeout(std::chrono::seconds(5));
  2831. auto res =
  2832. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2833. "application/json", [](uint64_t, uint64_t) { return false; });
  2834. ASSERT_TRUE(!res);
  2835. EXPECT_EQ(Error::Canceled, res.error());
  2836. }
  2837. TEST(CancelTest, WithCancelLargePayloadPost) {
  2838. Server svr;
  2839. svr.set_payload_max_length(200 * 1024 * 1024);
  2840. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2841. res.set_content(LARGE_DATA, "text/plain");
  2842. });
  2843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2844. auto se = detail::scope_exit([&] {
  2845. svr.stop();
  2846. thread.join();
  2847. ASSERT_FALSE(svr.is_running());
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, PORT);
  2851. cli.set_payload_max_length(200 * 1024 * 1024);
  2852. cli.set_connection_timeout(std::chrono::seconds(5));
  2853. auto res =
  2854. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2855. "application/json", [](uint64_t, uint64_t) { return false; });
  2856. ASSERT_TRUE(!res);
  2857. EXPECT_EQ(Error::Canceled, res.error());
  2858. }
  2859. TEST(CancelTest, NoCancelPut) {
  2860. Server svr;
  2861. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2862. res.set_content("Hello World!", "text/plain");
  2863. });
  2864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2865. auto se = detail::scope_exit([&] {
  2866. svr.stop();
  2867. thread.join();
  2868. ASSERT_FALSE(svr.is_running());
  2869. });
  2870. svr.wait_until_ready();
  2871. Client cli(HOST, PORT);
  2872. cli.set_connection_timeout(std::chrono::seconds(5));
  2873. auto res =
  2874. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2875. "application/json", [](uint64_t, uint64_t) { return true; });
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ("Hello World!", res->body);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2881. Server svr;
  2882. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2883. res.set_content("Hello World!", "text/plain");
  2884. });
  2885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2886. auto se = detail::scope_exit([&] {
  2887. svr.stop();
  2888. thread.join();
  2889. ASSERT_FALSE(svr.is_running());
  2890. });
  2891. svr.wait_until_ready();
  2892. Client cli(HOST, PORT);
  2893. cli.set_connection_timeout(std::chrono::seconds(5));
  2894. auto res =
  2895. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2896. "application/json", [](uint64_t, uint64_t) { return false; });
  2897. ASSERT_TRUE(!res);
  2898. EXPECT_EQ(Error::Canceled, res.error());
  2899. }
  2900. TEST(CancelTest, WithCancelLargePayloadPut) {
  2901. Server svr;
  2902. svr.set_payload_max_length(200 * 1024 * 1024);
  2903. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2904. res.set_content(LARGE_DATA, "text/plain");
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. Client cli(HOST, PORT);
  2914. cli.set_payload_max_length(200 * 1024 * 1024);
  2915. cli.set_connection_timeout(std::chrono::seconds(5));
  2916. auto res =
  2917. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2918. "application/json", [](uint64_t, uint64_t) { return false; });
  2919. ASSERT_TRUE(!res);
  2920. EXPECT_EQ(Error::Canceled, res.error());
  2921. }
  2922. TEST(CancelTest, NoCancelPatch) {
  2923. Server svr;
  2924. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("Hello World!", "text/plain");
  2926. });
  2927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2928. auto se = detail::scope_exit([&] {
  2929. svr.stop();
  2930. thread.join();
  2931. ASSERT_FALSE(svr.is_running());
  2932. });
  2933. svr.wait_until_ready();
  2934. Client cli(HOST, PORT);
  2935. cli.set_connection_timeout(std::chrono::seconds(5));
  2936. auto res =
  2937. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2938. "application/json", [](uint64_t, uint64_t) { return true; });
  2939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2940. EXPECT_EQ("Hello World!", res->body);
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2944. Server svr;
  2945. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2946. res.set_content("Hello World!", "text/plain");
  2947. });
  2948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2949. auto se = detail::scope_exit([&] {
  2950. svr.stop();
  2951. thread.join();
  2952. ASSERT_FALSE(svr.is_running());
  2953. });
  2954. svr.wait_until_ready();
  2955. Client cli(HOST, PORT);
  2956. cli.set_connection_timeout(std::chrono::seconds(5));
  2957. auto res =
  2958. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2959. "application/json", [](uint64_t, uint64_t) { return false; });
  2960. ASSERT_TRUE(!res);
  2961. EXPECT_EQ(Error::Canceled, res.error());
  2962. }
  2963. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2964. Server svr;
  2965. svr.set_payload_max_length(200 * 1024 * 1024);
  2966. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2967. res.set_content(LARGE_DATA, "text/plain");
  2968. });
  2969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2970. auto se = detail::scope_exit([&] {
  2971. svr.stop();
  2972. thread.join();
  2973. ASSERT_FALSE(svr.is_running());
  2974. });
  2975. svr.wait_until_ready();
  2976. Client cli(HOST, PORT);
  2977. cli.set_payload_max_length(200 * 1024 * 1024);
  2978. cli.set_connection_timeout(std::chrono::seconds(5));
  2979. auto res =
  2980. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2981. "application/json", [](uint64_t, uint64_t) { return false; });
  2982. ASSERT_TRUE(!res);
  2983. EXPECT_EQ(Error::Canceled, res.error());
  2984. }
  2985. TEST(CancelTest, NoCancelDelete) {
  2986. Server svr;
  2987. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2988. res.set_content("Hello World!", "text/plain");
  2989. });
  2990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. thread.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. Client cli(HOST, PORT);
  2998. cli.set_connection_timeout(std::chrono::seconds(5));
  2999. auto res =
  3000. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3001. "application/json", [](uint64_t, uint64_t) { return true; });
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("Hello World!", res->body);
  3004. EXPECT_EQ(StatusCode::OK_200, res->status);
  3005. }
  3006. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  3007. Server svr;
  3008. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3009. res.set_content("Hello World!", "text/plain");
  3010. });
  3011. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3012. auto se = detail::scope_exit([&] {
  3013. svr.stop();
  3014. thread.join();
  3015. ASSERT_FALSE(svr.is_running());
  3016. });
  3017. svr.wait_until_ready();
  3018. Client cli(HOST, PORT);
  3019. cli.set_connection_timeout(std::chrono::seconds(5));
  3020. auto res =
  3021. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3022. "application/json", [](uint64_t, uint64_t) { return false; });
  3023. ASSERT_TRUE(!res);
  3024. EXPECT_EQ(Error::Canceled, res.error());
  3025. }
  3026. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3027. Server svr;
  3028. svr.set_payload_max_length(200 * 1024 * 1024);
  3029. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3030. res.set_content(LARGE_DATA, "text/plain");
  3031. });
  3032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. thread.join();
  3036. ASSERT_FALSE(svr.is_running());
  3037. });
  3038. svr.wait_until_ready();
  3039. Client cli(HOST, PORT);
  3040. cli.set_payload_max_length(200 * 1024 * 1024);
  3041. cli.set_connection_timeout(std::chrono::seconds(5));
  3042. auto res =
  3043. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3044. "application/json", [](uint64_t, uint64_t) { return false; });
  3045. ASSERT_TRUE(!res);
  3046. EXPECT_EQ(Error::Canceled, res.error());
  3047. }
  3048. // One stop() from another thread ends a request that waits for the response
  3049. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3050. Server svr;
  3051. std::atomic<bool> received{false};
  3052. std::atomic<bool> done{false};
  3053. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3054. received.store(true);
  3055. while (!done.load()) {
  3056. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3057. }
  3058. res.set_content("Hello World!", "text/plain");
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3062. Client cli(HOST, port);
  3063. cli.set_read_timeout(std::chrono::seconds(30));
  3064. std::future<Result> request;
  3065. auto se = detail::scope_exit([&] {
  3066. done.store(true);
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3073. for (int i = 0; i < 500 && !received.load(); ++i) {
  3074. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3075. }
  3076. ASSERT_TRUE(received.load());
  3077. // Let the client block in the wait for the response
  3078. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3079. auto start = std::chrono::steady_clock::now();
  3080. cli.stop();
  3081. ASSERT_EQ(std::future_status::ready,
  3082. request.wait_for(std::chrono::seconds(5)));
  3083. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3084. auto res = request.get();
  3085. ASSERT_TRUE(!res);
  3086. EXPECT_EQ(Error::Read, res.error());
  3087. }
  3088. // A listener whose backlog completes the TCP connections of clients, and that
  3089. // never answers them
  3090. struct SilentListener {
  3091. socket_t sock = INVALID_SOCKET;
  3092. sockaddr_in addr{};
  3093. int port = 0;
  3094. explicit SilentListener(int backlog = 1) {
  3095. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3096. addr.sin_family = AF_INET;
  3097. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3098. socklen_t len = sizeof(addr);
  3099. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3100. ::listen(sock, backlog) != 0 ||
  3101. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3102. detail::close_socket(sock);
  3103. sock = INVALID_SOCKET;
  3104. }
  3105. port = ntohs(addr.sin_port);
  3106. }
  3107. ~SilentListener() { detail::close_socket(sock); }
  3108. // The next connection, whose reads give up after 5 seconds
  3109. socket_t accept() const {
  3110. auto peer = ::accept(sock, nullptr, nullptr);
  3111. if (peer != INVALID_SOCKET) {
  3112. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3113. }
  3114. return peer;
  3115. }
  3116. };
  3117. static bool receives_a_byte(socket_t peer) {
  3118. char c = 0;
  3119. return detail::read_socket(peer, &c, 1, 0) == 1;
  3120. }
  3121. // Runs op, stops cli once the listener receives the first byte op sends, and
  3122. // expects op to end with error soon after
  3123. template <typename ClientType, typename Op>
  3124. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3125. Op op, Error error = Error::Canceled) {
  3126. auto ended = std::async(std::launch::async, op);
  3127. auto peer = listener.accept();
  3128. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3129. ASSERT_NE(INVALID_SOCKET, peer);
  3130. ASSERT_TRUE(receives_a_byte(peer));
  3131. cli.stop();
  3132. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3133. EXPECT_EQ(error, ended.get());
  3134. }
  3135. // Stops itself from another thread as the connection opens, the last moment a
  3136. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3137. // waits for the connection fails the test instead of hanging it.
  3138. class StoppedAsConnectedClient : public ClientImpl {
  3139. public:
  3140. using ClientImpl::ClientImpl;
  3141. protected:
  3142. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3143. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3144. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3145. stopper_.wait_for(std::chrono::seconds(1));
  3146. return true;
  3147. }
  3148. private:
  3149. std::future<void> stopper_;
  3150. };
  3151. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3152. SilentListener listener;
  3153. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3154. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3155. cli.set_read_timeout(std::chrono::seconds(3));
  3156. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3157. auto peer = listener.accept();
  3158. EXPECT_FALSE(receives_a_byte(peer));
  3159. detail::close_socket(peer);
  3160. auto handle = cli.open_stream("GET", "/");
  3161. EXPECT_FALSE(handle.is_valid());
  3162. EXPECT_EQ(Error::Canceled, handle.error);
  3163. peer = listener.accept();
  3164. EXPECT_FALSE(receives_a_byte(peer));
  3165. detail::close_socket(peer);
  3166. }
  3167. #ifdef __linux__
  3168. // A connect that a listener with a full backlog never completes
  3169. TEST(ClientStopTest, StopEndsAConnect) {
  3170. SilentListener listener(0);
  3171. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3172. std::vector<socket_t> backlog;
  3173. auto close_backlog = detail::scope_exit([&] {
  3174. for (auto sock : backlog) {
  3175. detail::close_socket(sock);
  3176. }
  3177. });
  3178. for (int i = 0; i < 8; i++) {
  3179. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3180. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3181. sizeof(listener.addr));
  3182. backlog.push_back(sock);
  3183. }
  3184. Client cli("127.0.0.1", listener.port);
  3185. cli.set_connection_timeout(std::chrono::seconds(3));
  3186. auto ended =
  3187. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3188. // A stop() before the request starts does not apply to it, so it repeats
  3189. auto status = std::future_status::timeout;
  3190. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3191. cli.stop();
  3192. status = ended.wait_for(std::chrono::milliseconds(10));
  3193. }
  3194. EXPECT_EQ(std::future_status::ready, status);
  3195. EXPECT_EQ(Error::Canceled, ended.get());
  3196. }
  3197. #endif
  3198. // The stream holds the socket while it waits for the head, out of the reach
  3199. // of shutdown()
  3200. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3201. SilentListener listener;
  3202. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3203. Client cli("127.0.0.1", listener.port);
  3204. cli.set_read_timeout(std::chrono::seconds(3));
  3205. expect_stop_ends(
  3206. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3207. Error::Read);
  3208. }
  3209. #ifdef CPPHTTPLIB_SSL_ENABLED
  3210. // A server that never answers the ClientHello
  3211. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3212. SilentListener listener;
  3213. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3214. SSLClient cli("127.0.0.1", listener.port);
  3215. cli.enable_server_certificate_verification(false);
  3216. cli.set_connection_timeout(std::chrono::seconds(3));
  3217. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3218. expect_stop_ends(cli, listener,
  3219. [&] { return cli.open_stream("GET", "/").error; });
  3220. }
  3221. // A proxy that takes the CONNECT and never answers it
  3222. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3223. SilentListener listener;
  3224. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3225. SSLClient cli("example.com", 443);
  3226. cli.set_proxy("127.0.0.1", listener.port);
  3227. cli.set_read_timeout(std::chrono::seconds(3));
  3228. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3229. }
  3230. #endif
  3231. // A read timeout past what the clock reaches waits for the response
  3232. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3233. SilentListener listener;
  3234. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3235. Client cli("127.0.0.1", listener.port);
  3236. cli.set_read_timeout(
  3237. static_cast<time_t>((std::min)(static_cast<long long>(
  3238. (std::numeric_limits<time_t>::max)()),
  3239. 10000000000LL)),
  3240. 0);
  3241. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3242. auto peer = listener.accept();
  3243. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3244. ASSERT_NE(INVALID_SOCKET, peer);
  3245. ASSERT_TRUE(receives_a_byte(peer));
  3246. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3247. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3248. "Connection: close\r\n\r\nok";
  3249. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3250. auto result = res.get();
  3251. ASSERT_TRUE(result);
  3252. EXPECT_EQ("ok", result->body);
  3253. }
  3254. static std::string remove_whitespace(const std::string &input) {
  3255. std::string output;
  3256. output.reserve(input.size());
  3257. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3258. [](unsigned char c) { return !std::isspace(c); });
  3259. return output;
  3260. }
  3261. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3262. auto host = "httpbingo.org";
  3263. auto path = std::string{"/basic-auth/hello/world"};
  3264. #ifdef CPPHTTPLIB_SSL_ENABLED
  3265. auto port = 443;
  3266. SSLClient cli(host, port);
  3267. #else
  3268. auto port = 80;
  3269. Client cli(host, port);
  3270. #endif
  3271. {
  3272. auto res = retry_service_failures([&] { return cli.Get(path); });
  3273. SKIP_ON_SERVICE_FAILURE(res);
  3274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3275. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3276. }
  3277. {
  3278. auto res = retry_service_failures([&] {
  3279. return cli.Get(
  3280. path, Headers{make_basic_authentication_header("hello", "world")});
  3281. });
  3282. SKIP_ON_SERVICE_FAILURE(res);
  3283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3284. auto body = remove_whitespace(res->body);
  3285. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3286. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. {
  3290. cli.set_basic_auth("hello", "world");
  3291. auto res = retry_service_failures([&] { return cli.Get(path); });
  3292. SKIP_ON_SERVICE_FAILURE(res);
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. auto body = remove_whitespace(res->body);
  3295. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3296. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3297. EXPECT_EQ(StatusCode::OK_200, res->status);
  3298. }
  3299. {
  3300. cli.set_basic_auth("hello", "bad");
  3301. auto res = retry_service_failures([&] { return cli.Get(path); });
  3302. SKIP_ON_SERVICE_FAILURE(res);
  3303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3304. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3305. }
  3306. {
  3307. cli.set_basic_auth("bad", "world");
  3308. auto res = retry_service_failures([&] { return cli.Get(path); });
  3309. SKIP_ON_SERVICE_FAILURE(res);
  3310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3311. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3312. }
  3313. }
  3314. #ifdef CPPHTTPLIB_SSL_ENABLED
  3315. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3316. auto host = "httpbingo.org";
  3317. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3318. auto paths = std::vector<std::string>{
  3319. "/digest-auth/auth/hello/world/MD5",
  3320. "/digest-auth/auth/hello/world/SHA-256",
  3321. };
  3322. auto port = 443;
  3323. SSLClient cli(host, port);
  3324. {
  3325. auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
  3326. SKIP_ON_SERVICE_FAILURE(res);
  3327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3328. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3329. }
  3330. {
  3331. cli.set_digest_auth("hello", "world");
  3332. for (const auto &path : paths) {
  3333. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3334. SKIP_ON_SERVICE_FAILURE(res);
  3335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3336. auto body = remove_whitespace(res->body);
  3337. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3338. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3339. EXPECT_EQ(StatusCode::OK_200, res->status);
  3340. }
  3341. cli.set_digest_auth("hello", "bad");
  3342. for (const auto &path : paths) {
  3343. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3344. SKIP_ON_SERVICE_FAILURE(res);
  3345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3346. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3347. }
  3348. }
  3349. }
  3350. // Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
  3351. // field lines (get_combined_header_value() joins them in receipt order) and
  3352. // returns the Authorization header of the retry.
  3353. static std::string
  3354. get_digest_retry_authorization(const std::vector<std::string> &challenges) {
  3355. std::atomic<int> hits{0};
  3356. std::string authorization;
  3357. Server svr;
  3358. svr.Get("/x", [&](const Request &req, Response &res) {
  3359. if (++hits == 1) {
  3360. res.status = StatusCode::Unauthorized_401;
  3361. for (const auto &challenge : challenges) {
  3362. res.set_header("WWW-Authenticate", challenge);
  3363. }
  3364. } else {
  3365. authorization = req.get_header_value("Authorization");
  3366. res.set_content("ok", "text/plain");
  3367. }
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. std::thread t([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. t.join();
  3374. });
  3375. svr.wait_until_ready();
  3376. Client cli(HOST, port);
  3377. cli.set_digest_auth("hello", "world");
  3378. auto res = cli.Get("/x");
  3379. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ(2, hits.load());
  3381. return authorization;
  3382. }
  3383. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3384. // comma-separated list of challenges, and each challenge may itself carry a
  3385. // comma-separated auth-param list, so a server can legally offer Basic
  3386. // before Digest, either as two field lines or packed into one. Checks that
  3387. // the retry carries a well-formed Digest Authorization header naming
  3388. // expected_realm.
  3389. static void
  3390. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3391. const std::string &expected_realm) {
  3392. auto authorization = get_digest_retry_authorization(challenges);
  3393. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3394. EXPECT_NE(std::string::npos,
  3395. authorization.find("realm=\"" + expected_realm + "\""));
  3396. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3397. }
  3398. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3399. static const char *kDigestChallenge =
  3400. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3401. "algorithm=MD5";
  3402. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3403. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3404. "testrealm");
  3405. }
  3406. // Same challenge list with the schemes in the opposite order, to make sure
  3407. // the fix above didn't just special-case "Basic first".
  3408. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3409. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3410. "testrealm");
  3411. }
  3412. // A comma inside a quoted auth-param value must not be mistaken for the
  3413. // separator between two challenges (or two auth-params).
  3414. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3415. run_digest_challenge_list_test(
  3416. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3417. "algorithm=MD5"},
  3418. "test,realm");
  3419. }
  3420. // RFC 9110 11.6.1: 1*SP separates the scheme from its first auth-param.
  3421. TEST(DigestAuthTest, SeveralSpacesAfterScheme) {
  3422. auto authorization =
  3423. get_digest_retry_authorization({"Digest realm=\"r\", nonce=\"n\""});
  3424. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n\""));
  3425. }
  3426. // RFC 9110 11.2: auth-param names are matched case-insensitively.
  3427. TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
  3428. auto authorization = get_digest_retry_authorization(
  3429. {"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
  3430. "Algorithm=SHA-256, OPAQUE=\"op\""});
  3431. EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
  3432. EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
  3433. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3434. EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
  3435. EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
  3436. }
  3437. // The algorithm is matched case-insensitively and sent back as the server
  3438. // wrote it (RFC 7616 3.4).
  3439. TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
  3440. auto authorization = get_digest_retry_authorization(
  3441. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
  3442. EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
  3443. const std::string prefix = "response=\"";
  3444. auto b = authorization.find(prefix);
  3445. ASSERT_NE(std::string::npos, b);
  3446. b += prefix.size();
  3447. EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
  3448. }
  3449. // qop options are matched case-insensitively.
  3450. TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
  3451. auto authorization = get_digest_retry_authorization(
  3452. {"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
  3453. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3454. }
  3455. // auth-int hashes req.body, which is empty when a content provider streams the
  3456. // body, so it is chosen only when the server offers no auth.
  3457. TEST(DigestAuthTest, PrefersQopAuthOverAuthInt) {
  3458. auto authorization = get_digest_retry_authorization(
  3459. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth-int, auth\""});
  3460. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3461. authorization = get_digest_retry_authorization(
  3462. {"Digest realm=\"r\", nonce=\"n\", qop=\"Auth-Int\""});
  3463. EXPECT_NE(std::string::npos, authorization.find("qop=auth-int,"));
  3464. }
  3465. // RFC 7616 3.7: the client uses the first Digest challenge it can answer.
  3466. TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
  3467. auto authorization = get_digest_retry_authorization(
  3468. {"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
  3469. "Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
  3470. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3471. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3472. authorization = get_digest_retry_authorization(
  3473. {"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
  3474. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3475. }
  3476. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3477. // the params and leaves out the fragment.
  3478. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3479. Server svr;
  3480. std::string uri, target;
  3481. svr.Get("/a b", [&](const Request &req, Response &res) {
  3482. auto auth = req.get_header_value("Authorization");
  3483. if (auth.empty()) {
  3484. res.status = StatusCode::Unauthorized_401;
  3485. res.set_header("WWW-Authenticate",
  3486. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3487. return;
  3488. }
  3489. auto b = auth.find("uri=\"") + 5;
  3490. uri = auth.substr(b, auth.find('"', b) - b);
  3491. target = req.target;
  3492. });
  3493. auto port = svr.bind_to_any_port(HOST);
  3494. std::thread t([&]() { svr.listen_after_bind(); });
  3495. auto se = detail::scope_exit([&] {
  3496. svr.stop();
  3497. t.join();
  3498. });
  3499. svr.wait_until_ready();
  3500. Client cli(HOST, port);
  3501. cli.set_digest_auth("hello", "world");
  3502. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3504. EXPECT_EQ("/a%20b?x=1", target);
  3505. EXPECT_EQ(target, uri);
  3506. }
  3507. // A Digest challenge the client can't answer (realm or nonce missing, or no
  3508. // algorithm or qop option it implements) must leave the 401 as it is, without
  3509. // a retry.
  3510. static void
  3511. run_unanswerable_digest_challenge_test(const std::string &challenge) {
  3512. std::atomic<int> hits{0};
  3513. Server svr;
  3514. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3515. ++hits;
  3516. res.status = StatusCode::Unauthorized_401;
  3517. res.set_header("WWW-Authenticate", challenge);
  3518. });
  3519. auto port = svr.bind_to_any_port(HOST);
  3520. std::thread t([&]() { svr.listen_after_bind(); });
  3521. auto se = detail::scope_exit([&] {
  3522. svr.stop();
  3523. t.join();
  3524. });
  3525. svr.wait_until_ready();
  3526. Client cli(HOST, port);
  3527. cli.set_digest_auth("hello", "world");
  3528. auto res = cli.Get("/x");
  3529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3531. EXPECT_EQ(1, hits.load());
  3532. }
  3533. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3534. run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
  3535. }
  3536. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3537. run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
  3538. }
  3539. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3540. run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
  3541. }
  3542. // RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
  3543. // ignored. The last value isn't a token and would otherwise inject auth-params
  3544. // into the Authorization header.
  3545. TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
  3546. for (auto algorithm :
  3547. {"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
  3548. SCOPED_TRACE(algorithm);
  3549. run_unanswerable_digest_challenge_test(
  3550. std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
  3551. "algorithm=") +
  3552. algorithm);
  3553. }
  3554. }
  3555. // RFC 7616 3.3: qop options the client doesn't implement are ignored, and a
  3556. // challenge that offers no other can't be answered.
  3557. TEST(DigestAuthTest, UnsupportedQopIsIgnored) {
  3558. run_unanswerable_digest_challenge_test(
  3559. "Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\"");
  3560. }
  3561. // A hostile server can put a '"' in realm/nonce/opaque in its challenge.
  3562. // parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
  3563. // the header builder has to re-escape them; otherwise the value breaks out of
  3564. // its quoted-string and injects extra auth-params into the Authorization.
  3565. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3566. // On the wire the quotes embedded in the value are backslash-escaped.
  3567. auto authorization = get_digest_retry_authorization(
  3568. {"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
  3569. "qop=\"auth\""});
  3570. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3571. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3572. // inside its quoted-string rather than starting an "injected" auth-param.
  3573. EXPECT_NE(std::string::npos,
  3574. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3575. }
  3576. #endif
  3577. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3578. auto host = "google.com";
  3579. auto another_host = "example.com";
  3580. auto wrong_ip = "0.0.0.0";
  3581. #ifdef CPPHTTPLIB_SSL_ENABLED
  3582. SSLClient cli(host);
  3583. #else
  3584. Client cli(host);
  3585. #endif
  3586. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3587. auto res = cli.Get("/");
  3588. // Any status: Google may redirect or rate-limit CI runners.
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. }
  3591. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3592. auto host = "google.com";
  3593. auto wrong_ip = "0.0.0.0";
  3594. #ifdef CPPHTTPLIB_SSL_ENABLED
  3595. SSLClient cli(host);
  3596. #else
  3597. Client cli(host);
  3598. #endif
  3599. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3600. auto res = cli.Get("/");
  3601. ASSERT_TRUE(!res);
  3602. EXPECT_EQ(Error::Connection, res.error());
  3603. }
  3604. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3605. // A mapped value that is not an IP literal must be resolved. "localhost"
  3606. // resolves from the hosts file, so this test needs no external DNS.
  3607. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3608. auto host = "target.invalid";
  3609. Server svr;
  3610. std::string received_host;
  3611. svr.Get("/hi", [&](const Request &req, Response &res) {
  3612. received_host = req.get_header_value("Host");
  3613. res.set_content("Hello World!", "text/plain");
  3614. });
  3615. auto port = svr.bind_to_any_port(HOST);
  3616. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3617. auto se = detail::scope_exit([&] {
  3618. svr.stop();
  3619. thread.join();
  3620. ASSERT_FALSE(svr.is_running());
  3621. });
  3622. svr.wait_until_ready();
  3623. Client cli(host, port);
  3624. cli.set_direct_hostname_addr_map({{host, HOST}});
  3625. auto res = cli.Get("/hi");
  3626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3627. EXPECT_EQ(StatusCode::OK_200, res->status);
  3628. // The mapping only redirects the connection; the identity stays host_.
  3629. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3630. }
  3631. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3632. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3633. auto host = "target.invalid";
  3634. Server svr;
  3635. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3636. res.set_content("Hello World!", "text/plain");
  3637. });
  3638. auto port = svr.bind_to_any_port("127.0.0.1");
  3639. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3640. auto se = detail::scope_exit([&] {
  3641. svr.stop();
  3642. thread.join();
  3643. ASSERT_FALSE(svr.is_running());
  3644. });
  3645. svr.wait_until_ready();
  3646. Client cli(host, port);
  3647. cli.set_direct_hostname_addr_map({{host, "127.0.0.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(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3653. // An empty mapped value must leave host_ as the connection target. Without
  3654. // that guard the empty value would become the host argument, getaddrinfo
  3655. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3656. // loopback - silently connecting somewhere the caller never asked for.
  3657. // The server listens on loopback, so such a fallback would succeed and is
  3658. // therefore observable as a failure of this test.
  3659. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3660. Server svr;
  3661. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3662. res.set_content("Hello World!", "text/plain");
  3663. });
  3664. auto port = svr.bind_to_any_port(HOST);
  3665. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3666. auto se = detail::scope_exit([&] {
  3667. svr.stop();
  3668. thread.join();
  3669. ASSERT_FALSE(svr.is_running());
  3670. });
  3671. svr.wait_until_ready();
  3672. Client cli(blackhole, port);
  3673. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3674. cli.set_connection_timeout(1);
  3675. auto res = cli.Get("/hi");
  3676. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3677. }
  3678. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3679. auto host = "target.invalid";
  3680. Server svr;
  3681. std::string received_host;
  3682. svr.Get("/hi", [&](const Request &req, Response &res) {
  3683. received_host = req.get_header_value("Host");
  3684. res.set_content("Hello World!", "text/plain");
  3685. });
  3686. auto port = svr.bind_to_any_port("127.0.0.1");
  3687. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3688. auto se = detail::scope_exit([&] {
  3689. svr.stop();
  3690. thread.join();
  3691. ASSERT_FALSE(svr.is_running());
  3692. });
  3693. svr.wait_until_ready();
  3694. Client cli(host, port);
  3695. #pragma GCC diagnostic push
  3696. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3697. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3698. #pragma GCC diagnostic pop
  3699. auto res = cli.Get("/hi");
  3700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3701. EXPECT_EQ(StatusCode::OK_200, res->status);
  3702. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3703. }
  3704. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3705. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3706. Server svr;
  3707. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3708. res.set_content("Hello World!", "text/plain");
  3709. });
  3710. auto port = svr.bind_to_any_port("127.0.0.1");
  3711. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3712. auto se = detail::scope_exit([&] {
  3713. svr.stop();
  3714. thread.join();
  3715. ASSERT_FALSE(svr.is_running());
  3716. });
  3717. svr.wait_until_ready();
  3718. Client cli("127.0.0.1", port);
  3719. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3720. cli.set_connection_timeout(1);
  3721. auto res = cli.Get("/hi");
  3722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3723. EXPECT_EQ(StatusCode::OK_200, res->status);
  3724. }
  3725. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3726. auto host = "httpbingo.org";
  3727. auto path = std::string{"/absolute-redirect/3"};
  3728. #ifdef CPPHTTPLIB_SSL_ENABLED
  3729. SSLClient cli(host);
  3730. #else
  3731. Client cli(host);
  3732. #endif
  3733. cli.set_follow_location(true);
  3734. auto res = retry_service_failures([&] { return cli.Get(path); });
  3735. SKIP_ON_SERVICE_FAILURE(res);
  3736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. }
  3739. TEST(RedirectTest, Redirect_Online) {
  3740. auto host = "httpbingo.org";
  3741. auto path = std::string{"/redirect/3"};
  3742. #ifdef CPPHTTPLIB_SSL_ENABLED
  3743. SSLClient cli(host);
  3744. #else
  3745. Client cli(host);
  3746. #endif
  3747. cli.set_follow_location(true);
  3748. auto res = retry_service_failures([&] { return cli.Get(path); });
  3749. SKIP_ON_SERVICE_FAILURE(res);
  3750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. }
  3753. TEST(RelativeRedirectTest, Redirect_Online) {
  3754. auto host = "httpbingo.org";
  3755. auto path = std::string{"/relative-redirect/3"};
  3756. #ifdef CPPHTTPLIB_SSL_ENABLED
  3757. SSLClient cli(host);
  3758. #else
  3759. Client cli(host);
  3760. #endif
  3761. cli.set_follow_location(true);
  3762. auto res = retry_service_failures([&] { return cli.Get(path); });
  3763. SKIP_ON_SERVICE_FAILURE(res);
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::OK_200, res->status);
  3766. }
  3767. TEST(TooManyRedirectTest, Redirect_Online) {
  3768. auto host = "httpbingo.org";
  3769. auto path = std::string{"/redirect/21"};
  3770. #ifdef CPPHTTPLIB_SSL_ENABLED
  3771. SSLClient cli(host);
  3772. #else
  3773. Client cli(host);
  3774. #endif
  3775. cli.set_follow_location(true);
  3776. auto res = retry_service_failures([&] { return cli.Get(path); });
  3777. SKIP_ON_SERVICE_FAILURE(res);
  3778. ASSERT_TRUE(!res);
  3779. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3780. }
  3781. #ifdef CPPHTTPLIB_SSL_ENABLED
  3782. TEST(YahooRedirectTest, Redirect_Online) {
  3783. Client cli("yahoo.com");
  3784. auto res = cli.Get("/");
  3785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3786. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3787. cli.set_follow_location(true);
  3788. res = cli.Get("/");
  3789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3792. }
  3793. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3794. #define REDIR_HOST "httpbingo.org"
  3795. #define REDIR_PATH "/redirect-to"
  3796. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3797. SSLClient cli(REDIR_HOST);
  3798. cli.set_follow_location(true);
  3799. auto res = retry_service_failures([&] {
  3800. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3801. });
  3802. SKIP_ON_SERVICE_FAILURE(res);
  3803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3804. EXPECT_EQ(StatusCode::OK_200, res->status);
  3805. }
  3806. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3807. SSLClient cli(REDIR_HOST);
  3808. cli.set_follow_location(true);
  3809. Params params;
  3810. params.emplace("url", "http://example.com");
  3811. params.emplace("status_code", "302");
  3812. auto res = retry_service_failures(
  3813. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3814. SKIP_ON_SERVICE_FAILURE(res);
  3815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3816. EXPECT_EQ(StatusCode::OK_200, res->status);
  3817. }
  3818. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3819. SSLClient cli(REDIR_HOST);
  3820. cli.set_follow_location(true);
  3821. Params params;
  3822. params.emplace("url", "http://example.com");
  3823. auto res = retry_service_failures([&] {
  3824. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3825. });
  3826. SKIP_ON_SERVICE_FAILURE(res);
  3827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3828. EXPECT_EQ(StatusCode::OK_200, res->status);
  3829. }
  3830. TEST(UrlWithSpace, Redirect_Online) {
  3831. SSLClient cli("edge.forgecdn.net");
  3832. cli.set_follow_location(true);
  3833. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3837. }
  3838. #endif
  3839. #if !defined(_WIN32) && !defined(_WIN64)
  3840. TEST(ReceiveSignals, Signal) {
  3841. auto setupSignalHandlers = []() {
  3842. struct sigaction act;
  3843. sigemptyset(&act.sa_mask);
  3844. act.sa_flags = SA_SIGINFO;
  3845. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3846. switch (sig) {
  3847. case SIGINT:
  3848. default: break;
  3849. }
  3850. };
  3851. ::sigaction(SIGINT, &act, nullptr);
  3852. };
  3853. Server svr;
  3854. int port = 0;
  3855. auto thread = std::thread([&]() {
  3856. setupSignalHandlers();
  3857. port = svr.bind_to_any_port(HOST);
  3858. svr.listen_after_bind();
  3859. });
  3860. auto se = detail::scope_exit([&] {
  3861. svr.stop();
  3862. thread.join();
  3863. ASSERT_FALSE(svr.is_running());
  3864. });
  3865. svr.wait_until_ready();
  3866. ASSERT_TRUE(svr.is_running());
  3867. pthread_kill(thread.native_handle(), SIGINT);
  3868. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3869. ASSERT_TRUE(svr.is_running());
  3870. }
  3871. #endif
  3872. TEST(RedirectToDifferentPort, Redirect) {
  3873. Server svr1;
  3874. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3875. res.set_content("Hello World!", "text/plain");
  3876. });
  3877. int svr1_port = 0;
  3878. auto thread1 = std::thread([&]() {
  3879. svr1_port = svr1.bind_to_any_port(HOST);
  3880. svr1.listen_after_bind();
  3881. });
  3882. Server svr2;
  3883. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3884. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3885. });
  3886. int svr2_port = 0;
  3887. auto thread2 = std::thread([&]() {
  3888. svr2_port = svr2.bind_to_any_port(HOST);
  3889. svr2.listen_after_bind();
  3890. });
  3891. auto se = detail::scope_exit([&] {
  3892. svr2.stop();
  3893. thread2.join();
  3894. svr1.stop();
  3895. thread1.join();
  3896. ASSERT_FALSE(svr2.is_running());
  3897. ASSERT_FALSE(svr1.is_running());
  3898. });
  3899. svr1.wait_until_ready();
  3900. svr2.wait_until_ready();
  3901. Client cli("localhost", svr2_port);
  3902. cli.set_follow_location(true);
  3903. auto res = cli.Get("/2");
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ(StatusCode::OK_200, res->status);
  3906. EXPECT_EQ("Hello World!", res->body);
  3907. }
  3908. // GET /redir on one server redirects to /target on another port, so the
  3909. // client follows it with a new client.
  3910. static Result
  3911. GetThroughRedirectToDifferentPort(Server::Handler target,
  3912. const std::function<void(Client &)> &setup,
  3913. const Headers &headers = Headers()) {
  3914. Server target_svr;
  3915. target_svr.Get("/target", target);
  3916. int target_port = 0;
  3917. auto target_thread = std::thread([&]() {
  3918. target_port = target_svr.bind_to_any_port(HOST);
  3919. target_svr.listen_after_bind();
  3920. });
  3921. Server origin_svr;
  3922. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3923. res.set_redirect(
  3924. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3925. });
  3926. int origin_port = 0;
  3927. auto origin_thread = std::thread([&]() {
  3928. origin_port = origin_svr.bind_to_any_port(HOST);
  3929. origin_svr.listen_after_bind();
  3930. });
  3931. auto se = detail::scope_exit([&] {
  3932. origin_svr.stop();
  3933. origin_thread.join();
  3934. target_svr.stop();
  3935. target_thread.join();
  3936. });
  3937. target_svr.wait_until_ready();
  3938. origin_svr.wait_until_ready();
  3939. Client cli("localhost", origin_port);
  3940. cli.set_follow_location(true);
  3941. setup(cli);
  3942. return cli.Get("/redir", headers);
  3943. }
  3944. static void
  3945. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3946. std::string captured_authorization;
  3947. auto result = GetThroughRedirectToDifferentPort(
  3948. [&](const Request &req, Response &res) {
  3949. captured_authorization = req.get_header_value("Authorization");
  3950. res.set_content("OK", "text/plain");
  3951. },
  3952. set_auth);
  3953. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3954. EXPECT_EQ(StatusCode::OK_200, result->status);
  3955. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3956. EXPECT_TRUE(captured_authorization.empty());
  3957. }
  3958. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3959. TestDoNotForwardCredentialsOnRedirect(
  3960. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3961. }
  3962. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3963. TestDoNotForwardCredentialsOnRedirect(
  3964. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3965. }
  3966. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3967. std::string captured_cookie;
  3968. auto result = GetThroughRedirectToDifferentPort(
  3969. [&](const Request &req, Response &res) {
  3970. captured_cookie = req.get_header_value("Cookie");
  3971. res.set_content("OK", "text/plain");
  3972. },
  3973. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3974. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3975. EXPECT_EQ(StatusCode::OK_200, result->status);
  3976. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3977. EXPECT_TRUE(captured_cookie.empty());
  3978. }
  3979. TEST(RedirectToSamePort, ForwardCookie) {
  3980. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3981. // header so that ordinary session flows keep working.
  3982. Server svr;
  3983. std::string captured_cookie;
  3984. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3985. res.set_redirect("/target", 302);
  3986. });
  3987. svr.Get("/target", [&](const Request &req, Response &res) {
  3988. captured_cookie = req.get_header_value("Cookie");
  3989. res.set_content("OK", "text/plain");
  3990. });
  3991. auto port = svr.bind_to_any_port(HOST);
  3992. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3993. auto se = detail::scope_exit([&] {
  3994. svr.stop();
  3995. thread.join();
  3996. ASSERT_FALSE(svr.is_running());
  3997. });
  3998. svr.wait_until_ready();
  3999. Client cli(HOST, port);
  4000. cli.set_follow_location(true);
  4001. Headers headers = {{"Cookie", "session_id=SECRET"}};
  4002. auto res = cli.Get("/redir", headers);
  4003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4004. EXPECT_EQ(StatusCode::OK_200, res->status);
  4005. EXPECT_EQ("session_id=SECRET", captured_cookie);
  4006. }
  4007. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  4008. // The Location alone names the next target, on any origin.
  4009. Server target_svr;
  4010. std::string cross_target;
  4011. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  4012. cross_target = req.target;
  4013. res.set_content("OK", "text/plain");
  4014. });
  4015. auto target_port = target_svr.bind_to_any_port(HOST);
  4016. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  4017. Server origin_svr;
  4018. std::string same_target;
  4019. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  4020. res.set_redirect(
  4021. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  4022. });
  4023. origin_svr.Get("/same", [&](const Request &, Response &res) {
  4024. res.set_redirect("/landing", 302);
  4025. });
  4026. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  4027. same_target = req.target;
  4028. res.set_content("OK", "text/plain");
  4029. });
  4030. auto origin_port = origin_svr.bind_to_any_port(HOST);
  4031. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  4032. auto se = detail::scope_exit([&] {
  4033. origin_svr.stop();
  4034. origin_thread.join();
  4035. target_svr.stop();
  4036. target_thread.join();
  4037. });
  4038. target_svr.wait_until_ready();
  4039. origin_svr.wait_until_ready();
  4040. Client cli("localhost", origin_port);
  4041. cli.set_follow_location(true);
  4042. Request req;
  4043. req.method = "GET";
  4044. req.params = {{"api_key", "SECRET"}};
  4045. req.path = "/cross";
  4046. auto res = cli.send(req);
  4047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4048. EXPECT_EQ("/landing", cross_target);
  4049. req.path = "/same";
  4050. res = cli.send(req);
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ("/landing", same_target);
  4053. }
  4054. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  4055. std::string authorization;
  4056. std::string trace_id;
  4057. auto result = GetThroughRedirectToDifferentPort(
  4058. [&](const Request &req, Response &res) {
  4059. authorization = req.get_header_value("Authorization");
  4060. trace_id = req.get_header_value("X-Trace-Id");
  4061. res.set_content("OK", "text/plain");
  4062. },
  4063. [](Client &cli) {
  4064. cli.set_default_headers(
  4065. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4066. });
  4067. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4068. EXPECT_EQ(StatusCode::OK_200, result->status);
  4069. // Like a header given with the request, a default one goes along unless it
  4070. // carries credentials (RFC 9110 15.4).
  4071. EXPECT_TRUE(authorization.empty());
  4072. EXPECT_EQ("42", trace_id);
  4073. }
  4074. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4075. auto result = GetThroughRedirectToDifferentPort(
  4076. [](const Request &, Response &res) {
  4077. res.set_content(std::string(2048, 'x'), "text/plain");
  4078. },
  4079. [](Client &cli) { cli.set_payload_max_length(1024); });
  4080. EXPECT_FALSE(result);
  4081. }
  4082. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4083. auto result = GetThroughRedirectToDifferentPort(
  4084. [](const Request &req, Response &res) {
  4085. // Answer after a second, or once the client gives up.
  4086. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4087. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4088. }
  4089. res.set_content("late", "text/plain");
  4090. },
  4091. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4092. ASSERT_FALSE(result);
  4093. EXPECT_EQ(Error::Read, result.error());
  4094. }
  4095. #ifdef CPPHTTPLIB_SSL_ENABLED
  4096. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4097. auto result = GetThroughRedirectToDifferentPort(
  4098. [](const Request &, Response &res) {
  4099. res.status = StatusCode::Unauthorized_401;
  4100. res.set_header("WWW-Authenticate",
  4101. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4102. },
  4103. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4104. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4105. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4106. }
  4107. #endif
  4108. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4109. Server svr;
  4110. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4111. // Port number that overflows int — should not crash
  4112. res.set_redirect("http://localhost:99999999999999999999/target");
  4113. });
  4114. auto port = svr.bind_to_any_port(HOST);
  4115. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4116. auto se = detail::scope_exit([&] {
  4117. svr.stop();
  4118. thread.join();
  4119. ASSERT_FALSE(svr.is_running());
  4120. });
  4121. svr.wait_until_ready();
  4122. Client cli(HOST, port);
  4123. cli.set_follow_location(true);
  4124. auto res = cli.Get("/redir");
  4125. // Should fail gracefully, not crash (no valid response due to bad port)
  4126. EXPECT_FALSE(res);
  4127. }
  4128. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4129. Server svr;
  4130. auto port = svr.bind_to_any_port(HOST);
  4131. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4132. // The server's own port followed by junk must not be followed
  4133. res.set_redirect("http://" + std::string(HOST) + ":" +
  4134. std::to_string(port) + "junk/target");
  4135. });
  4136. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4137. res.set_content("target", "text/plain");
  4138. });
  4139. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4140. auto se = detail::scope_exit([&] {
  4141. svr.stop();
  4142. thread.join();
  4143. ASSERT_FALSE(svr.is_running());
  4144. });
  4145. svr.wait_until_ready();
  4146. Client cli(HOST, port);
  4147. cli.set_follow_location(true);
  4148. auto res = cli.Get("/redir");
  4149. EXPECT_FALSE(res);
  4150. }
  4151. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4152. Server target_svr;
  4153. std::atomic<int> target_hits{0};
  4154. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4155. target_hits++;
  4156. res.set_content("target", "text/plain");
  4157. });
  4158. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4159. res.set_content("target", "text/plain");
  4160. });
  4161. int target_port = 0;
  4162. auto target_thread = std::thread([&]() {
  4163. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4164. target_svr.listen_after_bind();
  4165. });
  4166. Server origin_svr;
  4167. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4168. res.set_redirect(req.get_param_value("to"));
  4169. });
  4170. int origin_port = 0;
  4171. auto origin_thread = std::thread([&]() {
  4172. origin_port = origin_svr.bind_to_any_port(HOST);
  4173. origin_svr.listen_after_bind();
  4174. });
  4175. auto se = detail::scope_exit([&] {
  4176. origin_svr.stop();
  4177. origin_thread.join();
  4178. target_svr.stop();
  4179. target_thread.join();
  4180. ASSERT_FALSE(origin_svr.is_running());
  4181. ASSERT_FALSE(target_svr.is_running());
  4182. });
  4183. target_svr.wait_until_ready();
  4184. origin_svr.wait_until_ready();
  4185. auto port = std::to_string(target_port);
  4186. for (const auto &to :
  4187. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4188. Client cli(HOST, origin_port);
  4189. cli.set_follow_location(true);
  4190. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4191. EXPECT_FALSE(res) << to;
  4192. }
  4193. EXPECT_EQ(0, target_hits);
  4194. Client cli(HOST, origin_port);
  4195. cli.set_follow_location(true);
  4196. auto res = cli.Get("/redir?to=" +
  4197. encode_query_component("//127.0.0.1:" + port + "/target"));
  4198. ASSERT_TRUE(res) << to_string(res.error());
  4199. EXPECT_EQ(StatusCode::OK_200, res->status);
  4200. EXPECT_EQ("target", res->body);
  4201. }
  4202. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4203. Server svr;
  4204. std::atomic<bool> followed{false};
  4205. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4206. res.status = StatusCode::NotModified_304;
  4207. res.set_header("Location", "/target");
  4208. });
  4209. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4210. res.status = StatusCode::UseProxy_305;
  4211. res.set_header("Location", "/target");
  4212. });
  4213. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4214. followed = true;
  4215. res.set_content("target", "text/plain");
  4216. });
  4217. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. th.join();
  4221. ASSERT_FALSE(svr.is_running());
  4222. });
  4223. svr.wait_until_ready();
  4224. Client cli("localhost", PORT);
  4225. cli.set_follow_location(true);
  4226. auto res = cli.Get("/304");
  4227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4228. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4229. res = cli.Get("/305");
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4232. EXPECT_FALSE(followed);
  4233. }
  4234. TEST(RedirectFromPageWithContent, Redirect) {
  4235. Server svr;
  4236. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4237. res.set_content("___", "text/plain");
  4238. res.set_redirect("/2");
  4239. });
  4240. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4241. res.set_content("Hello World!", "text/plain");
  4242. });
  4243. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4244. auto se = detail::scope_exit([&] {
  4245. svr.stop();
  4246. th.join();
  4247. ASSERT_FALSE(svr.is_running());
  4248. });
  4249. svr.wait_until_ready();
  4250. {
  4251. Client cli("localhost", PORT);
  4252. cli.set_follow_location(true);
  4253. std::string body;
  4254. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4255. body.append(data, data_length);
  4256. return true;
  4257. });
  4258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4259. EXPECT_EQ(StatusCode::OK_200, res->status);
  4260. EXPECT_EQ("Hello World!", body);
  4261. }
  4262. {
  4263. Client cli("localhost", PORT);
  4264. std::string body;
  4265. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4266. body.append(data, data_length);
  4267. return true;
  4268. });
  4269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4270. EXPECT_EQ(StatusCode::Found_302, res->status);
  4271. EXPECT_EQ("___", body);
  4272. }
  4273. }
  4274. // A server can close the connection after a request with "Connection: close"
  4275. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4276. // redirected request must go out on a new connection.
  4277. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4278. #ifndef _WIN32
  4279. signal(SIGPIPE, SIG_IGN);
  4280. #endif
  4281. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4282. default_socket_options(srv);
  4283. sockaddr_in addr{};
  4284. addr.sin_family = AF_INET;
  4285. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4286. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4287. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4288. ASSERT_EQ(0, ::listen(srv, 2));
  4289. auto send_text = [](socket_t sock, const std::string &text) {
  4290. ::send(sock,
  4291. #ifdef _WIN32
  4292. static_cast<const char *>(text.c_str()),
  4293. static_cast<int>(text.size()),
  4294. #else
  4295. text.c_str(), text.size(),
  4296. #endif
  4297. 0);
  4298. };
  4299. auto reused = false;
  4300. auto server_thread = std::thread([&] {
  4301. char buf[4096];
  4302. auto first = ::accept(srv, nullptr, nullptr);
  4303. if (first == INVALID_SOCKET) { return; }
  4304. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4305. ::recv(first, buf, sizeof(buf), 0);
  4306. send_text(
  4307. first,
  4308. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4309. auto next = first;
  4310. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4311. reused = true;
  4312. } else {
  4313. detail::close_socket(first);
  4314. next = ::accept(srv, nullptr, nullptr);
  4315. if (next == INVALID_SOCKET) { return; }
  4316. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4317. ::recv(next, buf, sizeof(buf), 0);
  4318. }
  4319. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4320. "Connection: close\r\n\r\nok");
  4321. detail::close_socket(next);
  4322. });
  4323. Client cli("127.0.0.1", PORT + 2);
  4324. cli.set_follow_location(true);
  4325. cli.set_read_timeout(5, 0);
  4326. auto res = cli.Get("/1");
  4327. server_thread.join();
  4328. detail::close_socket(srv);
  4329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4330. EXPECT_EQ(StatusCode::OK_200, res->status);
  4331. EXPECT_EQ("ok", res->body);
  4332. EXPECT_FALSE(reused);
  4333. }
  4334. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4335. Server svr;
  4336. auto port_str = std::to_string(PORT);
  4337. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4338. auto expected_host = "[::1]:" + port_str;
  4339. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4340. res.set_content("___", "text/plain");
  4341. // res.set_redirect("/2");
  4342. res.set_redirect(redirect_url);
  4343. });
  4344. svr.Get("/2", [&](const Request &req, Response &res) {
  4345. auto host_header = req.headers.find("Host");
  4346. ASSERT_TRUE(host_header != req.headers.end());
  4347. EXPECT_EQ(expected_host, host_header->second);
  4348. res.set_content("Hello World!", "text/plain");
  4349. });
  4350. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4351. auto se = detail::scope_exit([&] {
  4352. svr.stop();
  4353. th.join();
  4354. ASSERT_FALSE(svr.is_running());
  4355. });
  4356. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4357. // actually starts anything, so the condition !svr.is_running() will
  4358. // always remain true, and the loop never stops.
  4359. // This basically counts how many milliseconds have passed since the
  4360. // call to svr.listen(), and if after 5 seconds nothing started yet
  4361. // aborts the test.
  4362. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4363. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4364. ASSERT_LT(milliseconds, 5000U);
  4365. }
  4366. {
  4367. Client cli("::1", PORT);
  4368. cli.set_follow_location(true);
  4369. std::string body;
  4370. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4371. body.append(data, data_length);
  4372. return true;
  4373. });
  4374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4375. EXPECT_EQ(StatusCode::OK_200, res->status);
  4376. EXPECT_EQ("Hello World!", body);
  4377. }
  4378. {
  4379. Client cli("::1", PORT);
  4380. std::string body;
  4381. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4382. body.append(data, data_length);
  4383. return true;
  4384. });
  4385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4386. EXPECT_EQ(StatusCode::Found_302, res->status);
  4387. EXPECT_EQ("___", body);
  4388. }
  4389. }
  4390. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4391. Server svr;
  4392. svr.Get("/foo", [](const Request &req, Response &res) {
  4393. auto a = req.params.find("a");
  4394. if (a != req.params.end()) {
  4395. res.set_content((*a).second, "text/plain");
  4396. res.status = StatusCode::OK_200;
  4397. } else {
  4398. res.status = StatusCode::BadRequest_400;
  4399. }
  4400. });
  4401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4402. auto se = detail::scope_exit([&] {
  4403. svr.stop();
  4404. thread.join();
  4405. ASSERT_FALSE(svr.is_running());
  4406. });
  4407. svr.wait_until_ready();
  4408. {
  4409. Client cli(HOST, PORT);
  4410. cli.set_path_encode(false);
  4411. auto res = cli.Get("/foo?a=explicitly+encoded");
  4412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4413. EXPECT_EQ(StatusCode::OK_200, res->status);
  4414. // This expects it back with a space, as the `+` won't have been
  4415. // url-encoded, and server-side the params get decoded turning `+`
  4416. // into spaces.
  4417. EXPECT_EQ("explicitly encoded", res->body);
  4418. }
  4419. }
  4420. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4421. // When path encoding is disabled the client must transmit the supplied
  4422. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4423. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4424. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4425. // than a space (0x20). Assert on the raw wire target to catch this.
  4426. Server svr;
  4427. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4428. svr.Get("/foo", [&](const Request &req, Response &res) {
  4429. EXPECT_EQ(expected_target, req.target);
  4430. res.status = StatusCode::OK_200;
  4431. });
  4432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4433. auto se = detail::scope_exit([&] {
  4434. svr.stop();
  4435. thread.join();
  4436. ASSERT_FALSE(svr.is_running());
  4437. });
  4438. svr.wait_until_ready();
  4439. {
  4440. Client cli(HOST, PORT);
  4441. cli.set_path_encode(false);
  4442. auto res = cli.Get(expected_target.c_str());
  4443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4444. EXPECT_EQ(StatusCode::OK_200, res->status);
  4445. }
  4446. }
  4447. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4448. // `open_stream()` used to skip the path encoding that the buffered send
  4449. // path applies, so the same `path` produced different bytes in the request
  4450. // line depending on which API was used. Assert the two agree.
  4451. Server svr;
  4452. std::string target;
  4453. svr.Get(".*", [&](const Request &req, Response &res) {
  4454. target = req.target;
  4455. res.status = StatusCode::OK_200;
  4456. });
  4457. auto port = svr.bind_to_any_port(HOST);
  4458. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4459. auto se = detail::scope_exit([&] {
  4460. svr.stop();
  4461. thread.join();
  4462. ASSERT_FALSE(svr.is_running());
  4463. });
  4464. svr.wait_until_ready();
  4465. struct {
  4466. const char *path;
  4467. const char *expected;
  4468. } cases[] = {
  4469. {"/a b?x=1", "/a%20b?x=1"},
  4470. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4471. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4472. };
  4473. for (const auto &c : cases) {
  4474. Client cli(HOST, port);
  4475. target.clear();
  4476. auto res = cli.Get(c.path);
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4479. auto buffered_target = target;
  4480. target.clear();
  4481. auto handle = cli.open_stream("GET", c.path);
  4482. EXPECT_TRUE(handle.is_valid())
  4483. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4484. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4485. }
  4486. }
  4487. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4488. // The `set_path_encode(false)` contract — transmit the supplied target
  4489. // verbatim — must hold for the streaming API too.
  4490. Server svr;
  4491. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4492. std::string target;
  4493. svr.Get("/foo", [&](const Request &req, Response &res) {
  4494. target = req.target;
  4495. res.status = StatusCode::OK_200;
  4496. });
  4497. auto port = svr.bind_to_any_port(HOST);
  4498. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. {
  4506. Client cli(HOST, port);
  4507. cli.set_path_encode(false);
  4508. auto handle = cli.open_stream("GET", expected_target);
  4509. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4510. EXPECT_EQ(expected_target, target);
  4511. }
  4512. }
  4513. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4514. // With path encoding enabled a CR/LF in the target is percent-encoded
  4515. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4516. // write_request_line still backstops `set_path_encode(false)`, which is
  4517. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4518. Server svr;
  4519. // Captured before routing: the decoded path contains a newline, which a
  4520. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4521. std::string target;
  4522. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4523. target = req.target;
  4524. res.status = StatusCode::OK_200;
  4525. return Server::HandlerResponse::Handled;
  4526. });
  4527. auto port = svr.bind_to_any_port(HOST);
  4528. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4529. auto se = detail::scope_exit([&] {
  4530. svr.stop();
  4531. thread.join();
  4532. ASSERT_FALSE(svr.is_running());
  4533. });
  4534. svr.wait_until_ready();
  4535. {
  4536. Client cli(HOST, port);
  4537. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4538. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4539. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4540. }
  4541. }
  4542. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4543. // Every control character is percent-encoded, not just CR/LF, so the target
  4544. // passes the request-target check in write_request_line.
  4545. Server svr;
  4546. std::string target;
  4547. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4548. target = req.target;
  4549. res.status = StatusCode::OK_200;
  4550. return Server::HandlerResponse::Handled;
  4551. });
  4552. auto port = svr.bind_to_any_port(HOST);
  4553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4554. auto se = detail::scope_exit([&] {
  4555. svr.stop();
  4556. thread.join();
  4557. ASSERT_FALSE(svr.is_running());
  4558. });
  4559. svr.wait_until_ready();
  4560. {
  4561. Client cli(HOST, port);
  4562. auto res = cli.Get("/a\tb\x1b\x7f");
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("/a%09b%1B%7F", target);
  4565. }
  4566. }
  4567. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4568. // Nothing may reach the wire: a raw CR/LF target would split the request
  4569. // line and inject headers.
  4570. Server svr;
  4571. // Pre-routing so that "not called" means nothing reached the server at all,
  4572. // rather than merely failing to match a handler pattern.
  4573. auto handler_called = false;
  4574. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4575. handler_called = true;
  4576. res.status = StatusCode::OK_200;
  4577. return Server::HandlerResponse::Handled;
  4578. });
  4579. auto port = svr.bind_to_any_port(HOST);
  4580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4581. auto se = detail::scope_exit([&] {
  4582. svr.stop();
  4583. thread.join();
  4584. ASSERT_FALSE(svr.is_running());
  4585. });
  4586. svr.wait_until_ready();
  4587. {
  4588. Client cli(HOST, port);
  4589. cli.set_path_encode(false);
  4590. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4591. EXPECT_FALSE(handle.is_valid());
  4592. EXPECT_EQ(Error::Write, handle.error);
  4593. EXPECT_FALSE(handler_called);
  4594. }
  4595. }
  4596. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4597. // Which of the two branches runs is decided by whether the query component
  4598. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4599. // an empty query and must still fall back to building one from
  4600. // `req.params`, while a non-empty query must win over `req.params`.
  4601. Server svr;
  4602. std::string target;
  4603. svr.Get("/foo", [&](const Request &req, Response &res) {
  4604. target = req.target;
  4605. res.status = StatusCode::OK_200;
  4606. });
  4607. auto port = svr.bind_to_any_port(HOST);
  4608. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4609. auto se = detail::scope_exit([&] {
  4610. svr.stop();
  4611. thread.join();
  4612. ASSERT_FALSE(svr.is_running());
  4613. });
  4614. svr.wait_until_ready();
  4615. {
  4616. // Trailing `?` -> empty query component -> `req.params` is used.
  4617. Client cli(HOST, port);
  4618. Request req;
  4619. req.method = "GET";
  4620. req.path = "/foo?";
  4621. req.params.emplace("a", "1");
  4622. target.clear();
  4623. auto res = cli.send(req);
  4624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4625. EXPECT_EQ("/foo?a=1", target);
  4626. }
  4627. {
  4628. // Non-empty query in `req.path` -> `req.params` is not appended.
  4629. Client cli(HOST, port);
  4630. Request req;
  4631. req.method = "GET";
  4632. req.path = "/foo?b=2";
  4633. req.params.emplace("a", "1");
  4634. target.clear();
  4635. auto res = cli.send(req);
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ("/foo?b=2", target);
  4638. }
  4639. }
  4640. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4641. Server svr;
  4642. svr.Get("/", [](const Request &req, Response &) {
  4643. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4644. });
  4645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4646. auto se = detail::scope_exit([&] {
  4647. svr.stop();
  4648. thread.join();
  4649. ASSERT_FALSE(svr.is_running());
  4650. });
  4651. svr.wait_until_ready();
  4652. {
  4653. Client cli(HOST, PORT);
  4654. cli.set_path_encode(false);
  4655. auto res = cli.Get("/?something=%0A");
  4656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. }
  4659. }
  4660. TEST(BindServerTest, BindDualStack) {
  4661. Server svr;
  4662. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4663. res.set_content("Hello World!", "text/plain");
  4664. });
  4665. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4666. auto se = detail::scope_exit([&] {
  4667. svr.stop();
  4668. thread.join();
  4669. ASSERT_FALSE(svr.is_running());
  4670. });
  4671. svr.wait_until_ready();
  4672. {
  4673. Client cli("127.0.0.1", PORT);
  4674. auto res = cli.Get("/1");
  4675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4676. EXPECT_EQ(StatusCode::OK_200, res->status);
  4677. EXPECT_EQ("Hello World!", res->body);
  4678. }
  4679. {
  4680. Client cli("::1", PORT);
  4681. auto res = cli.Get("/1");
  4682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("Hello World!", res->body);
  4685. }
  4686. }
  4687. TEST(BindServerTest, BindAndListenSeparately) {
  4688. Server svr;
  4689. int port = svr.bind_to_any_port("0.0.0.0");
  4690. ASSERT_TRUE(svr.is_valid());
  4691. ASSERT_TRUE(port > 0);
  4692. svr.stop();
  4693. }
  4694. // Reports whether anything is still listening on a loopback port. A plain
  4695. // connect() is used instead of a Client request because a socket left bound by
  4696. // mistake accepts the connection into its backlog and never answers, which
  4697. // would hang the test instead of failing it.
  4698. static bool is_loopback_port_accepting(int port) {
  4699. sockaddr_in addr{};
  4700. addr.sin_family = AF_INET;
  4701. addr.sin_port = htons(static_cast<uint16_t>(port));
  4702. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4703. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4704. EXPECT_NE(sock, INVALID_SOCKET);
  4705. if (sock == INVALID_SOCKET) { return false; }
  4706. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4707. static_cast<socklen_t>(sizeof(addr)));
  4708. detail::close_socket(sock);
  4709. return ret == 0;
  4710. }
  4711. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4712. Server svr;
  4713. auto port = svr.bind_to_any_port("127.0.0.1");
  4714. ASSERT_TRUE(port > 0);
  4715. svr.stop();
  4716. // bind_to_any_port() already called listen(2), so until stop() closed the
  4717. // descriptor the port kept accepting connections into the backlog. ASSERT
  4718. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4719. // below blocks forever in the accept loop.
  4720. ASSERT_FALSE(is_loopback_port_accepting(port));
  4721. // Nothing is left to accept on, so listen_after_bind() must report failure
  4722. // instead of returning success without ever serving.
  4723. EXPECT_FALSE(svr.listen_after_bind());
  4724. // The failed listen marks the server decommissioned, so a waiter returns
  4725. // instead of spinning forever.
  4726. svr.wait_until_ready();
  4727. }
  4728. #ifdef CPPHTTPLIB_SSL_ENABLED
  4729. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4731. CLIENT_CA_CERT_DIR);
  4732. int port = svr.bind_to_any_port("0.0.0.0");
  4733. ASSERT_TRUE(svr.is_valid());
  4734. ASSERT_TRUE(port > 0);
  4735. svr.stop();
  4736. }
  4737. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4738. // or a rejected CustomRoute() registration would not stop the server binding.
  4739. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4741. CLIENT_CA_CERT_DIR);
  4742. ASSERT_TRUE(svr.is_valid());
  4743. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4744. EXPECT_FALSE(svr.is_valid());
  4745. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4746. }
  4747. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4748. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4749. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4750. int port = svr.bind_to_any_port("0.0.0.0");
  4751. ASSERT_TRUE(svr.is_valid());
  4752. ASSERT_TRUE(port > 0);
  4753. svr.stop();
  4754. }
  4755. TEST(BindServerTest, UpdateCertsPem) {
  4756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4757. int port = svr.bind_to_any_port("0.0.0.0");
  4758. ASSERT_TRUE(svr.is_valid());
  4759. ASSERT_TRUE(port > 0);
  4760. // Read PEM files
  4761. std::string cert_pem, key_pem, ca_pem;
  4762. read_file(SERVER_CERT_FILE, cert_pem);
  4763. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4764. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4765. // Update server certificates using PEM API
  4766. ASSERT_TRUE(
  4767. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4768. ASSERT_TRUE(svr.is_valid());
  4769. svr.stop();
  4770. }
  4771. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4772. // Start server with client CA (enables client auth)
  4773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4774. ASSERT_TRUE(svr.is_valid());
  4775. bool handler_called = false;
  4776. svr.Get("/test", [&](const Request &req, Response &res) {
  4777. handler_called = true;
  4778. // Verify client certificate is present
  4779. auto cert = req.peer_cert();
  4780. EXPECT_TRUE(static_cast<bool>(cert));
  4781. res.set_content("ok", "text/plain");
  4782. });
  4783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4784. auto se = detail::scope_exit([&] {
  4785. svr.stop();
  4786. t.join();
  4787. ASSERT_FALSE(svr.is_running());
  4788. });
  4789. svr.wait_until_ready();
  4790. // Read PEM files
  4791. std::string cert_pem, key_pem, ca_pem;
  4792. read_file(SERVER_CERT_FILE, cert_pem);
  4793. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4794. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4795. // Update server certificates and client CA using PEM API while server running
  4796. ASSERT_TRUE(
  4797. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4798. // Connect with client certificate
  4799. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4800. cli.enable_server_certificate_verification(false);
  4801. cli.set_connection_timeout(30);
  4802. auto res = cli.Get("/test");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. ASSERT_EQ(StatusCode::OK_200, res->status);
  4805. ASSERT_TRUE(handler_called);
  4806. EXPECT_EQ("ok", res->body);
  4807. }
  4808. // Puts a CA that did not sign the client's certificate in the old one's place.
  4809. static bool replace_client_ca(SSLServer &svr) {
  4810. std::string cert_pem, key_pem, ca_pem;
  4811. read_file(SERVER_CERT_FILE, cert_pem);
  4812. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4813. read_file(SERVER_CERT2_FILE, ca_pem);
  4814. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4815. ca_pem.c_str());
  4816. }
  4817. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4819. ASSERT_TRUE(svr.is_valid());
  4820. svr.Get("/test", [](const Request &, Response &res) {
  4821. res.set_content("ok", "text/plain");
  4822. });
  4823. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4824. auto se = detail::scope_exit([&] {
  4825. svr.stop();
  4826. t.join();
  4827. ASSERT_FALSE(svr.is_running());
  4828. });
  4829. svr.wait_until_ready();
  4830. auto get = [] {
  4831. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4832. cli.enable_server_certificate_verification(false);
  4833. return cli.Get("/test");
  4834. };
  4835. ASSERT_TRUE(get());
  4836. ASSERT_TRUE(replace_client_ca(svr));
  4837. EXPECT_FALSE(get());
  4838. }
  4839. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4840. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4842. ASSERT_TRUE(svr.is_valid());
  4843. tls::set_verify_callback(svr.tls_context(),
  4844. [](const tls::VerifyContext &) -> bool {
  4845. throw std::runtime_error("verify");
  4846. });
  4847. svr.Get("/test", [](const Request &, Response &res) {
  4848. res.set_content("ok", "text/plain");
  4849. });
  4850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4851. auto se = detail::scope_exit([&] {
  4852. svr.stop();
  4853. t.join();
  4854. ASSERT_FALSE(svr.is_running());
  4855. });
  4856. svr.wait_until_ready();
  4857. auto get = [] {
  4858. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4859. cli.enable_server_certificate_verification(false);
  4860. return cli.Get("/test");
  4861. };
  4862. EXPECT_FALSE(get());
  4863. // The handshake is over, so an update does not wait for it.
  4864. std::string cert_pem, key_pem;
  4865. read_file(SERVER_CERT_FILE, cert_pem);
  4866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4867. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4868. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4869. return v.preverify_ok;
  4870. });
  4871. auto res = get();
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. EXPECT_EQ("ok", res->body);
  4874. }
  4875. #endif
  4876. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4877. // Sends each request over a new connection with a client certificate,
  4878. // resuming the session of the one before when there is one.
  4879. class ResumingClient {
  4880. public:
  4881. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4882. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4883. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4884. SSL_FILETYPE_PEM);
  4885. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4886. // callback, not through SSL_get1_session().
  4887. SSL_CTX_set_app_data(ctx_, this);
  4888. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4889. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4890. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4891. auto self = static_cast<ResumingClient *>(
  4892. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4893. SSL_SESSION_free(self->session_);
  4894. self->session_ = session;
  4895. return 1; // Keeps the reference
  4896. });
  4897. }
  4898. ~ResumingClient() {
  4899. SSL_SESSION_free(session_);
  4900. SSL_CTX_free(ctx_);
  4901. }
  4902. // Tells whether the request was answered.
  4903. bool get() {
  4904. auto error = Error::Success;
  4905. auto sock = detail::create_client_socket(
  4906. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4907. /*connection_timeout_sec=*/5, 0,
  4908. /*read_timeout_sec=*/5, 0,
  4909. /*write_timeout_sec=*/5, 0, std::string(), error);
  4910. if (sock == INVALID_SOCKET) { return false; }
  4911. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4912. auto ssl = SSL_new(ctx_);
  4913. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4914. SSL_set_fd(ssl, static_cast<int>(sock));
  4915. if (session_) { SSL_set_session(ssl, session_); }
  4916. if (SSL_connect(ssl) != 1) { return false; }
  4917. reused_ = SSL_session_reused(ssl) == 1;
  4918. // Reading the response also takes in a TLS 1.3 session ticket.
  4919. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4920. "Connection: close\r\n\r\n";
  4921. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4922. std::string res;
  4923. char buf[256];
  4924. int n;
  4925. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4926. res.append(buf, static_cast<size_t>(n));
  4927. }
  4928. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4929. SSL_shutdown(ssl);
  4930. return res.find("200 OK") != std::string::npos;
  4931. }
  4932. // Whether the last connection resumed a session
  4933. bool reused() const { return reused_; }
  4934. private:
  4935. SSL_CTX *ctx_;
  4936. SSL_SESSION *session_ = nullptr;
  4937. bool reused_ = false;
  4938. };
  4939. // A client that resumes its session gets through, but not once the client CA
  4940. // has changed, as a resumed session does not show the certificate again.
  4941. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4943. ASSERT_TRUE(svr.is_valid());
  4944. svr.Get("/test", [](const Request &, Response &res) {
  4945. res.set_content("ok", "text/plain");
  4946. });
  4947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4948. auto se = detail::scope_exit([&] {
  4949. svr.stop();
  4950. t.join();
  4951. ASSERT_FALSE(svr.is_running());
  4952. });
  4953. svr.wait_until_ready();
  4954. ResumingClient cli;
  4955. ASSERT_TRUE(cli.get());
  4956. ASSERT_TRUE(cli.get());
  4957. EXPECT_TRUE(cli.reused());
  4958. ASSERT_TRUE(replace_client_ca(svr));
  4959. EXPECT_FALSE(cli.get());
  4960. }
  4961. // A resumed session does not show the certificate again, so the server does
  4962. // not resume one with a verify callback to run on it.
  4963. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4965. ASSERT_TRUE(svr.is_valid());
  4966. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4967. return v.preverify_ok;
  4968. });
  4969. svr.Get("/test", [](const Request &, Response &res) {
  4970. res.set_content("ok", "text/plain");
  4971. });
  4972. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4973. auto se = detail::scope_exit([&] {
  4974. svr.stop();
  4975. t.join();
  4976. ASSERT_FALSE(svr.is_running());
  4977. });
  4978. svr.wait_until_ready();
  4979. ResumingClient cli;
  4980. ASSERT_TRUE(cli.get());
  4981. ASSERT_TRUE(cli.get());
  4982. EXPECT_FALSE(cli.reused());
  4983. }
  4984. #endif
  4985. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4986. // wolfSSL shares its session cache between contexts, so a resumed session
  4987. // could carry a client certificate checked against another server's CA, or
  4988. // against a client CA since replaced.
  4989. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4991. ASSERT_TRUE(svr.is_valid());
  4992. // Trusts a CA that did not sign the client's certificate.
  4993. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4994. ASSERT_TRUE(other.is_valid());
  4995. for (auto s : {&svr, &other}) {
  4996. s->Get("/test", [](const Request &, Response &res) {
  4997. res.set_content("ok", "text/plain");
  4998. });
  4999. }
  5000. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5001. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  5002. auto se = detail::scope_exit([&] {
  5003. other.stop();
  5004. svr.stop();
  5005. t2.join();
  5006. t.join();
  5007. });
  5008. svr.wait_until_ready();
  5009. other.wait_until_ready();
  5010. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  5011. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  5012. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  5013. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  5014. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  5015. ASSERT_EQ(WOLFSSL_SUCCESS,
  5016. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  5017. WOLFSSL_FILETYPE_PEM));
  5018. WOLFSSL_SESSION *session = nullptr;
  5019. auto session_se = detail::scope_exit([&] {
  5020. if (session) { wolfSSL_SESSION_free(session); }
  5021. });
  5022. // A request over a new connection, resuming `session` when there is one and
  5023. // keeping the connection's own in its place. Tells whether it was answered.
  5024. auto get = [&](int port) {
  5025. auto error = Error::Success;
  5026. auto sock = detail::create_client_socket(
  5027. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  5028. /*connection_timeout_sec=*/5, 0,
  5029. /*read_timeout_sec=*/5, 0,
  5030. /*write_timeout_sec=*/5, 0, std::string(), error);
  5031. if (sock == INVALID_SOCKET) { return false; }
  5032. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  5033. auto ssl = wolfSSL_new(ctx);
  5034. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  5035. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  5036. if (session) { wolfSSL_set_session(ssl, session); }
  5037. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  5038. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  5039. "Connection: close\r\n\r\n";
  5040. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  5041. std::string res;
  5042. char buf[256];
  5043. int n;
  5044. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  5045. res.append(buf, static_cast<size_t>(n));
  5046. }
  5047. wolfSSL_shutdown(ssl);
  5048. if (session) { wolfSSL_SESSION_free(session); }
  5049. session = wolfSSL_get1_session(ssl);
  5050. return res.find("200 OK") != std::string::npos;
  5051. };
  5052. ASSERT_TRUE(get(PORT));
  5053. EXPECT_FALSE(get(PORT + 1));
  5054. ASSERT_TRUE(get(PORT));
  5055. ASSERT_TRUE(replace_client_ca(svr));
  5056. EXPECT_FALSE(get(PORT));
  5057. }
  5058. #endif
  5059. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  5060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5061. ASSERT_TRUE(svr.is_valid());
  5062. // Keep-alive parking would wait for the ClientHello without a handshake.
  5063. svr.set_keep_alive_parking(false);
  5064. svr.Get("/test", [](const Request &, Response &res) {
  5065. res.set_content("ok", "text/plain");
  5066. });
  5067. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5068. auto se = detail::scope_exit([&] {
  5069. svr.stop();
  5070. t.join();
  5071. ASSERT_FALSE(svr.is_running());
  5072. });
  5073. svr.wait_until_ready();
  5074. // A connection that sends no ClientHello keeps its handshake in progress,
  5075. // once the server has had a moment to start it.
  5076. auto error = Error::Success;
  5077. auto sock = detail::create_client_socket(
  5078. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5079. /*connection_timeout_sec=*/5, 0,
  5080. /*read_timeout_sec=*/5, 0,
  5081. /*write_timeout_sec=*/5, 0, std::string(), error);
  5082. ASSERT_NE(INVALID_SOCKET, sock);
  5083. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5084. std::string cert_pem, key_pem;
  5085. read_file(SERVER_CERT_FILE, cert_pem);
  5086. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5087. auto update = std::async(std::launch::async, [&]() {
  5088. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5089. });
  5090. EXPECT_EQ(std::future_status::timeout,
  5091. update.wait_for(std::chrono::milliseconds(200)));
  5092. detail::close_socket(sock);
  5093. EXPECT_TRUE(update.get());
  5094. SSLClient cli(HOST, PORT);
  5095. cli.enable_server_certificate_verification(false);
  5096. auto res = cli.Get("/test");
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. }
  5100. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5102. ASSERT_TRUE(svr.is_valid());
  5103. // Keep-alive parking would wait for the ClientHello without a handshake.
  5104. svr.set_keep_alive_parking(false);
  5105. svr.set_read_timeout(10, 0);
  5106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5107. auto se = detail::scope_exit([&] {
  5108. svr.stop();
  5109. if (t.joinable()) { t.join(); }
  5110. });
  5111. svr.wait_until_ready();
  5112. // A connection that sends no ClientHello keeps its handshake in progress,
  5113. // once the server has had a moment to start it.
  5114. auto error = Error::Success;
  5115. auto sock = detail::create_client_socket(
  5116. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5117. /*connection_timeout_sec=*/5, 0,
  5118. /*read_timeout_sec=*/5, 0,
  5119. /*write_timeout_sec=*/5, 0, std::string(), error);
  5120. ASSERT_NE(INVALID_SOCKET, sock);
  5121. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5122. auto start = std::chrono::steady_clock::now();
  5123. svr.stop();
  5124. t.join();
  5125. auto elapsed = std::chrono::steady_clock::now() - start;
  5126. detail::close_socket(sock);
  5127. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5128. }
  5129. #endif
  5130. TEST(ErrorHandlerTest, ContentLength) {
  5131. Server svr;
  5132. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5133. res.status = StatusCode::OK_200;
  5134. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5135. "text/html"); // <= Content-Length still 13
  5136. });
  5137. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5138. res.set_content("Hello World!\n", "text/plain");
  5139. res.status = 524;
  5140. });
  5141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5142. auto se = detail::scope_exit([&] {
  5143. svr.stop();
  5144. thread.join();
  5145. ASSERT_FALSE(svr.is_running());
  5146. });
  5147. svr.wait_until_ready();
  5148. {
  5149. Client cli(HOST, PORT);
  5150. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5156. }
  5157. }
  5158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5159. TEST(ExceptionTest, WithoutExceptionHandler) {
  5160. Server svr;
  5161. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5162. throw std::runtime_error("exception...");
  5163. });
  5164. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5165. throw std::runtime_error("exception\r\n...");
  5166. });
  5167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5168. auto se = detail::scope_exit([&] {
  5169. svr.stop();
  5170. listen_thread.join();
  5171. ASSERT_FALSE(svr.is_running());
  5172. });
  5173. svr.wait_until_ready();
  5174. Client cli("localhost", PORT);
  5175. {
  5176. auto res = cli.Get("/exception");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5179. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5180. }
  5181. {
  5182. auto res = cli.Get("/unknown");
  5183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5185. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5186. }
  5187. }
  5188. TEST(ExceptionTest, WithExceptionHandler) {
  5189. Server svr;
  5190. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5191. std::exception_ptr ep) {
  5192. EXPECT_FALSE(ep == nullptr);
  5193. try {
  5194. std::rethrow_exception(ep);
  5195. } catch (std::exception &e) {
  5196. EXPECT_EQ("abc", std::string(e.what()));
  5197. } catch (...) {}
  5198. res.status = StatusCode::InternalServerError_500;
  5199. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5200. "text/html"); // <= Content-Length still 13 at this point
  5201. });
  5202. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5203. res.set_content("Hello World!\n", "text/plain");
  5204. throw std::runtime_error("abc");
  5205. });
  5206. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5207. auto se = detail::scope_exit([&] {
  5208. svr.stop();
  5209. thread.join();
  5210. ASSERT_FALSE(svr.is_running());
  5211. });
  5212. svr.wait_until_ready();
  5213. for (size_t i = 0; i < 10; i++) {
  5214. Client cli(HOST, PORT);
  5215. for (size_t j = 0; j < 100; j++) {
  5216. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5218. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5219. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5220. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5221. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5222. }
  5223. cli.set_keep_alive(true);
  5224. for (size_t j = 0; j < 100; j++) {
  5225. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5228. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5229. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5230. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5231. }
  5232. }
  5233. }
  5234. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5235. Server svr;
  5236. svr.set_exception_handler(
  5237. [](const Request &, Response &res, std::exception_ptr) {
  5238. res.set_content("oops", "text/plain");
  5239. });
  5240. svr.Get("/throw", [](const Request &, Response &) {
  5241. throw std::runtime_error("throw");
  5242. });
  5243. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5244. res.status = StatusCode::Created_201;
  5245. throw std::runtime_error("created-then-throw");
  5246. });
  5247. auto port = svr.bind_to_any_port(HOST);
  5248. ASSERT_GT(port, 0);
  5249. thread t = thread([&] { svr.listen_after_bind(); });
  5250. auto se = detail::scope_exit([&] {
  5251. svr.stop();
  5252. t.join();
  5253. ASSERT_FALSE(svr.is_running());
  5254. });
  5255. svr.wait_until_ready();
  5256. Client cli(HOST, port);
  5257. for (auto path : {"/throw", "/created-then-throw"}) {
  5258. auto res = cli.Get(path);
  5259. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5260. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5261. }
  5262. }
  5263. TEST(ExceptionTest, AndErrorHandler) {
  5264. Server svr;
  5265. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5266. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5267. });
  5268. svr.set_exception_handler(
  5269. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5270. EXPECT_FALSE(ep == nullptr);
  5271. try {
  5272. std::rethrow_exception(ep);
  5273. } catch (std::exception &e) {
  5274. res.set_content(e.what(), "text/html");
  5275. } catch (...) {}
  5276. res.status = StatusCode::InternalServerError_500;
  5277. });
  5278. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5279. throw std::runtime_error("EXCEPTION");
  5280. });
  5281. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5282. res.set_content("ERROR", "text/html");
  5283. res.status = StatusCode::InternalServerError_500;
  5284. });
  5285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5286. auto se = detail::scope_exit([&] {
  5287. svr.stop();
  5288. thread.join();
  5289. ASSERT_FALSE(svr.is_running());
  5290. });
  5291. svr.wait_until_ready();
  5292. Client cli(HOST, PORT);
  5293. {
  5294. auto res = cli.Get("/exception");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5297. EXPECT_EQ("EXCEPTION", res->body);
  5298. }
  5299. {
  5300. auto res = cli.Get("/error");
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5303. EXPECT_EQ("ERROR", res->body);
  5304. }
  5305. {
  5306. auto res = cli.Get("/invalid");
  5307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5309. EXPECT_EQ("NOT_FOUND", res->body);
  5310. }
  5311. }
  5312. #endif
  5313. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5314. // An exception from a user callback outside process_request()'s try/catch
  5315. // used to unwind into the task queue - which does not catch - and terminate
  5316. // the process. Each test below runs the server on a single worker thread: a
  5317. // guard that catches the exception but still loses the thread would otherwise
  5318. // be hidden by a spare worker serving the follow-up request. Note that a
  5319. // regression here aborts the whole test binary rather than failing one test.
  5320. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5321. Server svr;
  5322. svr.new_task_queue = [] { return new ThreadPool(1); };
  5323. std::atomic<int> reported{0};
  5324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5325. if (err == Error::UserCallbackException) { reported++; }
  5326. });
  5327. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5328. res.set_content_provider(
  5329. 1024, "text/plain",
  5330. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5331. sink.write("hello", 5);
  5332. throw std::runtime_error("from the content provider");
  5333. });
  5334. });
  5335. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5336. res.set_content("ok", "text/plain");
  5337. });
  5338. auto port = svr.bind_to_any_port(HOST);
  5339. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5340. auto se = detail::scope_exit([&] {
  5341. svr.stop();
  5342. listen_thread.join();
  5343. ASSERT_FALSE(svr.is_running());
  5344. });
  5345. svr.wait_until_ready();
  5346. {
  5347. Client cli(HOST, port);
  5348. cli.set_read_timeout(5, 0);
  5349. EXPECT_FALSE(cli.Get("/throw"));
  5350. }
  5351. EXPECT_TRUE(svr.is_running());
  5352. EXPECT_EQ(1, reported.load());
  5353. // A request on a fresh connection is still served.
  5354. {
  5355. Client cli(HOST, port);
  5356. auto res = cli.Get("/ok");
  5357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. EXPECT_EQ("ok", res->body);
  5360. }
  5361. }
  5362. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5363. Server svr;
  5364. svr.new_task_queue = [] { return new ThreadPool(1); };
  5365. std::atomic<bool> should_throw{true};
  5366. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5367. res.set_content("hi", "text/plain");
  5368. });
  5369. svr.set_post_routing_handler(
  5370. [&](const Request & /*req*/, Response & /*res*/) {
  5371. if (should_throw) {
  5372. throw std::runtime_error("from the post-routing handler");
  5373. }
  5374. });
  5375. auto port = svr.bind_to_any_port(HOST);
  5376. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5377. auto se = detail::scope_exit([&] {
  5378. svr.stop();
  5379. listen_thread.join();
  5380. ASSERT_FALSE(svr.is_running());
  5381. });
  5382. svr.wait_until_ready();
  5383. {
  5384. Client cli(HOST, port);
  5385. cli.set_read_timeout(5, 0);
  5386. EXPECT_FALSE(cli.Get("/hi"));
  5387. }
  5388. EXPECT_TRUE(svr.is_running());
  5389. should_throw = false;
  5390. {
  5391. Client cli(HOST, port);
  5392. auto res = cli.Get("/hi");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("hi", res->body);
  5396. }
  5397. }
  5398. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5399. // The guard reports the caught exception through the error logger, which is
  5400. // a user callback too. A logger that throws has to be contained as well, or
  5401. // the process would terminate from inside the catch.
  5402. Server svr;
  5403. svr.new_task_queue = [] { return new ThreadPool(1); };
  5404. std::atomic<int> reported{0};
  5405. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5406. if (err == Error::UserCallbackException) {
  5407. reported++;
  5408. throw std::runtime_error("from the error logger");
  5409. }
  5410. });
  5411. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5412. res.set_content_provider(
  5413. 1024, "text/plain",
  5414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5415. sink.write("hello", 5);
  5416. throw std::runtime_error("from the content provider");
  5417. });
  5418. });
  5419. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5420. res.set_content("ok", "text/plain");
  5421. });
  5422. auto port = svr.bind_to_any_port(HOST);
  5423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5424. auto se = detail::scope_exit([&] {
  5425. svr.stop();
  5426. listen_thread.join();
  5427. ASSERT_FALSE(svr.is_running());
  5428. });
  5429. svr.wait_until_ready();
  5430. {
  5431. Client cli(HOST, port);
  5432. cli.set_read_timeout(5, 0);
  5433. EXPECT_FALSE(cli.Get("/throw"));
  5434. }
  5435. EXPECT_TRUE(svr.is_running());
  5436. EXPECT_EQ(1, reported.load());
  5437. {
  5438. Client cli(HOST, port);
  5439. auto res = cli.Get("/ok");
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ(StatusCode::OK_200, res->status);
  5442. EXPECT_EQ("ok", res->body);
  5443. }
  5444. }
  5445. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5446. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5447. // so the exception unwinds through the ws::WebSocket object on its way to
  5448. // the guard. None of the HTTP cases above cross that.
  5449. Server svr;
  5450. svr.new_task_queue = [] { return new ThreadPool(1); };
  5451. std::atomic<int> reported{0};
  5452. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5453. if (err == Error::UserCallbackException) { reported++; }
  5454. });
  5455. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5456. throw std::runtime_error("from the WebSocket handler");
  5457. });
  5458. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5459. res.set_content("ok", "text/plain");
  5460. });
  5461. auto port = svr.bind_to_any_port(HOST);
  5462. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5463. auto se = detail::scope_exit([&] {
  5464. svr.stop();
  5465. listen_thread.join();
  5466. ASSERT_FALSE(svr.is_running());
  5467. });
  5468. svr.wait_until_ready();
  5469. {
  5470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5471. "/ws");
  5472. auto res = client.connect();
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. // The server dropped the connection instead of dying.
  5475. std::string msg;
  5476. EXPECT_FALSE(client.read(msg));
  5477. client.close();
  5478. }
  5479. EXPECT_TRUE(svr.is_running());
  5480. EXPECT_EQ(1, reported.load());
  5481. {
  5482. Client cli(HOST, port);
  5483. auto res = cli.Get("/ok");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("ok", res->body);
  5487. }
  5488. }
  5489. #ifdef CPPHTTPLIB_SSL_ENABLED
  5490. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5491. // SSLServer::process_and_close_socket() is a separate overload with its own
  5492. // guard, so it is exercised on its own.
  5493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5494. ASSERT_TRUE(svr.is_valid());
  5495. svr.new_task_queue = [] { return new ThreadPool(1); };
  5496. std::atomic<int> reported{0};
  5497. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5498. if (err == Error::UserCallbackException) { reported++; }
  5499. });
  5500. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5501. res.set_content_provider(
  5502. 1024, "text/plain",
  5503. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5504. sink.write("hello", 5);
  5505. throw std::runtime_error("from the content provider");
  5506. });
  5507. });
  5508. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5509. res.set_content("ok", "text/plain");
  5510. });
  5511. auto port = svr.bind_to_any_port(HOST);
  5512. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5513. auto se = detail::scope_exit([&] {
  5514. svr.stop();
  5515. listen_thread.join();
  5516. ASSERT_FALSE(svr.is_running());
  5517. });
  5518. svr.wait_until_ready();
  5519. {
  5520. SSLClient cli(HOST, port);
  5521. cli.enable_server_certificate_verification(false);
  5522. cli.set_read_timeout(5, 0);
  5523. EXPECT_FALSE(cli.Get("/throw"));
  5524. }
  5525. EXPECT_TRUE(svr.is_running());
  5526. EXPECT_EQ(1, reported.load());
  5527. {
  5528. SSLClient cli(HOST, port);
  5529. cli.enable_server_certificate_verification(false);
  5530. auto res = cli.Get("/ok");
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(StatusCode::OK_200, res->status);
  5533. EXPECT_EQ("ok", res->body);
  5534. }
  5535. }
  5536. #endif
  5537. #endif
  5538. TEST(NoContentTest, ContentLength) {
  5539. Server svr;
  5540. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5541. res.status = StatusCode::NoContent_204;
  5542. });
  5543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5544. auto se = detail::scope_exit([&] {
  5545. svr.stop();
  5546. thread.join();
  5547. ASSERT_FALSE(svr.is_running());
  5548. });
  5549. svr.wait_until_ready();
  5550. {
  5551. Client cli(HOST, PORT);
  5552. auto res = cli.Get("/hi");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5555. // RFC 9110 8.6: none in a 204 response
  5556. EXPECT_FALSE(res->has_header("Content-Length"));
  5557. }
  5558. }
  5559. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5560. Server svr;
  5561. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5562. res.set_header("Content-Length", "5");
  5563. res.set_content("hello world", "text/plain");
  5564. });
  5565. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5566. // A body that reads as the last chunk, were it taken as chunked
  5567. res.set_header("Transfer-Encoding", "chunked");
  5568. res.set_content("0\r\n\r\n", "text/plain");
  5569. });
  5570. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5571. res.set_header("Content-Length", "2");
  5572. res.set_content_provider(5, "text/plain",
  5573. [](size_t offset, size_t length, DataSink &sink) {
  5574. sink.write(&"hello"[offset], length);
  5575. return true;
  5576. });
  5577. });
  5578. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5579. res.set_header("Content-Length", "1234");
  5580. });
  5581. thread t = thread([&] { svr.listen(HOST, PORT); });
  5582. auto se = detail::scope_exit([&] {
  5583. svr.stop();
  5584. t.join();
  5585. ASSERT_FALSE(svr.is_running());
  5586. });
  5587. svr.wait_until_ready();
  5588. Client cli(HOST, PORT);
  5589. cli.set_read_timeout(1, 0);
  5590. auto expect_body = [&](const Result &res, const std::string &body) {
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(body, res->body);
  5593. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5594. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5595. };
  5596. Headers identity{{"Accept-Encoding", ""}};
  5597. expect_body(cli.Get("/body", identity), "hello world");
  5598. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5599. expect_body(cli.Get("/body",
  5600. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5601. "he");
  5602. expect_body(cli.Get("/provider", identity), "hello");
  5603. expect_body(cli.Get("/empty", identity), "");
  5604. // A HEAD response may give the length of the body a GET would get.
  5605. auto res = cli.Head("/empty");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5608. }
  5609. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5610. Server svr;
  5611. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5612. res.set_content("short", "text/plain");
  5613. });
  5614. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5615. res.body += " with a footer";
  5616. res.set_header("Transfer-Encoding", "chunked");
  5617. });
  5618. thread t = thread([&] { svr.listen(HOST, PORT); });
  5619. auto se = detail::scope_exit([&] {
  5620. svr.stop();
  5621. t.join();
  5622. ASSERT_FALSE(svr.is_running());
  5623. });
  5624. svr.wait_until_ready();
  5625. Client cli(HOST, PORT);
  5626. cli.set_read_timeout(1, 0);
  5627. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. EXPECT_EQ("short with a footer", res->body);
  5630. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5631. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5632. }
  5633. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5634. Server svr;
  5635. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5636. res.set_header("Content-Length", "3");
  5637. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5638. sink.write("abc", 3);
  5639. sink.done();
  5640. return true;
  5641. });
  5642. });
  5643. thread t = thread([&] { svr.listen(HOST, PORT); });
  5644. auto se = detail::scope_exit([&] {
  5645. svr.stop();
  5646. t.join();
  5647. ASSERT_FALSE(svr.is_running());
  5648. });
  5649. svr.wait_until_ready();
  5650. Client cli(HOST, PORT);
  5651. cli.set_keep_alive(true);
  5652. auto res = cli.Get("/");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ("abc", res->body);
  5655. EXPECT_FALSE(res->has_header("Content-Length"));
  5656. EXPECT_EQ("close", res->get_header_value("Connection"));
  5657. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5658. // No body to delimit
  5659. auto head = cli.Head("/");
  5660. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5661. EXPECT_FALSE(head->has_header("Connection"));
  5662. }
  5663. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5664. #ifdef CPPHTTPLIB_SSL_ENABLED
  5665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5666. ASSERT_TRUE(svr.is_valid());
  5667. #else
  5668. Server svr;
  5669. #endif
  5670. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5671. if (req.path == "/routing_handler") {
  5672. res.set_header("PRE_ROUTING", "on");
  5673. res.set_content("Routing Handler", "text/plain");
  5674. return httplib::Server::HandlerResponse::Handled;
  5675. }
  5676. return httplib::Server::HandlerResponse::Unhandled;
  5677. });
  5678. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5679. res.set_content("Error", "text/html");
  5680. });
  5681. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5682. if (req.path == "/routing_handler") {
  5683. res.set_header("POST_ROUTING", "on");
  5684. }
  5685. });
  5686. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5687. res.set_content("Hello World!\n", "text/plain");
  5688. });
  5689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5690. auto se = detail::scope_exit([&] {
  5691. svr.stop();
  5692. thread.join();
  5693. ASSERT_FALSE(svr.is_running());
  5694. });
  5695. svr.wait_until_ready();
  5696. {
  5697. #ifdef CPPHTTPLIB_SSL_ENABLED
  5698. SSLClient cli(HOST, PORT);
  5699. cli.enable_server_certificate_verification(false);
  5700. #else
  5701. Client cli(HOST, PORT);
  5702. #endif
  5703. auto res = cli.Get("/routing_handler");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ("Routing Handler", res->body);
  5707. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5708. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5709. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5710. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5711. }
  5712. {
  5713. #ifdef CPPHTTPLIB_SSL_ENABLED
  5714. SSLClient cli(HOST, PORT);
  5715. cli.enable_server_certificate_verification(false);
  5716. #else
  5717. Client cli(HOST, PORT);
  5718. #endif
  5719. auto res = cli.Get("/hi");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. EXPECT_EQ("Hello World!\n", res->body);
  5723. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5724. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5725. }
  5726. {
  5727. #ifdef CPPHTTPLIB_SSL_ENABLED
  5728. SSLClient cli(HOST, PORT);
  5729. cli.enable_server_certificate_verification(false);
  5730. #else
  5731. Client cli(HOST, PORT);
  5732. #endif
  5733. auto res = cli.Get("/aaa");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5736. EXPECT_EQ("Error", res->body);
  5737. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5738. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5739. }
  5740. }
  5741. TEST(RequestHandlerTest, PreRequestHandler) {
  5742. auto route_path = "/user/:user";
  5743. Server svr;
  5744. svr.Get("/hi", [](const Request &, Response &res) {
  5745. res.set_content("hi", "text/plain");
  5746. });
  5747. svr.Get(route_path, [](const Request &req, Response &res) {
  5748. res.set_content(req.path_params.at("user"), "text/plain");
  5749. });
  5750. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5751. if (req.matched_route == route_path) {
  5752. auto user = req.path_params.at("user");
  5753. if (user != "john") {
  5754. res.status = StatusCode::Forbidden_403;
  5755. res.set_content("error", "text/html");
  5756. return Server::HandlerResponse::Handled;
  5757. }
  5758. }
  5759. return Server::HandlerResponse::Unhandled;
  5760. });
  5761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5762. auto se = detail::scope_exit([&] {
  5763. svr.stop();
  5764. thread.join();
  5765. ASSERT_FALSE(svr.is_running());
  5766. });
  5767. svr.wait_until_ready();
  5768. Client cli(HOST, PORT);
  5769. {
  5770. auto res = cli.Get("/hi");
  5771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5772. EXPECT_EQ(StatusCode::OK_200, res->status);
  5773. EXPECT_EQ("hi", res->body);
  5774. }
  5775. {
  5776. auto res = cli.Get("/user/john");
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ("john", res->body);
  5780. }
  5781. {
  5782. auto res = cli.Get("/user/invalid-user");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5785. EXPECT_EQ("error", res->body);
  5786. }
  5787. }
  5788. // The pre-request handler must run before the request body is read, so a
  5789. // rejected request never forces the server to buffer a (potentially large)
  5790. // body. Here the posted body is larger than the payload limit: if the body
  5791. // were read first the server would answer 413, but because the pre-request
  5792. // handler runs first it answers 403 and the body is never read.
  5793. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5794. Server svr;
  5795. svr.set_payload_max_length(8);
  5796. auto handler_ran = false;
  5797. svr.Post("/reject", [&](const Request &req, Response &res) {
  5798. handler_ran = true;
  5799. res.set_content(req.body, "text/plain");
  5800. });
  5801. svr.Post("/accept", [](const Request &req, Response &res) {
  5802. res.set_content(req.body, "text/plain");
  5803. });
  5804. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5805. if (req.matched_route == "/reject") {
  5806. res.status = StatusCode::Forbidden_403;
  5807. res.set_content("denied", "text/plain");
  5808. return Server::HandlerResponse::Handled;
  5809. }
  5810. return Server::HandlerResponse::Unhandled;
  5811. });
  5812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5813. auto se = detail::scope_exit([&] {
  5814. svr.stop();
  5815. thread.join();
  5816. ASSERT_FALSE(svr.is_running());
  5817. });
  5818. svr.wait_until_ready();
  5819. Client cli(HOST, PORT);
  5820. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5821. // rejects with 403 before the body is read, so 413 is never reached.
  5822. {
  5823. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5826. EXPECT_EQ("denied", res->body);
  5827. EXPECT_FALSE(handler_ran);
  5828. }
  5829. // An approved route still reads the body and enforces the payload limit.
  5830. {
  5831. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5834. }
  5835. }
  5836. TEST(UserDataTest, BasicOperations) {
  5837. httplib::UserData ud;
  5838. // Initially empty
  5839. EXPECT_FALSE(ud.has("key"));
  5840. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5841. // set and get
  5842. ud.set("key", 42);
  5843. EXPECT_TRUE(ud.has("key"));
  5844. auto *p = ud.get<int>("key");
  5845. ASSERT_NE(nullptr, p);
  5846. EXPECT_EQ(42, *p);
  5847. // Type mismatch → nullptr
  5848. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5849. // Overwrite with different type
  5850. ud.set("key", std::string("hello"));
  5851. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5852. auto *s = ud.get<std::string>("key");
  5853. ASSERT_NE(nullptr, s);
  5854. EXPECT_EQ("hello", *s);
  5855. // erase
  5856. ud.erase("key");
  5857. EXPECT_FALSE(ud.has("key"));
  5858. // clear
  5859. ud.set("a", 1);
  5860. ud.set("b", 2);
  5861. ud.clear();
  5862. EXPECT_FALSE(ud.has("a"));
  5863. EXPECT_FALSE(ud.has("b"));
  5864. }
  5865. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5866. struct AuthCtx {
  5867. std::string user_id;
  5868. };
  5869. Server svr;
  5870. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5871. res.user_data.set("auth", AuthCtx{"alice"});
  5872. return Server::HandlerResponse::Unhandled;
  5873. });
  5874. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5875. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5876. ASSERT_NE(nullptr, ctx);
  5877. res.set_content("Hello " + ctx->user_id, "text/plain");
  5878. });
  5879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5880. auto se = detail::scope_exit([&] {
  5881. svr.stop();
  5882. thread.join();
  5883. ASSERT_FALSE(svr.is_running());
  5884. });
  5885. svr.wait_until_ready();
  5886. Client cli(HOST, PORT);
  5887. auto res = cli.Get("/me");
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::OK_200, res->status);
  5890. EXPECT_EQ("Hello alice", res->body);
  5891. }
  5892. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5893. struct RoleCtx {
  5894. std::string role;
  5895. };
  5896. Server svr;
  5897. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5898. res.user_data.set("role", RoleCtx{"admin"});
  5899. return Server::HandlerResponse::Unhandled;
  5900. });
  5901. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5902. auto *ctx = res.user_data.get<RoleCtx>("role");
  5903. ASSERT_NE(nullptr, ctx);
  5904. res.set_content(ctx->role, "text/plain");
  5905. });
  5906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5907. auto se = detail::scope_exit([&] {
  5908. svr.stop();
  5909. thread.join();
  5910. ASSERT_FALSE(svr.is_running());
  5911. });
  5912. svr.wait_until_ready();
  5913. Client cli(HOST, PORT);
  5914. auto res = cli.Get("/role");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_EQ("admin", res->body);
  5918. }
  5919. TEST(InvalidFormatTest, StatusCode) {
  5920. Server svr;
  5921. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5922. res.set_content("Hello World!\n", "text/plain");
  5923. res.status = 9999; // Status should be a three-digit code...
  5924. });
  5925. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5926. auto se = detail::scope_exit([&] {
  5927. svr.stop();
  5928. thread.join();
  5929. ASSERT_FALSE(svr.is_running());
  5930. });
  5931. svr.wait_until_ready();
  5932. {
  5933. Client cli(HOST, PORT);
  5934. auto res = cli.Get("/hi");
  5935. ASSERT_FALSE(res);
  5936. }
  5937. }
  5938. TEST(URLFragmentTest, WithFragment) {
  5939. Server svr;
  5940. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5941. EXPECT_TRUE(req.target == "/hi");
  5942. });
  5943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5944. auto se = detail::scope_exit([&] {
  5945. svr.stop();
  5946. thread.join();
  5947. ASSERT_FALSE(svr.is_running());
  5948. });
  5949. svr.wait_until_ready();
  5950. {
  5951. Client cli(HOST, PORT);
  5952. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5953. EXPECT_TRUE(res);
  5954. EXPECT_EQ(StatusCode::OK_200, res->status);
  5955. res = cli.Get("/hi%23key1=val1=key2=val2");
  5956. EXPECT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5958. }
  5959. }
  5960. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5961. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5962. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5963. Server svr;
  5964. std::vector<std::string> targets;
  5965. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5966. targets.push_back(req.target);
  5967. });
  5968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5969. auto se = detail::scope_exit([&] {
  5970. svr.stop();
  5971. thread.join();
  5972. ASSERT_FALSE(svr.is_running());
  5973. });
  5974. svr.wait_until_ready();
  5975. Client cli(HOST, PORT);
  5976. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5977. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5978. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5979. // A '?' after the '#' belongs to the fragment, not to the query.
  5980. Request req;
  5981. req.method = "GET";
  5982. req.path = "/hi#f?x=1";
  5983. req.params.emplace("a", "1");
  5984. Response res;
  5985. auto error = Error::Success;
  5986. EXPECT_TRUE(cli.send(req, res, error));
  5987. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5988. "/hi?a=1"}),
  5989. targets);
  5990. }
  5991. TEST(HeaderWriter, SetHeaderWriter) {
  5992. Server svr;
  5993. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5994. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5995. return detail::write_headers(strm, hdrs);
  5996. });
  5997. svr.Get("/hi", [](const Request &req, Response &res) {
  5998. auto it = req.headers.find("CustomClientHeader");
  5999. EXPECT_TRUE(it != req.headers.end());
  6000. EXPECT_EQ(it->second, "CustomClientValue");
  6001. res.set_content("Hello World!\n", "text/plain");
  6002. });
  6003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6004. auto se = detail::scope_exit([&] {
  6005. svr.stop();
  6006. thread.join();
  6007. ASSERT_FALSE(svr.is_running());
  6008. });
  6009. svr.wait_until_ready();
  6010. {
  6011. Client cli(HOST, PORT);
  6012. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  6013. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  6014. return detail::write_headers(strm, hdrs);
  6015. });
  6016. auto res = cli.Get("/hi");
  6017. EXPECT_TRUE(res);
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. auto it = res->headers.find("CustomServerHeader");
  6020. EXPECT_TRUE(it != res->headers.end());
  6021. EXPECT_EQ(it->second, "CustomServerValue");
  6022. }
  6023. }
  6024. class ServerTest : public ::testing::Test {
  6025. protected:
  6026. ServerTest()
  6027. : cli_(HOST, PORT)
  6028. #ifdef CPPHTTPLIB_SSL_ENABLED
  6029. ,
  6030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6031. #endif
  6032. {
  6033. #ifdef CPPHTTPLIB_SSL_ENABLED
  6034. cli_.enable_server_certificate_verification(false);
  6035. #endif
  6036. // Allow LARGE_DATA (100MB) responses
  6037. cli_.set_payload_max_length(200 * 1024 * 1024);
  6038. }
  6039. virtual void SetUp() {
  6040. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  6041. svr_.set_payload_max_length(200 * 1024 * 1024);
  6042. svr_.set_mount_point("/", "./www");
  6043. svr_.set_mount_point("/mount", "./www2");
  6044. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  6045. svr_.Get("/hi",
  6046. [&](const Request & /*req*/, Response &res) {
  6047. res.set_content("Hello World!", "text/plain");
  6048. })
  6049. .Get("/file_content",
  6050. [&](const Request & /*req*/, Response &res) {
  6051. res.set_file_content("./www/dir/test.html");
  6052. })
  6053. .Get("/file_content_with_content_type",
  6054. [&](const Request & /*req*/, Response &res) {
  6055. res.set_file_content("./www/file", "text/plain");
  6056. })
  6057. .Get("/invalid_file_content",
  6058. [&](const Request & /*req*/, Response &res) {
  6059. res.set_file_content("./www/dir/invalid_file_path");
  6060. })
  6061. .Get("/http_response_splitting",
  6062. [&](const Request & /*req*/, Response &res) {
  6063. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6064. EXPECT_EQ(0U, res.headers.size());
  6065. EXPECT_FALSE(res.has_header("a"));
  6066. res.set_header("a", "1\nSet-Cookie: a=1");
  6067. EXPECT_EQ(0U, res.headers.size());
  6068. EXPECT_FALSE(res.has_header("a"));
  6069. res.set_header("a", "1\rSet-Cookie: a=1");
  6070. EXPECT_EQ(0U, res.headers.size());
  6071. EXPECT_FALSE(res.has_header("a"));
  6072. res.set_header("a\r\nb", "0");
  6073. EXPECT_EQ(0U, res.headers.size());
  6074. EXPECT_FALSE(res.has_header("a"));
  6075. res.set_header("a\rb", "0");
  6076. EXPECT_EQ(0U, res.headers.size());
  6077. EXPECT_FALSE(res.has_header("a"));
  6078. res.set_header("a\nb", "0");
  6079. EXPECT_EQ(0U, res.headers.size());
  6080. EXPECT_FALSE(res.has_header("a"));
  6081. res.set_redirect("1\r\nSet-Cookie: a=1");
  6082. EXPECT_EQ(0U, res.headers.size());
  6083. EXPECT_FALSE(res.has_header("Location"));
  6084. })
  6085. .Get("/slow",
  6086. [&](const Request & /*req*/, Response &res) {
  6087. std::this_thread::sleep_for(std::chrono::seconds(4));
  6088. res.set_content("slow", "text/plain");
  6089. })
  6090. #if 0
  6091. .Post("/slowpost",
  6092. [&](const Request & /*req*/, Response &res) {
  6093. std::this_thread::sleep_for(std::chrono::seconds(2));
  6094. res.set_content("slow", "text/plain");
  6095. })
  6096. #endif
  6097. .Get("/remote_addr",
  6098. [&](const Request &req, Response &res) {
  6099. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6100. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6101. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6102. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6103. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6104. #endif
  6105. res.set_content(req.remote_addr, "text/plain");
  6106. })
  6107. .Get("/local_addr",
  6108. [&](const Request &req, Response &res) {
  6109. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6110. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6111. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6112. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6113. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6114. #endif
  6115. auto local_addr = req.local_addr;
  6116. auto local_port = std::to_string(req.local_port);
  6117. res.set_content(local_addr.append(":").append(local_port),
  6118. "text/plain");
  6119. })
  6120. .Get("/endwith%",
  6121. [&](const Request & /*req*/, Response &res) {
  6122. res.set_content("Hello World!", "text/plain");
  6123. })
  6124. .Get("/a\\+\\+b",
  6125. [&](const Request &req, Response &res) {
  6126. ASSERT_TRUE(req.has_param("a +b"));
  6127. auto val = req.get_param_value("a +b");
  6128. res.set_content(val, "text/plain");
  6129. })
  6130. .Get("/", [&](const Request & /*req*/,
  6131. Response &res) { res.set_redirect("/hi"); })
  6132. .Post("/1",
  6133. [](const Request & /*req*/, Response &res) {
  6134. res.set_redirect("/2", StatusCode::SeeOther_303);
  6135. })
  6136. .Get("/2",
  6137. [](const Request & /*req*/, Response &res) {
  6138. res.set_content("redirected.", "text/plain");
  6139. res.status = StatusCode::OK_200;
  6140. })
  6141. .Post("/person",
  6142. [&](const Request &req, Response &res) {
  6143. if (req.has_param("name") && req.has_param("note")) {
  6144. persons_[req.get_param_value("name")] =
  6145. req.get_param_value("note");
  6146. } else {
  6147. res.status = StatusCode::BadRequest_400;
  6148. }
  6149. })
  6150. .Put("/person",
  6151. [&](const Request &req, Response &res) {
  6152. if (req.has_param("name") && req.has_param("note")) {
  6153. persons_[req.get_param_value("name")] =
  6154. req.get_param_value("note");
  6155. } else {
  6156. res.status = StatusCode::BadRequest_400;
  6157. }
  6158. })
  6159. .Get("/person/(.*)",
  6160. [&](const Request &req, Response &res) {
  6161. string name = req.matches[1];
  6162. if (persons_.find(name) != persons_.end()) {
  6163. auto note = persons_[name];
  6164. res.set_content(note, "text/plain");
  6165. } else {
  6166. res.status = StatusCode::NotFound_404;
  6167. }
  6168. })
  6169. .Delete("/person",
  6170. [&](const Request &req, Response &res) {
  6171. if (req.has_param("name")) {
  6172. string name = req.get_param_value("name");
  6173. if (persons_.find(name) != persons_.end()) {
  6174. persons_.erase(name);
  6175. res.set_content("DELETED", "text/plain");
  6176. } else {
  6177. res.status = StatusCode::NotFound_404;
  6178. }
  6179. } else {
  6180. res.status = StatusCode::BadRequest_400;
  6181. }
  6182. })
  6183. .Post("/x-www-form-urlencoded-json",
  6184. [&](const Request &req, Response &res) {
  6185. auto json = req.get_param_value("json");
  6186. ASSERT_EQ(JSON_DATA, json);
  6187. res.set_content(json, "appliation/json");
  6188. res.status = StatusCode::OK_200;
  6189. })
  6190. .Get("/streamed-chunked",
  6191. [&](const Request & /*req*/, Response &res) {
  6192. res.set_chunked_content_provider(
  6193. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6194. sink.os << "123";
  6195. sink.os << "456";
  6196. sink.os << "789";
  6197. sink.done();
  6198. return true;
  6199. });
  6200. })
  6201. .Get("/streamed-chunked-with-prohibited-trailer",
  6202. [&](const Request & /*req*/, Response &res) {
  6203. auto i = new int(0);
  6204. // Declare both a prohibited trailer (Content-Length) and an
  6205. // allowed one
  6206. res.set_header("Trailer", "Content-Length, X-Allowed");
  6207. res.set_chunked_content_provider(
  6208. "text/plain",
  6209. [i](size_t /*offset*/, DataSink &sink) {
  6210. switch (*i) {
  6211. case 0: sink.os << "123"; break;
  6212. case 1: sink.os << "456"; break;
  6213. case 2: sink.os << "789"; break;
  6214. case 3: {
  6215. sink.done_with_trailer(
  6216. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6217. } break;
  6218. }
  6219. (*i)++;
  6220. return true;
  6221. },
  6222. [i](bool success) {
  6223. EXPECT_TRUE(success);
  6224. delete i;
  6225. });
  6226. })
  6227. .Get("/streamed-chunked2",
  6228. [&](const Request & /*req*/, Response &res) {
  6229. auto i = new int(0);
  6230. res.set_chunked_content_provider(
  6231. "text/plain",
  6232. [i](size_t /*offset*/, DataSink &sink) {
  6233. switch (*i) {
  6234. case 0: sink.os << "123"; break;
  6235. case 1: sink.os << "456"; break;
  6236. case 2: sink.os << "789"; break;
  6237. case 3: sink.done(); break;
  6238. }
  6239. (*i)++;
  6240. return true;
  6241. },
  6242. [i](bool success) {
  6243. EXPECT_TRUE(success);
  6244. delete i;
  6245. });
  6246. })
  6247. .Get("/streamed-chunked-with-trailer",
  6248. [&](const Request & /*req*/, Response &res) {
  6249. auto i = new int(0);
  6250. res.set_header("Trailer", "Dummy1, Dummy2");
  6251. res.set_chunked_content_provider(
  6252. "text/plain",
  6253. [i](size_t /*offset*/, DataSink &sink) {
  6254. switch (*i) {
  6255. case 0: sink.os << "123"; break;
  6256. case 1: sink.os << "456"; break;
  6257. case 2: sink.os << "789"; break;
  6258. case 3: {
  6259. sink.done_with_trailer(
  6260. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6261. } break;
  6262. }
  6263. (*i)++;
  6264. return true;
  6265. },
  6266. [i](bool success) {
  6267. EXPECT_TRUE(success);
  6268. delete i;
  6269. });
  6270. })
  6271. .Get("/streamed",
  6272. [&](const Request & /*req*/, Response &res) {
  6273. res.set_content_provider(
  6274. 6, "text/plain",
  6275. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6276. sink.os << (offset < 3 ? "a" : "b");
  6277. return true;
  6278. });
  6279. })
  6280. .Get("/streamed-without-length",
  6281. [&](const Request & /*req*/, Response &res) {
  6282. auto data = new std::string("abcdefg");
  6283. res.set_content_provider(
  6284. "text/plain",
  6285. [data](size_t offset, DataSink &sink) {
  6286. if (offset < data->size()) {
  6287. sink.os << data->substr(offset);
  6288. }
  6289. sink.done();
  6290. return true;
  6291. },
  6292. [data](bool success) {
  6293. EXPECT_TRUE(success);
  6294. delete data;
  6295. });
  6296. })
  6297. .Get("/streamed-with-range",
  6298. [&](const Request &req, Response &res) {
  6299. auto data = new std::string("abcdefg");
  6300. // An explicit status keeps the server from picking the 206 it
  6301. // would otherwise choose for a ranged request, so the response
  6302. // is not a partial representation.
  6303. auto status = req.get_param_value("status");
  6304. if (status == "200") {
  6305. res.status = StatusCode::OK_200;
  6306. } else if (status == "403") {
  6307. res.status = StatusCode::Forbidden_403;
  6308. }
  6309. res.set_content_provider(
  6310. data->size(), "text/plain",
  6311. [data](size_t offset, size_t length, DataSink &sink) {
  6312. size_t DATA_CHUNK_SIZE = 4;
  6313. const auto &d = *data;
  6314. auto out_len =
  6315. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6316. auto ret =
  6317. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6318. EXPECT_TRUE(ret);
  6319. return true;
  6320. },
  6321. [data, &req](bool success) {
  6322. EXPECT_EQ(success, !req.has_param("error"));
  6323. delete data;
  6324. });
  6325. })
  6326. .Get("/streamed-cancel",
  6327. [&](const Request & /*req*/, Response &res) {
  6328. res.set_content_provider(
  6329. size_t(-1), "text/plain",
  6330. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6331. sink.os << "data_chunk";
  6332. return true;
  6333. });
  6334. })
  6335. .Get("/regex-with-delimiter",
  6336. [&](const Request &req, Response & /*res*/) {
  6337. ASSERT_TRUE(req.has_param("key"));
  6338. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6339. })
  6340. .Get("/with-range",
  6341. [&](const Request & /*req*/, Response &res) {
  6342. res.set_content("abcdefg", "text/plain");
  6343. })
  6344. .Get("/test-start-time",
  6345. [&](const Request &req, Response & /*res*/) {
  6346. EXPECT_NE(req.start_time_,
  6347. std::chrono::steady_clock::time_point::min());
  6348. })
  6349. .Get("/with-range-customized-response",
  6350. [&](const Request & /*req*/, Response &res) {
  6351. res.status = StatusCode::BadRequest_400;
  6352. res.set_content(JSON_DATA, "application/json");
  6353. })
  6354. .Post("/chunked",
  6355. [&](const Request &req, Response & /*res*/) {
  6356. EXPECT_EQ(req.body, "dechunked post body");
  6357. })
  6358. .Post("/large-chunked",
  6359. [&](const Request &req, Response & /*res*/) {
  6360. std::string expected(6 * 30 * 1024u, 'a');
  6361. EXPECT_EQ(req.body, expected);
  6362. })
  6363. .Post("/multipart",
  6364. [&](const Request &req, Response & /*res*/) {
  6365. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6366. req.form.get_field_count("text2") +
  6367. req.form.get_field_count("file3") +
  6368. req.form.get_field_count("file4"));
  6369. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6370. req.form.get_file_count("file2"));
  6371. ASSERT_TRUE(!req.form.has_file("???"));
  6372. ASSERT_TRUE(!req.form.has_field("???"));
  6373. ASSERT_TRUE(req.body.empty());
  6374. {
  6375. const auto &text = req.form.get_field("text1");
  6376. EXPECT_EQ("text default", text);
  6377. }
  6378. {
  6379. const auto &text = req.form.get_field("text2");
  6380. EXPECT_EQ("aωb", text);
  6381. }
  6382. {
  6383. const auto &file = req.form.get_file("file1");
  6384. EXPECT_EQ("hello.txt", file.filename);
  6385. EXPECT_EQ("text/plain", file.content_type);
  6386. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6387. }
  6388. {
  6389. const auto &file = req.form.get_file("file2");
  6390. EXPECT_EQ("world.json", file.filename);
  6391. EXPECT_EQ("application/json", file.content_type);
  6392. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6393. }
  6394. {
  6395. const auto &text = req.form.get_field("file3");
  6396. EXPECT_EQ(0u, text.size());
  6397. }
  6398. {
  6399. const auto &text = req.form.get_field("file4");
  6400. EXPECT_EQ(0u, text.size());
  6401. }
  6402. })
  6403. .Post("/multipart/multi_file_values",
  6404. [&](const Request &req, Response & /*res*/) {
  6405. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6406. req.form.get_field_count("multi_text1"));
  6407. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6408. ASSERT_TRUE(!req.form.has_file("???"));
  6409. ASSERT_TRUE(!req.form.has_field("???"));
  6410. ASSERT_TRUE(req.body.empty());
  6411. {
  6412. const auto &text = req.form.get_field("text");
  6413. EXPECT_EQ("default text", text);
  6414. }
  6415. {
  6416. const auto &text1_values = req.form.get_fields("multi_text1");
  6417. EXPECT_EQ(2u, text1_values.size());
  6418. EXPECT_EQ("aaaaa", text1_values[0]);
  6419. EXPECT_EQ("bbbbb", text1_values[1]);
  6420. }
  6421. {
  6422. const auto &file1_values = req.form.get_files("multi_file1");
  6423. EXPECT_EQ(2u, file1_values.size());
  6424. auto file1 = file1_values[0];
  6425. EXPECT_EQ(file1.filename, "hello.txt");
  6426. EXPECT_EQ(file1.content_type, "text/plain");
  6427. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6428. auto file2 = file1_values[1];
  6429. EXPECT_EQ(file2.filename, "world.json");
  6430. EXPECT_EQ(file2.content_type, "application/json");
  6431. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6432. }
  6433. })
  6434. .Post("/empty",
  6435. [&](const Request &req, Response &res) {
  6436. EXPECT_EQ(req.body, "");
  6437. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6438. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6439. res.set_content("empty", "text/plain");
  6440. })
  6441. .Post("/empty-no-content-type",
  6442. [&](const Request &req, Response &res) {
  6443. EXPECT_EQ(req.body, "");
  6444. EXPECT_FALSE(req.has_header("Content-Type"));
  6445. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6446. res.set_content("empty-no-content-type", "text/plain");
  6447. })
  6448. .Post("/path-only",
  6449. [&](const Request &req, Response &res) {
  6450. EXPECT_EQ(req.body, "");
  6451. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6452. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6453. res.set_content("path-only", "text/plain");
  6454. })
  6455. .Post("/path-headers-only",
  6456. [&](const Request &req, Response &res) {
  6457. EXPECT_EQ(req.body, "");
  6458. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6459. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6460. EXPECT_EQ("world", req.get_header_value("hello"));
  6461. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6462. res.set_content("path-headers-only", "text/plain");
  6463. })
  6464. .Post("/post-large",
  6465. [&](const Request &req, Response &res) {
  6466. EXPECT_EQ(req.body, LARGE_DATA);
  6467. res.set_content(req.body, "text/plain");
  6468. })
  6469. .Post("/post-loopback",
  6470. [&](const Request &, Response &res,
  6471. ContentReader const &content_reader) {
  6472. std::string body;
  6473. content_reader([&](const char *data, size_t data_length) {
  6474. body.append(data, data_length);
  6475. return true;
  6476. });
  6477. res.set_content(body, "text/plain");
  6478. })
  6479. .Put("/put-loopback",
  6480. [&](const Request &, Response &res,
  6481. ContentReader const &content_reader) {
  6482. std::string body;
  6483. content_reader([&](const char *data, size_t data_length) {
  6484. body.append(data, data_length);
  6485. return true;
  6486. });
  6487. res.set_content(body, "text/plain");
  6488. })
  6489. .Patch("/patch-loopback",
  6490. [&](const Request &, Response &res,
  6491. ContentReader const &content_reader) {
  6492. std::string body;
  6493. content_reader([&](const char *data, size_t data_length) {
  6494. body.append(data, data_length);
  6495. return true;
  6496. });
  6497. res.set_content(body, "text/plain");
  6498. })
  6499. .Put("/empty-no-content-type",
  6500. [&](const Request &req, Response &res) {
  6501. EXPECT_EQ(req.body, "");
  6502. EXPECT_FALSE(req.has_header("Content-Type"));
  6503. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6504. res.set_content("empty-no-content-type", "text/plain");
  6505. })
  6506. .Put("/put",
  6507. [&](const Request &req, Response &res) {
  6508. EXPECT_EQ(req.body, "PUT");
  6509. res.set_content(req.body, "text/plain");
  6510. })
  6511. .Put("/put-large",
  6512. [&](const Request &req, Response &res) {
  6513. EXPECT_EQ(req.body, LARGE_DATA);
  6514. res.set_content(req.body, "text/plain");
  6515. })
  6516. .Patch("/patch",
  6517. [&](const Request &req, Response &res) {
  6518. EXPECT_EQ(req.body, "PATCH");
  6519. res.set_content(req.body, "text/plain");
  6520. })
  6521. .Delete("/delete",
  6522. [&](const Request & /*req*/, Response &res) {
  6523. res.set_content("DELETE", "text/plain");
  6524. })
  6525. .Delete("/delete-body",
  6526. [&](const Request &req, Response &res) {
  6527. EXPECT_EQ(req.body, "content");
  6528. res.set_content(req.body, "text/plain");
  6529. })
  6530. .Options(R"(\*)",
  6531. [&](const Request & /*req*/, Response &res) {
  6532. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6533. })
  6534. .CustomRoute("PROPFIND", "/dav/:id",
  6535. [&](const Request &req, Response &res) {
  6536. res.set_header("x-body-size",
  6537. std::to_string(req.body.size()));
  6538. res.set_header("x-matched-route", req.matched_route);
  6539. res.set_header("x-dav-id", req.path_params.at("id"));
  6540. res.status = StatusCode::MultiStatus_207;
  6541. res.set_content(req.body, "application/xml");
  6542. })
  6543. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6544. [&](const Request &req, Response &res) {
  6545. res.set_header("x-dav-match", req.matches[1]);
  6546. res.status = StatusCode::MultiStatus_207;
  6547. })
  6548. .CustomRoute("MKCOL", "/dav-mkcol",
  6549. [&](const Request &req, Response &res) {
  6550. EXPECT_TRUE(req.body.empty());
  6551. res.status = StatusCode::Created_201;
  6552. })
  6553. .CustomRoute(
  6554. "REPORT", "/dav-report",
  6555. [&](const Request & /*req*/, Response &res,
  6556. const ContentReader &content_reader) {
  6557. std::string body;
  6558. content_reader([&](const char *data, size_t data_length) {
  6559. body.append(data, data_length);
  6560. return true;
  6561. });
  6562. res.set_header("x-body-size", std::to_string(body.size()));
  6563. res.status = StatusCode::MultiStatus_207;
  6564. res.set_content(body, "application/xml");
  6565. })
  6566. .Get("/request-target",
  6567. [&](const Request &req, Response & /*res*/) {
  6568. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6569. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6570. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6571. })
  6572. .Get("/long-query-value",
  6573. [&](const Request &req, Response & /*res*/) {
  6574. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6575. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6576. })
  6577. .Get("/too-long-query-value",
  6578. [&](const Request &req, Response & /*res*/) {
  6579. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6580. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6581. })
  6582. .Get("/array-param",
  6583. [&](const Request &req, Response & /*res*/) {
  6584. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6585. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6586. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6587. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6588. })
  6589. .Get("/array-param-values",
  6590. [&](const Request &req, Response & /*res*/) {
  6591. auto values = req.get_param_values("array");
  6592. EXPECT_EQ(3u, values.size());
  6593. EXPECT_EQ("value1", values[0]);
  6594. EXPECT_EQ("value2", values[1]);
  6595. EXPECT_EQ("value3", values[2]);
  6596. auto empty = req.get_param_values("nonexistent");
  6597. EXPECT_TRUE(empty.empty());
  6598. })
  6599. .Post("/validate-no-multiple-headers",
  6600. [&](const Request &req, Response & /*res*/) {
  6601. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6602. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6603. })
  6604. .Post("/content_receiver",
  6605. [&](const Request &req, Response &res,
  6606. const ContentReader &content_reader) {
  6607. if (req.is_multipart_form_data()) {
  6608. std::vector<FormData> items;
  6609. content_reader(
  6610. [&](const FormData &file) {
  6611. items.push_back(file);
  6612. return true;
  6613. },
  6614. [&](const char *data, size_t data_length) {
  6615. items.back().content.append(data, data_length);
  6616. return true;
  6617. });
  6618. EXPECT_EQ(5u, items.size());
  6619. {
  6620. const auto &file = get_file_value(items, "text1");
  6621. EXPECT_TRUE(file.filename.empty());
  6622. EXPECT_EQ("text default", file.content);
  6623. }
  6624. {
  6625. const auto &file = get_file_value(items, "text2");
  6626. EXPECT_TRUE(file.filename.empty());
  6627. EXPECT_EQ("aωb", file.content);
  6628. }
  6629. {
  6630. const auto &file = get_file_value(items, "file1");
  6631. EXPECT_EQ("hello.txt", file.filename);
  6632. EXPECT_EQ("text/plain", file.content_type);
  6633. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6634. }
  6635. {
  6636. const auto &file = get_file_value(items, "file2");
  6637. EXPECT_EQ("world.json", file.filename);
  6638. EXPECT_EQ("application/json", file.content_type);
  6639. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6640. }
  6641. {
  6642. const auto &file = get_file_value(items, "file3");
  6643. EXPECT_TRUE(file.filename.empty());
  6644. EXPECT_EQ("application/octet-stream", file.content_type);
  6645. EXPECT_EQ(0u, file.content.size());
  6646. }
  6647. } else {
  6648. std::string body;
  6649. content_reader([&](const char *data, size_t data_length) {
  6650. EXPECT_EQ(7U, data_length);
  6651. body.append(data, data_length);
  6652. return true;
  6653. });
  6654. EXPECT_EQ(body, "content");
  6655. res.set_content(body, "text/plain");
  6656. }
  6657. })
  6658. .Put("/content_receiver",
  6659. [&](const Request & /*req*/, Response &res,
  6660. const ContentReader &content_reader) {
  6661. std::string body;
  6662. content_reader([&](const char *data, size_t data_length) {
  6663. body.append(data, data_length);
  6664. return true;
  6665. });
  6666. EXPECT_EQ(body, "content");
  6667. res.set_content(body, "text/plain");
  6668. })
  6669. .Patch("/content_receiver",
  6670. [&](const Request & /*req*/, Response &res,
  6671. const ContentReader &content_reader) {
  6672. std::string body;
  6673. content_reader([&](const char *data, size_t data_length) {
  6674. body.append(data, data_length);
  6675. return true;
  6676. });
  6677. EXPECT_EQ(body, "content");
  6678. res.set_content(body, "text/plain");
  6679. })
  6680. .Post("/query-string-and-body",
  6681. [&](const Request &req, Response & /*res*/) {
  6682. ASSERT_TRUE(req.has_param("key"));
  6683. EXPECT_EQ(req.get_param_value("key"), "value");
  6684. EXPECT_EQ(req.body, "content");
  6685. })
  6686. .Get("/last-request",
  6687. [&](const Request &req, Response & /*res*/) {
  6688. EXPECT_EQ("close", req.get_header_value("Connection"));
  6689. })
  6690. .Get(R"(/redirect/(\d+))",
  6691. [&](const Request &req, Response &res) {
  6692. auto num = std::stoi(req.matches[1]) + 1;
  6693. std::string url = "/redirect/" + std::to_string(num);
  6694. res.set_redirect(url);
  6695. })
  6696. .Post("/binary",
  6697. [&](const Request &req, Response &res) {
  6698. EXPECT_EQ(4U, req.body.size());
  6699. EXPECT_EQ("application/octet-stream",
  6700. req.get_header_value("Content-Type"));
  6701. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6702. res.set_content(req.body, "application/octet-stream");
  6703. })
  6704. .Put("/binary",
  6705. [&](const Request &req, Response &res) {
  6706. EXPECT_EQ(4U, req.body.size());
  6707. EXPECT_EQ("application/octet-stream",
  6708. req.get_header_value("Content-Type"));
  6709. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6710. res.set_content(req.body, "application/octet-stream");
  6711. })
  6712. .Patch("/binary",
  6713. [&](const Request &req, Response &res) {
  6714. EXPECT_EQ(4U, req.body.size());
  6715. EXPECT_EQ("application/octet-stream",
  6716. req.get_header_value("Content-Type"));
  6717. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6718. res.set_content(req.body, "application/octet-stream");
  6719. })
  6720. .Delete("/binary",
  6721. [&](const Request &req, Response &res) {
  6722. EXPECT_EQ(4U, req.body.size());
  6723. EXPECT_EQ("application/octet-stream",
  6724. req.get_header_value("Content-Type"));
  6725. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6726. res.set_content(req.body, "application/octet-stream");
  6727. })
  6728. .Get("/issue1772",
  6729. [&](const Request & /*req*/, Response &res) {
  6730. res.status = 401;
  6731. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6732. })
  6733. .Delete("/issue609",
  6734. [](const httplib::Request &, httplib::Response &res,
  6735. const httplib::ContentReader &) {
  6736. res.set_content("ok", "text/plain");
  6737. })
  6738. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6739. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6740. .Get("/compress",
  6741. [&](const Request & /*req*/, Response &res) {
  6742. res.set_content(
  6743. "12345678901234567890123456789012345678901234567890123456789"
  6744. "01234567890123456789012345678901234567890",
  6745. "text/plain");
  6746. })
  6747. .Get("/compress-with-charset",
  6748. [&](const Request & /*req*/, Response &res) {
  6749. res.set_content(
  6750. "12345678901234567890123456789012345678901234567890123456789"
  6751. "01234567890123456789012345678901234567890",
  6752. "application/json; charset=utf-8");
  6753. })
  6754. .Get("/nocompress",
  6755. [&](const Request & /*req*/, Response &res) {
  6756. res.set_content(
  6757. "12345678901234567890123456789012345678901234567890123456789"
  6758. "01234567890123456789012345678901234567890",
  6759. "application/octet-stream");
  6760. })
  6761. .Post("/compress-multipart",
  6762. [&](const Request &req, Response & /*res*/) {
  6763. EXPECT_EQ(2u, req.form.fields.size());
  6764. ASSERT_TRUE(!req.form.has_field("???"));
  6765. {
  6766. const auto &text = req.form.get_field("key1");
  6767. EXPECT_EQ("test", text);
  6768. }
  6769. {
  6770. const auto &text = req.form.get_field("key2");
  6771. EXPECT_EQ("--abcdefg123", text);
  6772. }
  6773. })
  6774. #endif
  6775. ;
  6776. persons_["john"] = "programmer";
  6777. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6778. svr_.wait_until_ready();
  6779. }
  6780. virtual void TearDown() {
  6781. svr_.stop();
  6782. if (!request_threads_.empty()) {
  6783. std::this_thread::sleep_for(std::chrono::seconds(1));
  6784. for (auto &t : request_threads_) {
  6785. t.join();
  6786. }
  6787. }
  6788. t_.join();
  6789. }
  6790. map<string, string> persons_;
  6791. #ifdef CPPHTTPLIB_SSL_ENABLED
  6792. SSLClient cli_;
  6793. SSLServer svr_;
  6794. #else
  6795. Client cli_;
  6796. Server svr_;
  6797. #endif
  6798. thread t_;
  6799. std::vector<thread> request_threads_;
  6800. };
  6801. TEST_F(ServerTest, GetMethod200) {
  6802. auto res = cli_.Get("/hi");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ("HTTP/1.1", res->version);
  6805. EXPECT_EQ(StatusCode::OK_200, res->status);
  6806. EXPECT_EQ("OK", res->reason);
  6807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6808. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6809. EXPECT_EQ("Hello World!", res->body);
  6810. }
  6811. TEST_F(ServerTest, GetEmptyFile) {
  6812. auto res = cli_.Get("/empty_file");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6816. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6817. EXPECT_EQ("", res->body);
  6818. }
  6819. TEST_F(ServerTest, GetFileContent) {
  6820. auto res = cli_.Get("/file_content");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6824. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6825. EXPECT_EQ("test.html", res->body);
  6826. }
  6827. TEST_F(ServerTest, GetFileContentWithRange) {
  6828. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6831. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6832. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6833. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6834. EXPECT_EQ("est", res->body);
  6835. }
  6836. TEST_F(ServerTest, GetFileContentWithContentType) {
  6837. auto res = cli_.Get("/file_content_with_content_type");
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6841. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6842. EXPECT_EQ("file\n", res->body);
  6843. }
  6844. TEST_F(ServerTest, GetInvalidFileContent) {
  6845. auto res = cli_.Get("/invalid_file_content");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6848. }
  6849. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6850. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ("HTTP/1.1", res->version);
  6853. EXPECT_EQ(StatusCode::OK_200, res->status);
  6854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6855. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6856. EXPECT_EQ("Hello World!", res->body);
  6857. }
  6858. TEST_F(ServerTest, GetMethod302) {
  6859. auto res = cli_.Get("/");
  6860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6861. EXPECT_EQ(StatusCode::Found_302, res->status);
  6862. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6863. }
  6864. TEST_F(ServerTest, GetMethod302Redirect) {
  6865. cli_.set_follow_location(true);
  6866. auto res = cli_.Get("/");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. EXPECT_EQ("Hello World!", res->body);
  6870. EXPECT_EQ("/hi", res->location);
  6871. }
  6872. TEST_F(ServerTest, GetMethod404) {
  6873. auto res = cli_.Get("/invalid");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6876. }
  6877. TEST_F(ServerTest, HeadMethod200) {
  6878. auto res = cli_.Head("/hi");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6882. EXPECT_TRUE(res->body.empty());
  6883. }
  6884. TEST_F(ServerTest, HeadMethod200Static) {
  6885. auto res = cli_.Head("/mount/dir/index.html");
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::OK_200, res->status);
  6888. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6889. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6890. EXPECT_TRUE(res->body.empty());
  6891. }
  6892. TEST_F(ServerTest, HeadMethod404) {
  6893. auto res = cli_.Head("/invalid");
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6896. EXPECT_TRUE(res->body.empty());
  6897. }
  6898. TEST_F(ServerTest, GetMethodPersonJohn) {
  6899. auto res = cli_.Get("/person/john");
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. EXPECT_EQ(StatusCode::OK_200, res->status);
  6902. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6903. EXPECT_EQ("programmer", res->body);
  6904. }
  6905. TEST_F(ServerTest, PostMethod1) {
  6906. auto res = cli_.Get("/person/john1");
  6907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6908. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6909. res = cli_.Post("/person", "name=john1&note=coder",
  6910. "application/x-www-form-urlencoded");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. res = cli_.Get("/person/john1");
  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("coder", res->body);
  6918. }
  6919. TEST_F(ServerTest, PostMethod2) {
  6920. auto res = cli_.Get("/person/john2");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6923. Params params;
  6924. params.emplace("name", "john2");
  6925. params.emplace("note", "coder");
  6926. res = cli_.Post("/person", params);
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::OK_200, res->status);
  6929. res = cli_.Get("/person/john2");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. ASSERT_EQ(StatusCode::OK_200, res->status);
  6932. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6933. ASSERT_EQ("coder", res->body);
  6934. }
  6935. TEST_F(ServerTest, PutMethod3) {
  6936. auto res = cli_.Get("/person/john3");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6939. Params params;
  6940. params.emplace("name", "john3");
  6941. params.emplace("note", "coder");
  6942. res = cli_.Put("/person", params);
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. res = cli_.Get("/person/john3");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. ASSERT_EQ(StatusCode::OK_200, res->status);
  6948. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6949. ASSERT_EQ("coder", res->body);
  6950. }
  6951. TEST_F(ServerTest, DeleteMethod1) {
  6952. auto res = cli_.Get("/person/john4");
  6953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6954. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6955. Params params;
  6956. params.emplace("name", "john4");
  6957. params.emplace("note", "coder");
  6958. res = cli_.Post("/person", params);
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. ASSERT_EQ(StatusCode::OK_200, res->status);
  6961. res = cli_.Get("/person/john4");
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. ASSERT_EQ(StatusCode::OK_200, res->status);
  6964. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6965. ASSERT_EQ("coder", res->body);
  6966. Params delete_params;
  6967. delete_params.emplace("name", "john4");
  6968. res = cli_.Delete("/person", delete_params);
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. ASSERT_EQ(StatusCode::OK_200, res->status);
  6971. ASSERT_EQ("DELETED", res->body);
  6972. res = cli_.Get("/person/john4");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6975. }
  6976. TEST_F(ServerTest, DeleteMethod2) {
  6977. auto res = cli_.Get("/person/john5");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6980. Params params;
  6981. params.emplace("name", "john5");
  6982. params.emplace("note", "developer");
  6983. res = cli_.Post("/person", params);
  6984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6985. ASSERT_EQ(StatusCode::OK_200, res->status);
  6986. res = cli_.Get("/person/john5");
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. ASSERT_EQ(StatusCode::OK_200, res->status);
  6989. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6990. ASSERT_EQ("developer", res->body);
  6991. Params delete_params;
  6992. delete_params.emplace("name", "john5");
  6993. Headers headers;
  6994. headers.emplace("Custom-Header", "test-value");
  6995. res = cli_.Delete("/person", headers, delete_params);
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. ASSERT_EQ(StatusCode::OK_200, res->status);
  6998. ASSERT_EQ("DELETED", res->body);
  6999. res = cli_.Get("/person/john5");
  7000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7001. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7002. }
  7003. TEST_F(ServerTest, DeleteMethod3) {
  7004. auto res = cli_.Get("/person/john6");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7007. Params params;
  7008. params.emplace("name", "john6");
  7009. params.emplace("note", "tester");
  7010. res = cli_.Post("/person", params);
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. ASSERT_EQ(StatusCode::OK_200, res->status);
  7013. res = cli_.Get("/person/john6");
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. ASSERT_EQ(StatusCode::OK_200, res->status);
  7016. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  7017. ASSERT_EQ("tester", res->body);
  7018. Params delete_params;
  7019. delete_params.emplace("name", "john6");
  7020. Headers headers;
  7021. headers.emplace("Custom-Header", "test-value");
  7022. res = cli_.Delete("/person", headers, delete_params, nullptr);
  7023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7024. ASSERT_EQ(StatusCode::OK_200, res->status);
  7025. ASSERT_EQ("DELETED", res->body);
  7026. res = cli_.Get("/person/john6");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7029. }
  7030. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  7031. Params params;
  7032. params.emplace("json", JSON_DATA);
  7033. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. ASSERT_EQ(StatusCode::OK_200, res->status);
  7036. ASSERT_EQ(JSON_DATA, res->body);
  7037. }
  7038. TEST_F(ServerTest, PostEmptyContent) {
  7039. auto res = cli_.Post("/empty", "", "text/plain");
  7040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7041. ASSERT_EQ(StatusCode::OK_200, res->status);
  7042. ASSERT_EQ("empty", res->body);
  7043. }
  7044. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  7045. auto res = cli_.Post("/empty-no-content-type");
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. ASSERT_EQ(StatusCode::OK_200, res->status);
  7048. ASSERT_EQ("empty-no-content-type", res->body);
  7049. }
  7050. TEST_F(ServerTest, PostPathOnly) {
  7051. auto res = cli_.Post("/path-only");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. ASSERT_EQ(StatusCode::OK_200, res->status);
  7054. ASSERT_EQ("path-only", res->body);
  7055. }
  7056. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  7057. auto res = cli_.Post("/path-headers-only",
  7058. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. ASSERT_EQ(StatusCode::OK_200, res->status);
  7061. ASSERT_EQ("path-headers-only", res->body);
  7062. }
  7063. TEST_F(ServerTest, PostLarge) {
  7064. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. ASSERT_EQ(StatusCode::OK_200, res->status);
  7067. EXPECT_EQ(LARGE_DATA, res->body);
  7068. }
  7069. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7070. auto res = cli_.Put("/empty-no-content-type");
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. ASSERT_EQ(StatusCode::OK_200, res->status);
  7073. ASSERT_EQ("empty-no-content-type", res->body);
  7074. }
  7075. TEST_F(ServerTest, GetMethodDir) {
  7076. auto res = cli_.Get("/dir/");
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::OK_200, res->status);
  7079. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7080. auto body = R"(<html>
  7081. <head>
  7082. </head>
  7083. <body>
  7084. <a href="/dir/test.html">Test</a>
  7085. <a href="/hi">hi</a>
  7086. </body>
  7087. </html>
  7088. )";
  7089. EXPECT_EQ(body, res->body);
  7090. }
  7091. TEST_F(ServerTest, GetMethodDirTest) {
  7092. auto res = cli_.Get("/dir/test.html");
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. EXPECT_EQ(StatusCode::OK_200, res->status);
  7095. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7096. EXPECT_EQ("test.html", res->body);
  7097. }
  7098. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7099. auto res = cli_.Get("/dir/../dir/test.html");
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7102. }
  7103. TEST_F(ServerTest, GetMethodInvalidPath) {
  7104. auto res = cli_.Get("/dir/../test.html");
  7105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7106. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7107. }
  7108. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7109. auto res = cli_.Get("/../www/dir/test.html");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7112. }
  7113. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7114. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7117. }
  7118. TEST_F(ServerTest, GetMethodDirMountTest) {
  7119. auto res = cli_.Get("/mount/dir/test.html");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7123. EXPECT_EQ("test.html", res->body);
  7124. }
  7125. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7126. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7129. }
  7130. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7131. auto res = cli_.Get("/mount/dir/../test.html");
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7134. }
  7135. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7136. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7139. }
  7140. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7141. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7144. }
  7145. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7146. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7149. }
  7150. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7151. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7154. }
  7155. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7156. auto res = cli_.Get("/mount/dir");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7159. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7160. }
  7161. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7162. auto res = cli_.Get("//dir");
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7165. EXPECT_FALSE(res->has_header("Location"));
  7166. }
  7167. TEST_F(ServerTest, PostMethod303) {
  7168. auto res = cli_.Post("/1", "body", "text/plain");
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7171. EXPECT_EQ("/2", res->get_header_value("Location"));
  7172. }
  7173. TEST_F(ServerTest, PostMethod303Redirect) {
  7174. cli_.set_follow_location(true);
  7175. auto res = cli_.Post("/1", "body", "text/plain");
  7176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7177. EXPECT_EQ(StatusCode::OK_200, res->status);
  7178. EXPECT_EQ("redirected.", res->body);
  7179. EXPECT_EQ("/2", res->location);
  7180. }
  7181. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7182. auto res = cli_.Get("/dir/test.abcde");
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7186. EXPECT_EQ("abcde", res->body);
  7187. }
  7188. TEST_F(ServerTest, StaticFileRange) {
  7189. auto res =
  7190. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7193. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7194. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7195. EXPECT_EQ(true, res->has_header("Content-Range"));
  7196. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7197. EXPECT_EQ(std::string("cd"), res->body);
  7198. }
  7199. TEST_F(ServerTest, StaticFileRanges) {
  7200. auto res = cli_.Get("/dir/test.abcde",
  7201. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7204. EXPECT_TRUE(
  7205. res->get_header_value("Content-Type")
  7206. .find(
  7207. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7208. 0);
  7209. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7210. }
  7211. TEST_F(ServerTest, StaticFileRangeHead) {
  7212. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7215. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7216. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7217. EXPECT_EQ(true, res->has_header("Content-Range"));
  7218. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7219. }
  7220. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7221. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7225. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7226. EXPECT_EQ(true, res->has_header("Content-Range"));
  7227. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7228. res->get_header_value("Content-Range"));
  7229. EXPECT_EQ("LAST\n", res->body);
  7230. }
  7231. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7232. auto res =
  7233. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7237. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7238. EXPECT_EQ(true, res->has_header("Content-Range"));
  7239. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7240. }
  7241. TEST_F(ServerTest, StaticFileBigFile) {
  7242. auto res = cli_.Get("/dir/1MB.txt");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7246. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7247. }
  7248. TEST_F(ServerTest, InvalidBaseDirMount) {
  7249. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7250. }
  7251. TEST_F(ServerTest, Binary) {
  7252. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7253. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7254. "application/octet-stream");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. ASSERT_EQ(StatusCode::OK_200, res->status);
  7257. ASSERT_EQ(4U, res->body.size());
  7258. res = cli_.Put("/binary", binary.data(), binary.size(),
  7259. "application/octet-stream");
  7260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7261. ASSERT_EQ(StatusCode::OK_200, res->status);
  7262. ASSERT_EQ(4U, res->body.size());
  7263. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7264. "application/octet-stream");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. ASSERT_EQ(StatusCode::OK_200, res->status);
  7267. ASSERT_EQ(4U, res->body.size());
  7268. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7269. "application/octet-stream");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. ASSERT_EQ(StatusCode::OK_200, res->status);
  7272. ASSERT_EQ(4U, res->body.size());
  7273. }
  7274. TEST_F(ServerTest, BinaryString) {
  7275. auto binary = std::string("\x00\x01\x02\x03", 4);
  7276. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. ASSERT_EQ(StatusCode::OK_200, res->status);
  7279. ASSERT_EQ(4U, res->body.size());
  7280. res = cli_.Put("/binary", binary, "application/octet-stream");
  7281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7282. ASSERT_EQ(StatusCode::OK_200, res->status);
  7283. ASSERT_EQ(4U, res->body.size());
  7284. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. ASSERT_EQ(StatusCode::OK_200, res->status);
  7287. ASSERT_EQ(4U, res->body.size());
  7288. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7290. ASSERT_EQ(StatusCode::OK_200, res->status);
  7291. ASSERT_EQ(4U, res->body.size());
  7292. }
  7293. TEST_F(ServerTest, EmptyRequest) {
  7294. auto res = cli_.Get("");
  7295. ASSERT_TRUE(!res);
  7296. EXPECT_EQ(Error::Connection, res.error());
  7297. }
  7298. TEST_F(ServerTest, LongRequest) {
  7299. std::string request;
  7300. for (size_t i = 0; i < 545; i++) {
  7301. request += "/TooLongRequest";
  7302. }
  7303. request += "OK";
  7304. auto res = cli_.Get(request.c_str());
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7307. }
  7308. TEST_F(ServerTest, TooLongRequest) {
  7309. std::string request;
  7310. for (size_t i = 0; i < 546; i++) {
  7311. request += "/TooLongRequest";
  7312. }
  7313. request += "_NG";
  7314. auto start = std::chrono::high_resolution_clock::now();
  7315. cli_.set_keep_alive(true);
  7316. auto res = cli_.Get(request.c_str());
  7317. auto end = std::chrono::high_resolution_clock::now();
  7318. auto elapsed =
  7319. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7320. .count();
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7323. EXPECT_LE(elapsed, 1000);
  7324. EXPECT_EQ("close", res->get_header_value("Connection"));
  7325. EXPECT_FALSE(cli_.is_socket_open());
  7326. }
  7327. TEST_F(ServerTest, AlmostTooLongRequest) {
  7328. // test for #2046 - URI length check shouldn't include other content on req
  7329. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7330. // leading /, space, HTTP/1.1)
  7331. std::string request =
  7332. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7333. auto res = cli_.Get(request.c_str());
  7334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7336. }
  7337. TEST_F(ServerTest, LongHeader) {
  7338. Request req;
  7339. req.method = "GET";
  7340. req.path = "/hi";
  7341. std::string host_and_port;
  7342. host_and_port += HOST;
  7343. host_and_port += ":";
  7344. host_and_port += std::to_string(PORT);
  7345. req.headers.emplace("Host", host_and_port.c_str());
  7346. req.headers.emplace("Accept", "*/*");
  7347. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7348. req.headers.emplace(
  7349. "Header-Name",
  7350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7378. "@@@@@@@@@@@@@@@@");
  7379. auto res = std::make_shared<Response>();
  7380. auto error = Error::Success;
  7381. auto ret = cli_.send(req, *res, error);
  7382. ASSERT_TRUE(ret);
  7383. EXPECT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. TEST_F(ServerTest, LongQueryValue) {
  7386. auto start = std::chrono::high_resolution_clock::now();
  7387. cli_.set_keep_alive(true);
  7388. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7389. auto end = std::chrono::high_resolution_clock::now();
  7390. auto elapsed =
  7391. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7392. .count();
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7395. EXPECT_LE(elapsed, 1000);
  7396. EXPECT_EQ("close", res->get_header_value("Connection"));
  7397. EXPECT_FALSE(cli_.is_socket_open());
  7398. }
  7399. TEST_F(ServerTest, TooLongQueryValue) {
  7400. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7401. ASSERT_FALSE(res);
  7402. EXPECT_EQ(Error::Read, res.error());
  7403. }
  7404. TEST_F(ServerTest, TooLongHeader) {
  7405. Request req;
  7406. req.method = "GET";
  7407. req.path = "/hi";
  7408. std::string host_and_port;
  7409. host_and_port += HOST;
  7410. host_and_port += ":";
  7411. host_and_port += std::to_string(PORT);
  7412. req.headers.emplace("Host", host_and_port.c_str());
  7413. req.headers.emplace("Accept", "*/*");
  7414. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7415. req.headers.emplace(
  7416. "Header-Name",
  7417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7425. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7426. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7445. "@@@@@@@@@@@@@@@@@");
  7446. auto res = std::make_shared<Response>();
  7447. auto error = Error::Success;
  7448. auto ret = cli_.send(req, *res, error);
  7449. ASSERT_TRUE(ret);
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. }
  7452. TEST_F(ServerTest, HeaderCountAtLimit) {
  7453. // Test with headers just under the 100 limit
  7454. httplib::Headers headers;
  7455. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7456. // This should keep us just under the 100 header limit
  7457. for (int i = 0; i < 95; i++) {
  7458. std::string name = "X-Test-Header-" + std::to_string(i);
  7459. std::string value = "value" + std::to_string(i);
  7460. headers.emplace(name, value);
  7461. }
  7462. // This should work fine as we're under the limit
  7463. auto res = cli_.Get("/hi", headers);
  7464. EXPECT_TRUE(res);
  7465. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7466. }
  7467. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7468. // Test with many headers to exceed the 100 limit
  7469. httplib::Headers headers;
  7470. // Add 150 headers to definitely exceed the 100 limit
  7471. for (int i = 0; i < 150; i++) {
  7472. std::string name = "X-Test-Header-" + std::to_string(i);
  7473. std::string value = "value" + std::to_string(i);
  7474. headers.emplace(name, value);
  7475. }
  7476. // This should fail due to exceeding header count limit
  7477. cli_.set_keep_alive(true);
  7478. auto res = cli_.Get("/hi", headers);
  7479. // The server should respond with 400 Bad Request
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7482. EXPECT_EQ("close", res->get_header_value("Connection"));
  7483. EXPECT_FALSE(cli_.is_socket_open());
  7484. }
  7485. TEST_F(ServerTest, PercentEncoding) {
  7486. auto res = cli_.Get("/e%6edwith%");
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, PercentEncodingUnicode) {
  7491. auto res = cli_.Get("/e%u006edwith%");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. TEST_F(ServerTest, InvalidPercentEncoding) {
  7496. auto res = cli_.Get("/%endwith%");
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7499. }
  7500. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7501. auto res = cli_.Get("/%uendwith%");
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7504. }
  7505. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7506. auto res = cli_.Get("/hello?aaa=bbb%");
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7509. }
  7510. TEST_F(ServerTest, PlusSignEncoding) {
  7511. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::OK_200, res->status);
  7514. EXPECT_EQ("a +b", res->body);
  7515. }
  7516. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7517. // This test simulates a potential DoS attack using many headers
  7518. // to verify our security fix prevents memory exhaustion
  7519. httplib::Headers attack_headers;
  7520. // Attempt to add many headers like an attacker would (200 headers to far
  7521. // exceed limit)
  7522. for (int i = 0; i < 200; i++) {
  7523. std::string name = "X-Attack-Header-" + std::to_string(i);
  7524. std::string value = "attack_payload_" + std::to_string(i);
  7525. attack_headers.emplace(name, value);
  7526. }
  7527. // Try to POST with excessive headers
  7528. cli_.set_keep_alive(true);
  7529. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7530. // Should either fail or return 400 Bad Request due to security limit
  7531. if (res) {
  7532. // If we get a response, it should be 400 Bad Request
  7533. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7534. EXPECT_EQ("close", res->get_header_value("Connection"));
  7535. }
  7536. EXPECT_FALSE(cli_.is_socket_open());
  7537. }
  7538. TEST_F(ServerTest, MultipartFormData) {
  7539. UploadFormDataItems items = {
  7540. {"text1", "text default", "", ""},
  7541. {"text2", "aωb", "", ""},
  7542. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7543. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7544. {"file3", "", "", "application/octet-stream"},
  7545. {"file4", "", "", " application/json tmp-string "}};
  7546. auto res = cli_.Post("/multipart", items);
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. }
  7550. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7551. UploadFormDataItems items = {
  7552. {"text", "default text", "", ""},
  7553. {"multi_text1", "aaaaa", "", ""},
  7554. {"multi_text1", "bbbbb", "", ""},
  7555. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7556. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7557. "application/json"},
  7558. };
  7559. auto res = cli_.Post("/multipart/multi_file_values", items);
  7560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7561. EXPECT_EQ(StatusCode::OK_200, res->status);
  7562. }
  7563. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7564. auto res = cli_.Get("/hi");
  7565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7566. EXPECT_EQ(StatusCode::OK_200, res->status);
  7567. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7568. EXPECT_EQ("Hello World!", res->body);
  7569. }
  7570. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7571. Request req;
  7572. req.method = "POST";
  7573. req.path = "/chunked";
  7574. std::string host_and_port;
  7575. host_and_port += HOST;
  7576. host_and_port += ":";
  7577. host_and_port += std::to_string(PORT);
  7578. req.headers.emplace("Host", host_and_port.c_str());
  7579. req.headers.emplace("Accept", "*/*");
  7580. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7581. req.headers.emplace("Content-Type", "text/plain");
  7582. req.headers.emplace("Content-Length", "0");
  7583. req.headers.emplace(
  7584. "Transfer-Encoding",
  7585. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7586. // Client does not chunk, so make a chunked body manually.
  7587. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7588. auto res = std::make_shared<Response>();
  7589. auto error = Error::Success;
  7590. auto ret = cli_.send(req, *res, error);
  7591. ASSERT_TRUE(ret);
  7592. EXPECT_EQ(StatusCode::OK_200, res->status);
  7593. }
  7594. template <typename ClientT>
  7595. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7596. int expected_status) {
  7597. Request req;
  7598. req.method = "POST";
  7599. req.path = "/chunked";
  7600. std::string host_and_port;
  7601. host_and_port += HOST;
  7602. host_and_port += ":";
  7603. host_and_port += std::to_string(PORT);
  7604. req.headers.emplace("Host", host_and_port.c_str());
  7605. req.headers.emplace("Content-Length", "0");
  7606. req.headers.emplace("Transfer-Encoding", "chunked");
  7607. req.body = body;
  7608. auto res = std::make_shared<Response>();
  7609. auto error = Error::Success;
  7610. ASSERT_TRUE(cli.send(req, *res, error));
  7611. EXPECT_EQ(expected_status, res->status);
  7612. }
  7613. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7614. // rather than treat them as valid lengths.
  7615. template <typename ClientT>
  7616. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7617. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7618. }
  7619. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7620. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7621. }
  7622. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7623. expect_chunked_body_rejected(
  7624. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7625. }
  7626. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7627. // chunk-size line carries no CR, LF or other control character ahead of its
  7628. // terminator. Such a line must be refused rather than read as extension text.
  7629. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7630. expect_chunked_body_rejected(
  7631. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7632. }
  7633. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7634. expect_chunked_body_rejected(
  7635. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7636. }
  7637. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7638. expect_chunked_body_rejected(
  7639. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7640. }
  7641. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7642. // The literal stays split: a hex escape consumes every hex digit that
  7643. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7644. expect_chunked_body_rejected(
  7645. cli_, "4;a\x01"
  7646. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7647. }
  7648. // The bytes around chunk data are no payload, so they cannot ride on the
  7649. // payload limit
  7650. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7651. // Small enough that the whole request is sent before the server turns it
  7652. // down, yet past the limit by the last chunks
  7653. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7654. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7655. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7656. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7657. SCOPED_TRACE(size_line.substr(0, 2));
  7658. std::string body;
  7659. for (auto c : std::string("dechunked post body")) {
  7660. body += size_line + "\r\n" + c + "\r\n";
  7661. }
  7662. body += "0\r\n\r\n";
  7663. expect_chunked_body_rejected(cli_, body.c_str());
  7664. }
  7665. }
  7666. TEST_F(ServerTest, AcceptsChunkExtension) {
  7667. expect_chunked_body_status(cli_,
  7668. "4;name=value\r\ndech\r\n"
  7669. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7670. "0;last\r\n\r\n",
  7671. StatusCode::OK_200);
  7672. }
  7673. TEST_F(ServerTest, GetStreamed2) {
  7674. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7677. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7678. EXPECT_EQ(true, res->has_header("Content-Range"));
  7679. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7680. EXPECT_EQ(std::string("ab"), res->body);
  7681. }
  7682. TEST_F(ServerTest, GetStreamed) {
  7683. auto res = cli_.Get("/streamed");
  7684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7685. EXPECT_EQ(StatusCode::OK_200, res->status);
  7686. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7687. EXPECT_EQ(std::string("aaabbb"), res->body);
  7688. }
  7689. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7690. auto res = cli_.Get("/streamed-without-length",
  7691. Headers{make_range_header({{0, -1}})});
  7692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7693. EXPECT_EQ(StatusCode::OK_200, res->status);
  7694. EXPECT_EQ(false, res->has_header("Content-Length"));
  7695. EXPECT_EQ(false, res->has_header("Content-Range"));
  7696. EXPECT_EQ(std::string("abcdefg"), res->body);
  7697. }
  7698. TEST_F(ServerTest, GetStreamedWithRange1) {
  7699. auto res =
  7700. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7703. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7704. EXPECT_EQ(true, res->has_header("Content-Range"));
  7705. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7706. EXPECT_EQ(std::string("def"), res->body);
  7707. }
  7708. TEST_F(ServerTest, GetStreamedWithRange2) {
  7709. auto res =
  7710. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7713. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7714. EXPECT_EQ(true, res->has_header("Content-Range"));
  7715. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7716. EXPECT_EQ(std::string("bcdefg"), res->body);
  7717. }
  7718. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7719. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7722. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7723. EXPECT_EQ(true, res->has_header("Content-Range"));
  7724. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7725. EXPECT_EQ(std::string("efg"), res->body);
  7726. }
  7727. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7728. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7729. // the entire representation.
  7730. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7731. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7734. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7735. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7736. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7737. }
  7738. }
  7739. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7740. auto res =
  7741. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7743. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7744. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7745. EXPECT_EQ(false, res->has_header("Content-Range"));
  7746. EXPECT_EQ(0U, res->body.size());
  7747. }
  7748. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7749. // Only a 206 is served as a partial representation. Under any other status
  7750. // `apply_ranges()` reported the full content length, so the body must match
  7751. // that header, and the content provider must never be asked for an offset
  7752. // outside the representation.
  7753. auto check = [&](int status, const char *range) {
  7754. auto path =
  7755. std::string("/streamed-with-range?status=") + std::to_string(status);
  7756. auto ctx = path + " Range: " + range;
  7757. auto res = cli_.Get(path, Headers{{"Range", range}});
  7758. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7759. EXPECT_EQ(status, res->status) << ctx;
  7760. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7762. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7763. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7764. };
  7765. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7766. check(403, "bytes=3-5");
  7767. // The offset is far past the representation.
  7768. check(403, "bytes=100000-100200");
  7769. // `first_pos` is still -1 here, and the bounds asserts in
  7770. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7771. check(403, "bytes=-3");
  7772. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7773. // multipart branch would have written one that is empty.
  7774. check(403, "bytes=1-2, 4-5");
  7775. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7776. // covers the whole representation.
  7777. check(200, "bytes=3-5");
  7778. check(200, "bytes=1-2, 4-5");
  7779. }
  7780. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7781. auto res =
  7782. cli_.Get("/streamed-with-range",
  7783. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7784. "92233720368547758079223372036854775807"}});
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7787. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7788. EXPECT_EQ(false, res->has_header("Content-Range"));
  7789. EXPECT_EQ(0U, res->body.size());
  7790. }
  7791. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7792. auto res = cli_.Get(
  7793. "/with-range",
  7794. Headers{{"Range",
  7795. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7796. {"Accept-Encoding", ""}});
  7797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7798. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7799. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7800. EXPECT_EQ(true, res->has_header("Content-Range"));
  7801. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7802. EXPECT_EQ(std::string("abcdefg"), res->body);
  7803. }
  7804. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7805. auto res = cli_.Get("/with-range", Headers{
  7806. {"Range", "bytes=0-"},
  7807. {"Accept-Encoding", ""},
  7808. });
  7809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7811. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7812. EXPECT_EQ(true, res->has_header("Content-Range"));
  7813. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7814. EXPECT_EQ(std::string("abcdefg"), res->body);
  7815. }
  7816. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7817. auto res = cli_.Get("/streamed-with-range",
  7818. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7821. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(false, res->has_header("Content-Range"));
  7823. EXPECT_EQ(267U, res->body.size());
  7824. // Check that both range contents are present
  7825. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7826. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7827. // Check that Content-Range headers are present for both ranges
  7828. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7829. std::string::npos);
  7830. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7831. std::string::npos);
  7832. }
  7833. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7834. Ranges ranges;
  7835. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7836. ranges.emplace_back(0, -1);
  7837. }
  7838. auto res = cli_.Get("/streamed-with-range?error",
  7839. Headers{{make_range_header(ranges)}});
  7840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7841. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7842. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7843. EXPECT_EQ(false, res->has_header("Content-Range"));
  7844. EXPECT_EQ(0U, res->body.size());
  7845. }
  7846. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7847. auto res = cli_.Get("/streamed-with-range",
  7848. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7850. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7851. EXPECT_EQ(5U, res->body.size());
  7852. // Check that overlapping ranges are coalesced into a single range
  7853. EXPECT_EQ("bcdef", res->body);
  7854. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7855. // Should be single range, not multipart
  7856. EXPECT_TRUE(res->has_header("Content-Range"));
  7857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7858. }
  7859. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7860. auto res = cli_.Get("/streamed-with-range",
  7861. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7864. EXPECT_EQ(268U, res->body.size());
  7865. // Check that both range contents are present
  7866. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7867. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7868. // Check that Content-Range headers are present for both ranges
  7869. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7870. std::string::npos);
  7871. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7872. std::string::npos);
  7873. }
  7874. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7875. auto res = cli_.Get("/streamed-with-range",
  7876. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7879. EXPECT_EQ(269U, res->body.size());
  7880. // Check that both duplicate range contents are present
  7881. size_t first_abc = res->body.find("abc\r\n");
  7882. EXPECT_TRUE(first_abc != std::string::npos);
  7883. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7884. EXPECT_TRUE(second_abc != std::string::npos);
  7885. // Check that Content-Range headers are present for both ranges
  7886. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7887. EXPECT_TRUE(first_range != std::string::npos);
  7888. size_t second_range =
  7889. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7890. EXPECT_TRUE(second_range != std::string::npos);
  7891. }
  7892. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7893. auto res =
  7894. cli_.Get("/streamed-with-range?error",
  7895. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7898. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7899. EXPECT_EQ(false, res->has_header("Content-Range"));
  7900. EXPECT_EQ(0U, res->body.size());
  7901. }
  7902. TEST_F(ServerTest, GetStreamedEndless) {
  7903. uint64_t offset = 0;
  7904. auto res = cli_.Get("/streamed-cancel",
  7905. [&](const char * /*data*/, uint64_t data_length) {
  7906. if (offset < 100) {
  7907. offset += data_length;
  7908. return true;
  7909. }
  7910. return false;
  7911. });
  7912. ASSERT_TRUE(!res);
  7913. EXPECT_EQ(Error::Canceled, res.error());
  7914. }
  7915. TEST_F(ServerTest, ClientStop) {
  7916. std::atomic_size_t count{4};
  7917. std::vector<std::thread> threads;
  7918. for (auto i = count.load(); i != 0; --i) {
  7919. threads.emplace_back([&]() {
  7920. auto res = cli_.Get("/streamed-cancel",
  7921. [&](const char *, uint64_t) { return true; });
  7922. --count;
  7923. ASSERT_TRUE(!res);
  7924. EXPECT_TRUE(res.error() == Error::Canceled ||
  7925. res.error() == Error::Read || res.error() == Error::Write);
  7926. });
  7927. }
  7928. std::this_thread::sleep_for(std::chrono::seconds(2));
  7929. while (count != 0) {
  7930. cli_.stop();
  7931. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7932. }
  7933. for (auto &t : threads) {
  7934. t.join();
  7935. }
  7936. }
  7937. TEST_F(ServerTest, GetWithRange1) {
  7938. auto res = cli_.Get("/with-range", Headers{
  7939. make_range_header({{3, 5}}),
  7940. {"Accept-Encoding", ""},
  7941. });
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7944. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7945. EXPECT_EQ(true, res->has_header("Content-Range"));
  7946. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7947. EXPECT_EQ(std::string("def"), res->body);
  7948. }
  7949. TEST_F(ServerTest, GetWithRange2) {
  7950. auto res = cli_.Get("/with-range", Headers{
  7951. make_range_header({{1, -1}}),
  7952. {"Accept-Encoding", ""},
  7953. });
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7956. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7957. EXPECT_EQ(true, res->has_header("Content-Range"));
  7958. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7959. EXPECT_EQ(std::string("bcdefg"), res->body);
  7960. }
  7961. TEST_F(ServerTest, GetWithRange3) {
  7962. auto res = cli_.Get("/with-range", Headers{
  7963. make_range_header({{0, 0}}),
  7964. {"Accept-Encoding", ""},
  7965. });
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7968. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7969. EXPECT_EQ(true, res->has_header("Content-Range"));
  7970. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7971. EXPECT_EQ(std::string("a"), res->body);
  7972. }
  7973. TEST_F(ServerTest, GetWithRange4) {
  7974. auto res = cli_.Get("/with-range", Headers{
  7975. make_range_header({{-1, 2}}),
  7976. {"Accept-Encoding", ""},
  7977. });
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7980. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7981. EXPECT_EQ(true, res->has_header("Content-Range"));
  7982. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7983. EXPECT_EQ(std::string("fg"), res->body);
  7984. }
  7985. TEST_F(ServerTest, GetWithRange5) {
  7986. auto res = cli_.Get("/with-range", Headers{
  7987. make_range_header({{0, 5}}),
  7988. {"Accept-Encoding", ""},
  7989. });
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7992. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ(true, res->has_header("Content-Range"));
  7994. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7995. EXPECT_EQ(std::string("abcdef"), res->body);
  7996. }
  7997. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7998. TEST_F(ServerTest, GetWithRangeAcceptEncoding) {
  7999. cli_.set_decompress(false);
  8000. auto res = cli_.Get("/with-range", Headers{{"Range", "bytes=1-3"},
  8001. {"Accept-Encoding", "gzip"}});
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8004. EXPECT_EQ("bytes 1-3/7", res->get_header_value("Content-Range"));
  8005. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  8006. EXPECT_EQ("bcd", res->body);
  8007. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8008. }
  8009. #endif
  8010. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  8011. auto res =
  8012. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  8013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8014. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  8015. }
  8016. TEST_F(ServerTest, GetWithRangeMultipart) {
  8017. auto res =
  8018. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8021. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  8022. EXPECT_EQ(false, res->has_header("Content-Range"));
  8023. EXPECT_EQ(267U, res->body.size());
  8024. }
  8025. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  8026. // RFC 9110 14.1.1: the set is satisfiable when any of its ranges is, and the
  8027. // unsatisfiable ones are left out of the response.
  8028. auto res = cli_.Get("/with-range",
  8029. Headers{make_range_header({{-1, 2}, {10000, 30000}}),
  8030. {"Accept-Encoding", ""}});
  8031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8033. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8034. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  8035. EXPECT_EQ(std::string("fg"), res->body);
  8036. }
  8037. TEST_F(ServerTest, GetWithRangeMultipartSkipsUnsatisfiableRange) {
  8038. auto res =
  8039. cli_.Get("/with-range",
  8040. Headers{{make_range_header({{1, 2}, {10000, 30000}, {4, 5}})}});
  8041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8043. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  8044. EXPECT_EQ(false, res->has_header("Content-Range"));
  8045. EXPECT_EQ(267U, res->body.size());
  8046. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  8047. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  8048. }
  8049. TEST_F(ServerTest, GetWithRangeMultipartNoneSatisfiable) {
  8050. for (auto range : {"bytes=7-, -0", "bytes=10000-30000, 7-8"}) {
  8051. auto res = cli_.Get("/with-range", Headers{{"Range", range}});
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status) << range;
  8054. }
  8055. }
  8056. TEST_F(ServerTest, GetStreamedWithRangeSkipsUnsatisfiableRange) {
  8057. auto res =
  8058. cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=7-, 2-3"}});
  8059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8061. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8062. EXPECT_EQ("bytes 2-3/7", res->get_header_value("Content-Range"));
  8063. EXPECT_EQ(std::string("cd"), res->body);
  8064. }
  8065. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  8066. auto res = cli_.Get("/with-range-customized-response",
  8067. Headers{{make_range_header({{1, 2}})}});
  8068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8069. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8070. EXPECT_EQ(true, res->has_header("Content-Length"));
  8071. EXPECT_EQ(false, res->has_header("Content-Range"));
  8072. EXPECT_EQ(JSON_DATA, res->body);
  8073. }
  8074. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  8075. auto res = cli_.Get("/with-range-customized-response",
  8076. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8078. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8079. EXPECT_EQ(true, res->has_header("Content-Length"));
  8080. EXPECT_EQ(false, res->has_header("Content-Range"));
  8081. EXPECT_EQ(JSON_DATA, res->body);
  8082. }
  8083. TEST_F(ServerTest, Issue1772) {
  8084. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  8085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8086. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  8087. }
  8088. TEST_F(ServerTest, Issue609) {
  8089. auto res = cli_.Delete("/issue609");
  8090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8091. EXPECT_EQ(StatusCode::OK_200, res->status);
  8092. EXPECT_EQ(std::string("ok"), res->body);
  8093. }
  8094. TEST_F(ServerTest, GetStreamedChunked) {
  8095. auto res = cli_.Get("/streamed-chunked");
  8096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8097. EXPECT_EQ(StatusCode::OK_200, res->status);
  8098. EXPECT_EQ(std::string("123456789"), res->body);
  8099. }
  8100. TEST_F(ServerTest, GetStreamedChunked2) {
  8101. auto res = cli_.Get("/streamed-chunked2");
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ(StatusCode::OK_200, res->status);
  8104. EXPECT_EQ(std::string("123456789"), res->body);
  8105. }
  8106. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  8107. auto res = cli_.Get("/streamed-chunked-with-trailer");
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. EXPECT_EQ(std::string("123456789"), res->body);
  8111. EXPECT_TRUE(res->has_header("Trailer"));
  8112. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8113. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8114. // Trailers are now stored separately from headers (security fix)
  8115. EXPECT_EQ(2U, res->trailers.size());
  8116. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8117. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8118. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8119. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8120. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8121. // Verify trailers are NOT in headers (security verification)
  8122. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8123. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8124. }
  8125. TEST_F(ServerTest, LargeChunkedPost) {
  8126. Request req;
  8127. req.method = "POST";
  8128. req.path = "/large-chunked";
  8129. std::string host_and_port;
  8130. host_and_port += HOST;
  8131. host_and_port += ":";
  8132. host_and_port += std::to_string(PORT);
  8133. req.headers.emplace("Host", host_and_port.c_str());
  8134. req.headers.emplace("Accept", "*/*");
  8135. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8136. req.headers.emplace("Content-Type", "text/plain");
  8137. req.headers.emplace("Content-Length", "0");
  8138. req.headers.emplace("Transfer-Encoding", "chunked");
  8139. std::string long_string(30 * 1024u, 'a');
  8140. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8141. // Attempt to make a large enough post to exceed OS buffers, to test that
  8142. // the server handles short reads if the full chunk data isn't available.
  8143. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8144. auto res = std::make_shared<Response>();
  8145. auto error = Error::Success;
  8146. auto ret = cli_.send(req, *res, error);
  8147. ASSERT_TRUE(ret);
  8148. EXPECT_EQ(StatusCode::OK_200, res->status);
  8149. }
  8150. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8151. auto res = cli_.Get("/remote_addr");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::OK_200, res->status);
  8154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8155. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8156. }
  8157. TEST_F(ServerTest, GetMethodLocalAddr) {
  8158. auto res = cli_.Get("/local_addr");
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8162. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8163. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8164. }
  8165. TEST_F(ServerTest, HTTPResponseSplitting) {
  8166. auto res = cli_.Get("/http_response_splitting");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::OK_200, res->status);
  8169. }
  8170. TEST_F(ServerTest, SlowRequest) {
  8171. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8172. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8173. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8174. }
  8175. #if 0
  8176. TEST_F(ServerTest, SlowPost) {
  8177. char buffer[64 * 1024];
  8178. memset(buffer, 0x42, sizeof(buffer));
  8179. auto res = cli_.Post(
  8180. "/slowpost", 64 * 1024 * 1024,
  8181. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8182. auto ret = sink.write(buffer, sizeof(buffer));
  8183. EXPECT_TRUE(ret);
  8184. return true;
  8185. },
  8186. "text/plain");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. }
  8190. TEST_F(ServerTest, SlowPostFail) {
  8191. char buffer[64 * 1024];
  8192. memset(buffer, 0x42, sizeof(buffer));
  8193. cli_.set_write_timeout(std::chrono::seconds(0));
  8194. auto res = cli_.Post(
  8195. "/slowpost", 64 * 1024 * 1024,
  8196. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8197. sink.write(buffer, sizeof(buffer));
  8198. return true;
  8199. },
  8200. "text/plain");
  8201. ASSERT_TRUE(!res);
  8202. EXPECT_EQ(Error::Write, res.error());
  8203. }
  8204. #endif
  8205. TEST_F(ServerTest, Put) {
  8206. auto res = cli_.Put("/put", "PUT", "text/plain");
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. EXPECT_EQ("PUT", res->body);
  8210. }
  8211. TEST_F(ServerTest, PutWithContentProvider) {
  8212. auto res = cli_.Put(
  8213. "/put", 3,
  8214. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8215. sink.os << "PUT";
  8216. return true;
  8217. },
  8218. "text/plain");
  8219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8220. EXPECT_EQ(StatusCode::OK_200, res->status);
  8221. EXPECT_EQ("PUT", res->body);
  8222. }
  8223. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8224. auto res = cli_.Post(
  8225. "/post", 42,
  8226. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8227. return false;
  8228. },
  8229. "text/plain");
  8230. ASSERT_TRUE(!res);
  8231. EXPECT_EQ(Error::Canceled, res.error());
  8232. }
  8233. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8234. auto res = cli_.Put(
  8235. "/put",
  8236. [](size_t /*offset*/, DataSink &sink) {
  8237. sink.os << "PUT";
  8238. sink.done();
  8239. return true;
  8240. },
  8241. "text/plain");
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. EXPECT_EQ(StatusCode::OK_200, res->status);
  8244. EXPECT_EQ("PUT", res->body);
  8245. }
  8246. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8247. auto res = cli_.Post(
  8248. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8249. "text/plain");
  8250. ASSERT_TRUE(!res);
  8251. EXPECT_EQ(Error::Canceled, res.error());
  8252. }
  8253. TEST_F(ServerTest, PostLoopBack) {
  8254. std::string body;
  8255. auto res = cli_.Post(
  8256. "/post-loopback", 9,
  8257. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8258. EXPECT_EQ(9u, length);
  8259. sink.write("123", 3);
  8260. sink.write("456", 3);
  8261. sink.write("789", 3);
  8262. return true;
  8263. },
  8264. "text/plain",
  8265. [&body](const char *data, size_t data_length) {
  8266. body.append(data, data_length);
  8267. return true;
  8268. });
  8269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8270. EXPECT_EQ(StatusCode::OK_200, res->status);
  8271. EXPECT_EQ("123456789", body);
  8272. }
  8273. TEST_F(ServerTest, PutLoopBack) {
  8274. std::string body;
  8275. auto res = cli_.Put(
  8276. "/put-loopback", 9,
  8277. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8278. EXPECT_EQ(9u, length);
  8279. sink.write("123", 3);
  8280. sink.write("456", 3);
  8281. sink.write("789", 3);
  8282. return true;
  8283. },
  8284. "text/plain",
  8285. [&body](const char *data, size_t data_length) {
  8286. body.append(data, data_length);
  8287. return true;
  8288. });
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::OK_200, res->status);
  8291. EXPECT_EQ("123456789", body);
  8292. }
  8293. TEST_F(ServerTest, PatchLoopBack) {
  8294. std::string body;
  8295. auto res = cli_.Patch(
  8296. "/patch-loopback", 9,
  8297. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8298. EXPECT_EQ(9u, length);
  8299. sink.write("123", 3);
  8300. sink.write("456", 3);
  8301. sink.write("789", 3);
  8302. return true;
  8303. },
  8304. "text/plain",
  8305. [&body](const char *data, size_t data_length) {
  8306. body.append(data, data_length);
  8307. return true;
  8308. });
  8309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8310. EXPECT_EQ(StatusCode::OK_200, res->status);
  8311. EXPECT_EQ("123456789", body);
  8312. }
  8313. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8314. std::string body;
  8315. auto res = cli_.Post(
  8316. "/post-loopback",
  8317. [](size_t /*offset*/, DataSink &sink) {
  8318. sink.write("123", 3);
  8319. sink.write("456", 3);
  8320. sink.write("789", 3);
  8321. sink.done();
  8322. return true;
  8323. },
  8324. "text/plain",
  8325. [&body](const char *data, size_t data_length) {
  8326. body.append(data, data_length);
  8327. return true;
  8328. });
  8329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8330. EXPECT_EQ(StatusCode::OK_200, res->status);
  8331. EXPECT_EQ("123456789", body);
  8332. }
  8333. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8334. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8335. cli_.set_compress(true);
  8336. auto res = cli_.Put(
  8337. "/put", 3,
  8338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8339. sink.os << "PUT";
  8340. return true;
  8341. },
  8342. "text/plain");
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::OK_200, res->status);
  8345. EXPECT_EQ("PUT", res->body);
  8346. }
  8347. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8348. cli_.set_compress(true);
  8349. auto res = cli_.Post(
  8350. "/post", 42,
  8351. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8352. return false;
  8353. },
  8354. "text/plain");
  8355. ASSERT_TRUE(!res);
  8356. EXPECT_EQ(Error::Canceled, res.error());
  8357. }
  8358. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8359. cli_.set_compress(true);
  8360. auto res = cli_.Put(
  8361. "/put",
  8362. [](size_t /*offset*/, DataSink &sink) {
  8363. sink.os << "PUT";
  8364. sink.done();
  8365. return true;
  8366. },
  8367. "text/plain");
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_EQ("PUT", res->body);
  8371. }
  8372. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8373. cli_.set_compress(true);
  8374. auto res = cli_.Post(
  8375. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8376. "text/plain");
  8377. ASSERT_TRUE(!res);
  8378. EXPECT_EQ(Error::Canceled, res.error());
  8379. }
  8380. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8381. cli_.set_compress(true);
  8382. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::OK_200, res->status);
  8385. EXPECT_EQ(LARGE_DATA, res->body);
  8386. }
  8387. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8388. #ifdef CPPHTTPLIB_SSL_ENABLED
  8389. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8390. Client cli(s.c_str());
  8391. cli.enable_server_certificate_verification(false);
  8392. #else
  8393. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8394. Client cli(s.c_str());
  8395. #endif
  8396. cli.set_compress(true);
  8397. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_EQ(StatusCode::OK_200, res->status);
  8400. EXPECT_EQ(LARGE_DATA, res->body);
  8401. // The compressed size should be less than a 10th of the original. May vary
  8402. // depending on the zlib library.
  8403. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8404. static_cast<uint64_t>(10 * 1024 * 1024));
  8405. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8406. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8407. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8408. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8409. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8410. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8411. #endif
  8412. }
  8413. TEST_F(ServerTest, PutContentWithDeflate) {
  8414. cli_.set_compress(false);
  8415. Headers headers;
  8416. headers.emplace("Content-Encoding", "deflate");
  8417. // PUT in deflate format:
  8418. auto res = cli_.Put("/put", headers,
  8419. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. EXPECT_EQ("PUT", res->body);
  8423. }
  8424. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "gzip, deflate");
  8427. auto res = cli_.Get("/streamed-chunked", 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, GetStreamedChunkedWithGzip2) {
  8433. Headers headers;
  8434. headers.emplace("Accept-Encoding", "gzip, deflate");
  8435. auto res = cli_.Get("/streamed-chunked2", headers);
  8436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8437. EXPECT_EQ(StatusCode::OK_200, res->status);
  8438. EXPECT_EQ(std::string("123456789"), res->body);
  8439. }
  8440. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8441. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8443. EXPECT_EQ(StatusCode::OK_200, res->status);
  8444. }
  8445. TEST(GzipDecompressor, ChunkedDecompression) {
  8446. std::string data;
  8447. for (size_t i = 0; i < 32 * 1024; ++i) {
  8448. data.push_back(static_cast<char>('a' + i % 26));
  8449. }
  8450. std::string compressed_data;
  8451. {
  8452. httplib::detail::gzip_compressor compressor;
  8453. bool result = compressor.compress(
  8454. data.data(), data.size(),
  8455. /*last=*/true,
  8456. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8457. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8458. compressed_data_size);
  8459. return true;
  8460. });
  8461. ASSERT_TRUE(result);
  8462. }
  8463. std::string decompressed_data;
  8464. {
  8465. httplib::detail::gzip_decompressor decompressor;
  8466. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8467. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8468. size_t chunk_size = 130;
  8469. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8470. chunk_begin += chunk_size) {
  8471. size_t current_chunk_size =
  8472. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8473. bool result = decompressor.decompress(
  8474. compressed_data.data() + chunk_begin, current_chunk_size,
  8475. [&](const char *decompressed_data_chunk,
  8476. size_t decompressed_data_chunk_size) {
  8477. decompressed_data.insert(decompressed_data.size(),
  8478. decompressed_data_chunk,
  8479. decompressed_data_chunk_size);
  8480. return true;
  8481. });
  8482. ASSERT_TRUE(result);
  8483. }
  8484. }
  8485. ASSERT_EQ(data, decompressed_data);
  8486. }
  8487. TEST(GzipDecompressor, DeflateDecompression) {
  8488. std::string original_text = "Raw deflate without gzip";
  8489. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8490. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8491. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8492. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8493. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8494. std::string decompressed_data;
  8495. {
  8496. httplib::detail::gzip_decompressor decompressor;
  8497. bool result = decompressor.decompress(
  8498. compressed_data.data(), compressed_data.size(),
  8499. [&](const char *decompressed_data_chunk,
  8500. size_t decompressed_data_chunk_size) {
  8501. decompressed_data.insert(decompressed_data.size(),
  8502. decompressed_data_chunk,
  8503. decompressed_data_chunk_size);
  8504. return true;
  8505. });
  8506. ASSERT_TRUE(result);
  8507. }
  8508. ASSERT_EQ(original_text, decompressed_data);
  8509. }
  8510. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8511. std::string original_text = "Raw deflate without gzip";
  8512. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8513. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8514. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8515. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8516. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8517. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8518. std::string decompressed_data;
  8519. {
  8520. httplib::detail::gzip_decompressor decompressor;
  8521. bool result = decompressor.decompress(
  8522. compressed_data.data(), compressed_data.size(),
  8523. [&](const char *decompressed_data_chunk,
  8524. size_t decompressed_data_chunk_size) {
  8525. decompressed_data.insert(decompressed_data.size(),
  8526. decompressed_data_chunk,
  8527. decompressed_data_chunk_size);
  8528. return true;
  8529. });
  8530. ASSERT_TRUE(result);
  8531. }
  8532. ASSERT_EQ(original_text, decompressed_data);
  8533. }
  8534. TEST(GzipDecompressor, MultipleMembers) {
  8535. auto gzip = [](const std::string &data) {
  8536. std::string out;
  8537. httplib::detail::gzip_compressor compressor;
  8538. compressor.compress(data.data(), data.size(), /*last=*/true,
  8539. [&](const char *chunk, size_t n) {
  8540. out.append(chunk, n);
  8541. return true;
  8542. });
  8543. return out;
  8544. };
  8545. // Decompresses `data` handed over in two calls, the first `split` bytes long
  8546. auto decompress = [](const std::string &data, size_t split,
  8547. std::string &out) {
  8548. httplib::detail::gzip_decompressor decompressor;
  8549. auto callback = [&](const char *chunk, size_t n) {
  8550. out.append(chunk, n);
  8551. return true;
  8552. };
  8553. return decompressor.decompress(data.data(), split, callback) &&
  8554. decompressor.decompress(data.data() + split, data.size() - split,
  8555. callback);
  8556. };
  8557. // RFC 1952 2.2: a gzip body is a series of members, an empty one included.
  8558. // Bytes after the last member that start no other one are still ignored.
  8559. const auto members = gzip("Hello, ") + gzip("") + gzip("World!");
  8560. for (const auto &body : {members, members + std::string(8, '\0')}) {
  8561. for (size_t split = 0; split <= body.size(); split++) {
  8562. std::string out;
  8563. ASSERT_TRUE(decompress(body, split, out)) << "split at " << split;
  8564. EXPECT_EQ("Hello, World!", out) << "split at " << split;
  8565. }
  8566. }
  8567. // A broken later member fails like a broken first one
  8568. auto broken = gzip("Hello, ") + gzip("World!");
  8569. auto crc_pos = broken.size() - 8;
  8570. broken[crc_pos] = static_cast<char>(broken[crc_pos] ^ 0x01);
  8571. std::string out;
  8572. EXPECT_FALSE(decompress(broken, broken.size(), out));
  8573. }
  8574. #endif
  8575. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8576. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8577. Headers headers;
  8578. headers.emplace("Accept-Encoding", "br");
  8579. auto res = cli_.Get("/streamed-chunked", headers);
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ(StatusCode::OK_200, res->status);
  8582. EXPECT_EQ(std::string("123456789"), res->body);
  8583. }
  8584. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8585. Headers headers;
  8586. headers.emplace("Accept-Encoding", "br");
  8587. auto res = cli_.Get("/streamed-chunked2", headers);
  8588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8589. EXPECT_EQ(StatusCode::OK_200, res->status);
  8590. EXPECT_EQ(std::string("123456789"), res->body);
  8591. }
  8592. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8593. cli_.set_compress(true);
  8594. auto res = cli_.Put(
  8595. "/put", 3,
  8596. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8597. sink.os << "PUT";
  8598. return true;
  8599. },
  8600. "text/plain");
  8601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8602. EXPECT_EQ(StatusCode::OK_200, res->status);
  8603. EXPECT_EQ("PUT", res->body);
  8604. }
  8605. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8606. cli_.set_compress(true);
  8607. auto res = cli_.Put(
  8608. "/put",
  8609. [](size_t /*offset*/, DataSink &sink) {
  8610. sink.os << "PUT";
  8611. sink.done();
  8612. return true;
  8613. },
  8614. "text/plain");
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. EXPECT_EQ(StatusCode::OK_200, res->status);
  8617. EXPECT_EQ("PUT", res->body);
  8618. }
  8619. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8620. cli_.set_compress(true);
  8621. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. EXPECT_EQ(LARGE_DATA, res->body);
  8625. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8626. }
  8627. #endif
  8628. TEST_F(ServerTest, Patch) {
  8629. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8631. EXPECT_EQ(StatusCode::OK_200, res->status);
  8632. EXPECT_EQ("PATCH", res->body);
  8633. }
  8634. TEST_F(ServerTest, Delete) {
  8635. auto res = cli_.Delete("/delete");
  8636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8637. EXPECT_EQ(StatusCode::OK_200, res->status);
  8638. EXPECT_EQ("DELETE", res->body);
  8639. }
  8640. TEST_F(ServerTest, DeleteContentReceiver) {
  8641. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ("content", res->body);
  8645. }
  8646. TEST_F(ServerTest, Options) {
  8647. auto res = cli_.Options("*");
  8648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8649. EXPECT_EQ(StatusCode::OK_200, res->status);
  8650. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8651. EXPECT_TRUE(res->body.empty());
  8652. }
  8653. TEST_F(ServerTest, URL) {
  8654. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8656. EXPECT_EQ(StatusCode::OK_200, res->status);
  8657. }
  8658. TEST_F(ServerTest, ArrayParam) {
  8659. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8661. EXPECT_EQ(StatusCode::OK_200, res->status);
  8662. }
  8663. TEST_F(ServerTest, ArrayParamValues) {
  8664. auto res =
  8665. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8667. EXPECT_EQ(StatusCode::OK_200, res->status);
  8668. }
  8669. TEST_F(ServerTest, NoMultipleHeaders) {
  8670. Headers headers = {{"Content-Length", "5"}};
  8671. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8672. "text/plain");
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. }
  8676. TEST_F(ServerTest, PostContentReceiver) {
  8677. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8679. ASSERT_EQ(StatusCode::OK_200, res->status);
  8680. ASSERT_EQ("content", res->body);
  8681. }
  8682. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8683. UploadFormDataItems items = {
  8684. {"text1", "text default", "", ""},
  8685. {"text2", "aωb", "", ""},
  8686. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8687. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8688. {"file3", "", "", "application/octet-stream"},
  8689. };
  8690. auto res = cli_.Post("/content_receiver", items);
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::OK_200, res->status);
  8693. }
  8694. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8695. UploadFormDataItems items = {
  8696. {"text1", "text default", "", ""},
  8697. {"text2", "aωb", "", ""},
  8698. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8699. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8700. {"file3", "", "", "application/octet-stream"},
  8701. };
  8702. auto boundary = std::string("+++++");
  8703. std::string body;
  8704. for (const auto &item : items) {
  8705. body += "--" + boundary + "\r\n";
  8706. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8707. if (!item.filename.empty()) {
  8708. body += "; filename=\"" + item.filename + "\"";
  8709. }
  8710. body += "\r\n";
  8711. if (!item.content_type.empty()) {
  8712. body += "Content-Type: " + item.content_type + "\r\n";
  8713. }
  8714. body += "\r\n";
  8715. body += item.content + "\r\n";
  8716. }
  8717. body += "--" + boundary + "--\r\n";
  8718. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8719. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8721. EXPECT_EQ(StatusCode::OK_200, res->status);
  8722. }
  8723. TEST(MultipartFormDataTest, FieldEscaping) {
  8724. Server svr;
  8725. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8726. const ContentReader &content_reader) {
  8727. ASSERT_TRUE(req.is_multipart_form_data());
  8728. std::vector<FormData> received;
  8729. content_reader(
  8730. [&](const FormData &file) {
  8731. received.push_back(file);
  8732. return true;
  8733. },
  8734. [&](const char *data, size_t data_length) {
  8735. received.back().content.append(data, data_length);
  8736. return true;
  8737. });
  8738. // '"', CR and LF in names and filenames are escaped following the
  8739. // WHATWG HTML standard, so each part still parses as a single part
  8740. // with no injected headers. Content types get CR/LF escaped too,
  8741. // while '"' (legal there, e.g. quoted charset) is preserved.
  8742. ASSERT_EQ(4U, received.size());
  8743. EXPECT_EQ("na%22me", received[0].name);
  8744. EXPECT_EQ("quoted name", received[0].content);
  8745. EXPECT_EQ("file", received[1].name);
  8746. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8747. received[1].filename);
  8748. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8749. EXPECT_EQ("injected", received[1].content);
  8750. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8751. EXPECT_EQ("my%22file.txt", received[2].filename);
  8752. EXPECT_EQ("cr lf name", received[2].content);
  8753. EXPECT_EQ("typed", received[3].name);
  8754. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8755. received[3].content_type);
  8756. EXPECT_EQ("typed content", received[3].content);
  8757. });
  8758. auto port = svr.bind_to_any_port("localhost");
  8759. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8760. auto se = detail::scope_exit([&] {
  8761. svr.stop();
  8762. t.join();
  8763. ASSERT_FALSE(svr.is_running());
  8764. });
  8765. svr.wait_until_ready();
  8766. Client cli("localhost", port);
  8767. UploadFormDataItems items = {
  8768. {"na\"me", "quoted name", "", ""},
  8769. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8770. "application/octet-stream"},
  8771. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8772. {"typed", "typed content", "",
  8773. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8774. };
  8775. auto res = cli.Post("/post", items);
  8776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8777. EXPECT_EQ(StatusCode::OK_200, res->status);
  8778. }
  8779. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8780. const UploadFormDataItems items = {
  8781. {"name1", "Content 1", "", ""},
  8782. {"name2", "Content 2", "file2.txt", "text/plain"},
  8783. };
  8784. Server svr;
  8785. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8786. const ContentReader &content_reader) {
  8787. ASSERT_TRUE(req.is_multipart_form_data());
  8788. std::vector<FormData> received;
  8789. content_reader(
  8790. [&](const FormData &file) {
  8791. received.push_back(file);
  8792. return true;
  8793. },
  8794. [&](const char *data, size_t data_length) {
  8795. received.back().content.append(data, data_length);
  8796. return true;
  8797. });
  8798. ASSERT_EQ(2U, received.size());
  8799. EXPECT_EQ("name1", received[0].name);
  8800. EXPECT_EQ("Content 1", received[0].content);
  8801. EXPECT_EQ("name2", received[1].name);
  8802. EXPECT_EQ("Content 2", received[1].content);
  8803. EXPECT_EQ("file2.txt", received[1].filename);
  8804. EXPECT_EQ("text/plain", received[1].content_type);
  8805. });
  8806. auto port = svr.bind_to_any_port("localhost");
  8807. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8808. auto se = detail::scope_exit([&] {
  8809. svr.stop();
  8810. t.join();
  8811. ASSERT_FALSE(svr.is_running());
  8812. });
  8813. svr.wait_until_ready();
  8814. Client cli("localhost", port);
  8815. // Whole-body serialization with a generated boundary
  8816. {
  8817. MultipartFormDataWriter writer;
  8818. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8819. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8820. writer.content_type());
  8821. auto body = writer.serialize(items);
  8822. EXPECT_EQ(body.size(), writer.content_length(items));
  8823. auto res = cli.Post("/post", body, writer.content_type());
  8824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8825. EXPECT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. // Per-part framing with a custom boundary via a content provider
  8828. {
  8829. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8830. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8831. MultipartFormDataWriter writer("custom-boundary_123");
  8832. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8833. std::string body;
  8834. for (const auto &item : items) {
  8835. body += writer.item_begin(item);
  8836. body += item.content;
  8837. body += MultipartFormDataWriter::item_end();
  8838. }
  8839. body += writer.finish();
  8840. EXPECT_EQ(body.size(), writer.content_length(items));
  8841. auto res = cli.Post(
  8842. "/post", body.size(),
  8843. [&](size_t offset, size_t length, DataSink &sink) {
  8844. sink.write(body.data() + offset, length);
  8845. return true;
  8846. },
  8847. writer.content_type());
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. }
  8852. TEST_F(ServerTest, PostContentReceiverGzip) {
  8853. cli_.set_compress(true);
  8854. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8856. ASSERT_EQ(StatusCode::OK_200, res->status);
  8857. ASSERT_EQ("content", res->body);
  8858. }
  8859. TEST_F(ServerTest, PutContentReceiver) {
  8860. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8862. ASSERT_EQ(StatusCode::OK_200, res->status);
  8863. ASSERT_EQ("content", res->body);
  8864. }
  8865. TEST_F(ServerTest, PatchContentReceiver) {
  8866. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8868. ASSERT_EQ(StatusCode::OK_200, res->status);
  8869. ASSERT_EQ("content", res->body);
  8870. }
  8871. template <typename ClientType>
  8872. void TestWithHeadersAndContentReceiver(
  8873. ClientType &cli,
  8874. std::function<Result(ClientType &, const std::string &, const Headers &,
  8875. const std::string &, const std::string &,
  8876. ContentReceiver, DownloadProgress)>
  8877. request_func) {
  8878. Headers headers;
  8879. headers.emplace("X-Custom-Header", "test-value");
  8880. std::string received_body;
  8881. auto res = request_func(
  8882. cli, "/content_receiver", headers, "content", "application/json",
  8883. [&](const char *data, size_t data_length) {
  8884. received_body.append(data, data_length);
  8885. return true;
  8886. },
  8887. nullptr);
  8888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8889. EXPECT_EQ(StatusCode::OK_200, res->status);
  8890. EXPECT_EQ("content", received_body);
  8891. }
  8892. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8893. #ifdef CPPHTTPLIB_SSL_ENABLED
  8894. using ClientT = SSLClient;
  8895. #else
  8896. using ClientT = Client;
  8897. #endif
  8898. TestWithHeadersAndContentReceiver<ClientT>(
  8899. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8900. const std::string &body, const std::string &content_type,
  8901. ContentReceiver receiver, DownloadProgress progress) {
  8902. return cli.Post(path, headers, body, content_type, receiver, progress);
  8903. });
  8904. }
  8905. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8906. #ifdef CPPHTTPLIB_SSL_ENABLED
  8907. using ClientT = SSLClient;
  8908. #else
  8909. using ClientT = Client;
  8910. #endif
  8911. TestWithHeadersAndContentReceiver<ClientT>(
  8912. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8913. const std::string &body, const std::string &content_type,
  8914. ContentReceiver receiver, DownloadProgress progress) {
  8915. return cli.Put(path, headers, body, content_type, receiver, progress);
  8916. });
  8917. }
  8918. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8919. #ifdef CPPHTTPLIB_SSL_ENABLED
  8920. using ClientT = SSLClient;
  8921. #else
  8922. using ClientT = Client;
  8923. #endif
  8924. TestWithHeadersAndContentReceiver<ClientT>(
  8925. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8926. const std::string &body, const std::string &content_type,
  8927. ContentReceiver receiver, DownloadProgress progress) {
  8928. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8929. });
  8930. }
  8931. template <typename ClientType>
  8932. void TestWithHeadersAndContentReceiverWithProgress(
  8933. ClientType &cli,
  8934. std::function<Result(ClientType &, const std::string &, const Headers &,
  8935. const std::string &, const std::string &,
  8936. ContentReceiver, DownloadProgress)>
  8937. request_func) {
  8938. Headers headers;
  8939. headers.emplace("X-Test-Header", "progress-test");
  8940. std::string received_body;
  8941. auto progress_called = false;
  8942. auto res = request_func(
  8943. cli, "/content_receiver", headers, "content", "text/plain",
  8944. [&](const char *data, size_t data_length) {
  8945. received_body.append(data, data_length);
  8946. return true;
  8947. },
  8948. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8949. progress_called = true;
  8950. return true;
  8951. });
  8952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8953. EXPECT_EQ(StatusCode::OK_200, res->status);
  8954. EXPECT_EQ("content", received_body);
  8955. EXPECT_TRUE(progress_called);
  8956. }
  8957. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8958. #ifdef CPPHTTPLIB_SSL_ENABLED
  8959. using ClientT = SSLClient;
  8960. #else
  8961. using ClientT = Client;
  8962. #endif
  8963. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8964. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8965. const std::string &body, const std::string &content_type,
  8966. ContentReceiver receiver, DownloadProgress progress) {
  8967. return cli.Post(path, headers, body, content_type, receiver, progress);
  8968. });
  8969. }
  8970. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8971. #ifdef CPPHTTPLIB_SSL_ENABLED
  8972. using ClientT = SSLClient;
  8973. #else
  8974. using ClientT = Client;
  8975. #endif
  8976. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8977. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8978. const std::string &body, const std::string &content_type,
  8979. ContentReceiver receiver, DownloadProgress progress) {
  8980. return cli.Put(path, headers, body, content_type, receiver, progress);
  8981. });
  8982. }
  8983. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8984. #ifdef CPPHTTPLIB_SSL_ENABLED
  8985. using ClientT = SSLClient;
  8986. #else
  8987. using ClientT = Client;
  8988. #endif
  8989. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8990. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8991. const std::string &body, const std::string &content_type,
  8992. ContentReceiver receiver, DownloadProgress progress) {
  8993. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8994. });
  8995. }
  8996. template <typename ClientType>
  8997. void TestWithHeadersAndContentReceiverError(
  8998. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8999. const Headers &, const std::string &,
  9000. const std::string &, ContentReceiver)>
  9001. request_func) {
  9002. Headers headers;
  9003. headers.emplace("X-Error-Test", "true");
  9004. std::string received_body;
  9005. auto receiver_failed = false;
  9006. auto res =
  9007. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  9008. [&](const char *data, size_t data_length) {
  9009. received_body.append(data, data_length);
  9010. receiver_failed = true;
  9011. return false;
  9012. });
  9013. ASSERT_FALSE(res);
  9014. EXPECT_TRUE(receiver_failed);
  9015. }
  9016. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  9017. #ifdef CPPHTTPLIB_SSL_ENABLED
  9018. using ClientT = SSLClient;
  9019. #else
  9020. using ClientT = Client;
  9021. #endif
  9022. TestWithHeadersAndContentReceiverError<ClientT>(
  9023. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9024. const std::string &body, const std::string &content_type,
  9025. ContentReceiver receiver) {
  9026. return cli.Post(path, headers, body, content_type, receiver);
  9027. });
  9028. }
  9029. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  9030. #ifdef CPPHTTPLIB_SSL_ENABLED
  9031. using ClientT = SSLClient;
  9032. #else
  9033. using ClientT = Client;
  9034. #endif
  9035. TestWithHeadersAndContentReceiverError<ClientT>(
  9036. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9037. const std::string &body, const std::string &content_type,
  9038. ContentReceiver receiver) {
  9039. return cli.Put(path, headers, body, content_type, receiver);
  9040. });
  9041. }
  9042. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  9043. #ifdef CPPHTTPLIB_SSL_ENABLED
  9044. using ClientT = SSLClient;
  9045. #else
  9046. using ClientT = Client;
  9047. #endif
  9048. TestWithHeadersAndContentReceiverError<ClientT>(
  9049. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9050. const std::string &body, const std::string &content_type,
  9051. ContentReceiver receiver) {
  9052. return cli.Patch(path, headers, body, content_type, receiver);
  9053. });
  9054. }
  9055. TEST_F(ServerTest, PostQueryStringAndBody) {
  9056. auto res =
  9057. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  9058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9059. ASSERT_EQ(StatusCode::OK_200, res->status);
  9060. }
  9061. TEST_F(ServerTest, HTTP2Magic) {
  9062. Request req;
  9063. req.method = "PRI";
  9064. req.path = "*";
  9065. req.body = "SM";
  9066. auto res = std::make_shared<Response>();
  9067. auto error = Error::Success;
  9068. auto ret = cli_.send(req, *res, error);
  9069. ASSERT_TRUE(ret);
  9070. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9071. }
  9072. TEST_F(ServerTest, KeepAlive) {
  9073. auto res = cli_.Get("/hi");
  9074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9075. EXPECT_EQ(StatusCode::OK_200, res->status);
  9076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9077. EXPECT_EQ("Hello World!", res->body);
  9078. res = cli_.Get("/hi");
  9079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9080. EXPECT_EQ(StatusCode::OK_200, res->status);
  9081. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9082. EXPECT_EQ("Hello World!", res->body);
  9083. res = cli_.Get("/hi");
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_EQ(StatusCode::OK_200, res->status);
  9086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9087. EXPECT_EQ("Hello World!", res->body);
  9088. res = cli_.Get("/not-exist");
  9089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9091. res = cli_.Post("/empty", "", "text/plain");
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9095. EXPECT_EQ("empty", res->body);
  9096. EXPECT_EQ("close", res->get_header_value("Connection"));
  9097. res = cli_.Post(
  9098. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  9099. "text/plain");
  9100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9101. EXPECT_EQ(StatusCode::OK_200, res->status);
  9102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9103. EXPECT_EQ("empty", res->body);
  9104. cli_.set_keep_alive(false);
  9105. res = cli_.Get("/last-request");
  9106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9107. EXPECT_EQ(StatusCode::OK_200, res->status);
  9108. EXPECT_EQ("close", res->get_header_value("Connection"));
  9109. }
  9110. TEST_F(ServerTest, TooManyRedirect) {
  9111. cli_.set_follow_location(true);
  9112. auto res = cli_.Get("/redirect/0");
  9113. ASSERT_TRUE(!res);
  9114. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  9115. }
  9116. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  9117. Request req;
  9118. req.method = "FOOBAR";
  9119. req.path = "/hi";
  9120. cli_.set_keep_alive(true);
  9121. auto res = cli_.send(req);
  9122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9123. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9124. EXPECT_EQ("close", res->get_header_value("Connection"));
  9125. EXPECT_FALSE(cli_.is_socket_open());
  9126. }
  9127. TEST_F(ServerTest, CustomRouteReadsBody) {
  9128. const std::string xml =
  9129. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  9130. Request req;
  9131. req.method = "PROPFIND";
  9132. req.path = "/dav/dir";
  9133. req.set_header("Depth", "1");
  9134. req.body = xml;
  9135. auto res = cli_.send(req);
  9136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9137. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9138. EXPECT_EQ(xml, res->body);
  9139. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  9140. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  9141. }
  9142. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  9143. Request req;
  9144. req.method = "PROPFIND";
  9145. req.path = "/dav/42";
  9146. auto res = cli_.send(req);
  9147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9148. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9149. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9150. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9151. }
  9152. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9153. Request req;
  9154. req.method = "PROPFIND";
  9155. req.path = "/dav-re/123";
  9156. auto res = cli_.send(req);
  9157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9158. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9159. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9160. }
  9161. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9162. Request req;
  9163. req.method = "MKCOL";
  9164. req.path = "/dav-mkcol";
  9165. auto res = cli_.send(req);
  9166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9167. EXPECT_EQ(StatusCode::Created_201, res->status);
  9168. }
  9169. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9170. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9171. Request req;
  9172. req.method = "REPORT";
  9173. req.path = "/dav-report";
  9174. req.body = xml;
  9175. auto res = cli_.send(req);
  9176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9177. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9178. EXPECT_EQ(xml, res->body);
  9179. }
  9180. // A content reader route must fire even when the request carries no body,
  9181. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9182. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9183. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9184. Request req;
  9185. req.method = "REPORT";
  9186. req.path = "/dav-report";
  9187. auto res = cli_.send(req);
  9188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9189. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9190. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9191. }
  9192. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9193. Request req;
  9194. req.method = "PROPFIND";
  9195. req.path = "/not-dav";
  9196. auto res = cli_.send(req);
  9197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9199. }
  9200. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9201. Request req;
  9202. req.method = "UNLOCK";
  9203. req.path = "/dav/dir";
  9204. cli_.set_keep_alive(true);
  9205. auto res = cli_.send(req);
  9206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9207. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9208. EXPECT_EQ("close", res->get_header_value("Connection"));
  9209. EXPECT_FALSE(cli_.is_socket_open());
  9210. }
  9211. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9212. // The mount point serves this path, but only for GET and HEAD.
  9213. auto get_res = cli_.Get("/dir/index.html");
  9214. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9215. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9216. Request req;
  9217. req.method = "PROPFIND";
  9218. req.path = "/dir/index.html";
  9219. auto res = cli_.send(req);
  9220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9222. }
  9223. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9224. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9225. cli_.set_keep_alive(true);
  9226. for (auto i = 0; i < 2; i++) {
  9227. Request req;
  9228. req.method = "PROPFIND";
  9229. req.path = "/dav/dir";
  9230. req.body = xml;
  9231. auto res = cli_.send(req);
  9232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9233. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9234. EXPECT_EQ(xml, res->body);
  9235. EXPECT_TRUE(cli_.is_socket_open());
  9236. }
  9237. // A built-in method must still be served on the same connection.
  9238. cli_.set_keep_alive(false);
  9239. auto res = cli_.Get("/hi");
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. EXPECT_EQ("close", res->get_header_value("Connection"));
  9243. }
  9244. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9245. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9246. Request req;
  9247. req.method = "PROPFIND";
  9248. req.path = "/dav/dir";
  9249. req.set_header("Expect", "100-continue");
  9250. req.body = xml;
  9251. auto res = cli_.send(req);
  9252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9253. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9254. EXPECT_EQ(xml, res->body);
  9255. }
  9256. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9258. TEST_F(ServerTest, Gzip) {
  9259. Headers headers;
  9260. headers.emplace("Accept-Encoding", "gzip, deflate");
  9261. auto res = cli_.Get("/compress", headers);
  9262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9263. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9264. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9265. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9266. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9267. "7890123456789012345678901234567890",
  9268. res->body);
  9269. EXPECT_EQ(StatusCode::OK_200, res->status);
  9270. }
  9271. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9272. Headers headers;
  9273. headers.emplace("Accept-Encoding", "gzip, deflate");
  9274. auto res = cli_.Get("/compress-with-charset", headers);
  9275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9276. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9277. EXPECT_EQ("application/json; charset=utf-8",
  9278. res->get_header_value("Content-Type"));
  9279. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9280. "7890123456789012345678901234567890",
  9281. res->body);
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. }
  9284. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9285. Headers headers;
  9286. headers.emplace("Accept-Encoding", "");
  9287. auto res = cli_.Get("/compress", headers);
  9288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9289. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9290. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9291. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9292. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9293. "7890123456789012345678901234567890",
  9294. res->body);
  9295. EXPECT_EQ(StatusCode::OK_200, res->status);
  9296. }
  9297. TEST_F(ServerTest, GzipWithContentReceiver) {
  9298. Headers headers;
  9299. headers.emplace("Accept-Encoding", "gzip, deflate");
  9300. std::string body;
  9301. auto res =
  9302. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9303. EXPECT_EQ(100U, data_length);
  9304. body.append(data, data_length);
  9305. return true;
  9306. });
  9307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9308. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9310. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9311. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9312. "7890123456789012345678901234567890",
  9313. body);
  9314. EXPECT_EQ(StatusCode::OK_200, res->status);
  9315. }
  9316. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9317. Headers headers;
  9318. headers.emplace("Accept-Encoding", "gzip, deflate");
  9319. cli_.set_decompress(false);
  9320. auto res = cli_.Get("/compress", headers);
  9321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9322. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9323. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9324. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9325. EXPECT_EQ(33U, res->body.size());
  9326. EXPECT_EQ(StatusCode::OK_200, res->status);
  9327. }
  9328. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9329. Headers headers;
  9330. headers.emplace("Accept-Encoding", "");
  9331. std::string body;
  9332. auto res =
  9333. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9334. EXPECT_EQ(100U, data_length);
  9335. body.append(data, data_length);
  9336. return true;
  9337. });
  9338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9339. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9341. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9342. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9343. "7890123456789012345678901234567890",
  9344. body);
  9345. EXPECT_EQ(StatusCode::OK_200, res->status);
  9346. }
  9347. TEST_F(ServerTest, NoGzip) {
  9348. Headers headers;
  9349. headers.emplace("Accept-Encoding", "gzip, deflate");
  9350. auto res = cli_.Get("/nocompress", headers);
  9351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9352. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9353. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9354. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9355. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9356. "7890123456789012345678901234567890",
  9357. res->body);
  9358. EXPECT_EQ(StatusCode::OK_200, res->status);
  9359. }
  9360. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9361. Headers headers;
  9362. headers.emplace("Accept-Encoding", "gzip, deflate");
  9363. std::string body;
  9364. auto res = cli_.Get("/nocompress", headers,
  9365. [&](const char *data, size_t data_length) {
  9366. EXPECT_EQ(100U, data_length);
  9367. body.append(data, data_length);
  9368. return true;
  9369. });
  9370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9371. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9372. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9373. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9375. "7890123456789012345678901234567890",
  9376. body);
  9377. EXPECT_EQ(StatusCode::OK_200, res->status);
  9378. }
  9379. TEST_F(ServerTest, MultipartFormDataGzip) {
  9380. UploadFormDataItems items = {
  9381. {"key1", "test", "", ""},
  9382. {"key2", "--abcdefg123", "", ""},
  9383. };
  9384. cli_.set_compress(true);
  9385. auto res = cli_.Post("/compress-multipart", items);
  9386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9387. EXPECT_EQ(StatusCode::OK_200, res->status);
  9388. }
  9389. #endif
  9390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9391. // Static file compression is opt-in, so these run their own server rather than
  9392. // flipping it on for the shared ServerTest fixture, which would silently
  9393. // rewrite what every other static file test is asserting.
  9394. class StaticFileCompressionTest : public ::testing::Test {
  9395. protected:
  9396. void TearDown() override {
  9397. if (t_.joinable()) {
  9398. svr_.stop();
  9399. t_.join();
  9400. }
  9401. }
  9402. int start(const std::function<void(Server &)> &configure = nullptr) {
  9403. // Serves the same tree as a directory of build-time compressed assets
  9404. // would be served: the mount point names the coding the files are already
  9405. // stored in. Registered before "/" so it is the one that matches.
  9406. svr_.set_mount_point("/pre-encoded", "./www",
  9407. {{"Content-Encoding", "gzip"}});
  9408. svr_.set_mount_point("/", "./www");
  9409. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9410. res.set_file_content("./www/dir/index.html", "text/html");
  9411. });
  9412. svr_.Get("/pre-encoded-file-content",
  9413. [](const Request & /*req*/, Response &res) {
  9414. res.set_header("Content-Encoding", "gzip");
  9415. res.set_file_content("./www/dir/index.html", "text/html");
  9416. });
  9417. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9418. res.set_content_provider(
  9419. 6, "text/plain",
  9420. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9421. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9422. return true;
  9423. });
  9424. });
  9425. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9426. res.set_content_provider(
  9427. 1000, "text/plain",
  9428. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9429. if (offset < 100) {
  9430. std::string data(100, 'A');
  9431. sink.write(data.data(), data.size());
  9432. return true;
  9433. }
  9434. std::this_thread::sleep_for(std::chrono::seconds(2));
  9435. std::string data(900, 'B');
  9436. sink.write(data.data(), data.size());
  9437. return true;
  9438. });
  9439. });
  9440. if (configure) { configure(svr_); }
  9441. auto port = svr_.bind_to_any_port(HOST);
  9442. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9443. svr_.wait_until_ready();
  9444. return port;
  9445. }
  9446. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9447. // Every file under ./www except 1MB.txt is smaller than the default
  9448. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9449. // it out of the way.
  9450. static void enable_without_floor(Server &svr) {
  9451. svr.set_static_file_compression(true);
  9452. svr.set_static_file_compression_min_length(0);
  9453. }
  9454. Server svr_;
  9455. std::thread t_;
  9456. };
  9457. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9458. auto port = start();
  9459. Client cli(HOST, port);
  9460. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9462. EXPECT_EQ(StatusCode::OK_200, res->status);
  9463. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9464. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9465. EXPECT_EQ(1048576U, res->body.size());
  9466. }
  9467. TEST_F(StaticFileCompressionTest, MountPoint) {
  9468. auto port = start(enable);
  9469. Client cli(HOST, port);
  9470. cli.set_decompress(false);
  9471. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9473. EXPECT_EQ(StatusCode::OK_200, res->status);
  9474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9475. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9476. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9477. // The response stays self-delimiting: a length, not a chunked body.
  9478. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9479. EXPECT_EQ(std::to_string(res->body.size()),
  9480. res->get_header_value("Content-Length"));
  9481. EXPECT_LT(res->body.size(), 1048576U);
  9482. EXPECT_FALSE(res->body.empty());
  9483. }
  9484. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9485. auto port = start(enable);
  9486. Client cli(HOST, port);
  9487. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9489. EXPECT_EQ(StatusCode::OK_200, res->status);
  9490. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9491. EXPECT_EQ(1048576U, res->body.size());
  9492. }
  9493. TEST_F(StaticFileCompressionTest, FileContent) {
  9494. auto port = start(enable_without_floor);
  9495. Client cli(HOST, port);
  9496. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9498. EXPECT_EQ(StatusCode::OK_200, res->status);
  9499. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9500. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9501. EXPECT_EQ(104U, res->body.size());
  9502. }
  9503. // A handler that serves an already-encoded file names the coding itself. The
  9504. // file-backed path decided its coding from Accept-Encoding and the content
  9505. // type alone, so it compressed the stored bytes a second time and appended a
  9506. // second Content-Encoding field line.
  9507. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9508. auto port = start(enable_without_floor);
  9509. Client cli(HOST, port);
  9510. cli.set_decompress(false);
  9511. auto res = cli.Get("/pre-encoded-file-content",
  9512. Headers{{"Accept-Encoding", "gzip"}});
  9513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9514. EXPECT_EQ(StatusCode::OK_200, res->status);
  9515. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9516. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9517. // Vary belongs to a coding the server chose, and it chose none here.
  9518. EXPECT_FALSE(res->has_header("Vary"));
  9519. // The file travels exactly as it is stored on disk.
  9520. EXPECT_EQ(104U, res->body.size());
  9521. }
  9522. // The 1MB file clears the default floor, so this one runs the configuration a
  9523. // deployment would actually have.
  9524. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9525. auto port = start(enable);
  9526. Client cli(HOST, port);
  9527. cli.set_decompress(false);
  9528. auto res =
  9529. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9531. EXPECT_EQ(StatusCode::OK_200, res->status);
  9532. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9533. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9534. EXPECT_FALSE(res->has_header("Vary"));
  9535. EXPECT_EQ(1048576U, res->body.size());
  9536. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9537. }
  9538. TEST_F(StaticFileCompressionTest, Head) {
  9539. auto port = start(enable);
  9540. Client cli(HOST, port);
  9541. cli.set_decompress(false);
  9542. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9543. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9544. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9546. EXPECT_EQ(StatusCode::OK_200, res->status);
  9547. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9548. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9549. // HEAD still reports the size a GET would return.
  9550. EXPECT_EQ(get->get_header_value("Content-Length"),
  9551. res->get_header_value("Content-Length"));
  9552. EXPECT_TRUE(res->body.empty());
  9553. }
  9554. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9555. auto port = start(enable);
  9556. Client cli(HOST, port);
  9557. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9558. {"Accept-Encoding", "gzip"}});
  9559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9561. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9562. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9563. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9564. EXPECT_EQ("cd", res->body);
  9565. }
  9566. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9567. auto port = start(enable);
  9568. Client cli(HOST, port);
  9569. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9571. EXPECT_EQ(StatusCode::OK_200, res->status);
  9572. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9573. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9574. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9575. }
  9576. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9577. auto port = start(enable);
  9578. Client cli(HOST, port);
  9579. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9581. EXPECT_EQ(StatusCode::OK_200, res->status);
  9582. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9583. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9584. EXPECT_TRUE(res->body.empty());
  9585. }
  9586. TEST_F(StaticFileCompressionTest, MinLength) {
  9587. auto port = start(enable);
  9588. Client cli(HOST, port);
  9589. // 104 bytes, well under the default floor. Compressing it would add the
  9590. // gzip header and trailer to a body that already fits in one packet.
  9591. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9593. EXPECT_EQ(StatusCode::OK_200, res->status);
  9594. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9595. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9596. }
  9597. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9598. auto port = start([](Server &svr) {
  9599. svr.set_static_file_compression(true);
  9600. svr.set_static_file_compression_min_length(1);
  9601. });
  9602. Client cli(HOST, port);
  9603. cli.set_decompress(false);
  9604. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9606. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9607. // A 9-byte file comes back larger than it went in, because gzip's header and
  9608. // trailer outweigh anything deflate can save. That is the end of the range
  9609. // the floor exists to keep out.
  9610. EXPECT_GT(res->body.size(), 9U);
  9611. }
  9612. TEST_F(StaticFileCompressionTest, MaxLength) {
  9613. auto port = start([](Server &svr) {
  9614. svr.set_static_file_compression(true);
  9615. svr.set_static_file_compression_min_length(0);
  9616. svr.set_static_file_compression_max_length(1024);
  9617. });
  9618. Client cli(HOST, port);
  9619. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9620. // defines `small` as a macro on Windows.
  9621. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9622. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9623. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9624. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9625. // Under it: compressed.
  9626. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9627. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9628. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9629. }
  9630. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9631. auto port = start(enable_without_floor);
  9632. Client cli(HOST, port);
  9633. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9634. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9635. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9636. auto identity_etag = identity->get_header_value("ETag");
  9637. ASSERT_FALSE(identity_etag.empty());
  9638. auto gzipped =
  9639. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9640. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9641. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9642. auto gzip_etag = gzipped->get_header_value("ETag");
  9643. ASSERT_FALSE(gzip_etag.empty());
  9644. // Two representations, two validators.
  9645. EXPECT_NE(identity_etag, gzip_etag);
  9646. // Each one revalidates against the request that would produce it...
  9647. auto fresh =
  9648. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9649. {"If-None-Match", gzip_etag}});
  9650. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9651. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9652. auto fresh_identity =
  9653. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9654. {"If-None-Match", identity_etag}});
  9655. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9656. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9657. // ...and not against the other representation.
  9658. auto crossed =
  9659. cli.Get("/dir/index.html",
  9660. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9661. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9662. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9663. }
  9664. // The opt-in covers responses the server reads off disk itself. A caller's own
  9665. // known-length provider keeps its Content-Length and, more importantly, keeps
  9666. // delivering incrementally: routing it through a compressor would hold every
  9667. // write back until zlib's window filled.
  9668. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9669. auto port = start(enable);
  9670. Client cli(HOST, port);
  9671. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(StatusCode::OK_200, res->status);
  9674. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9675. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9676. EXPECT_EQ("aaabbb", res->body);
  9677. }
  9678. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9679. auto port = start(enable);
  9680. Client cli(HOST, port);
  9681. cli.set_read_timeout(1, 0);
  9682. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9683. Headers{{"Accept-Encoding", "gzip"}});
  9684. ASSERT_TRUE(handle.is_valid());
  9685. // The provider writes 100 bytes and then stalls for longer than the read
  9686. // timeout. Those first bytes have to arrive anyway: run the response through
  9687. // a compressor and zlib holds them until its window fills, so the read would
  9688. // come back empty instead.
  9689. char buf[256];
  9690. auto n = handle.read(buf, sizeof(buf));
  9691. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9692. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9693. }
  9694. #endif
  9695. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9696. TEST_F(ServerTest, Brotli) {
  9697. Headers headers;
  9698. headers.emplace("Accept-Encoding", "br");
  9699. auto res = cli_.Get("/compress", headers);
  9700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9701. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9702. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9703. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9704. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9705. "7890123456789012345678901234567890",
  9706. res->body);
  9707. EXPECT_EQ(StatusCode::OK_200, res->status);
  9708. }
  9709. #endif
  9710. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9711. TEST_F(ServerTest, Zstd) {
  9712. Headers headers;
  9713. headers.emplace("Accept-Encoding", "zstd");
  9714. auto res = cli_.Get("/compress", headers);
  9715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9716. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9717. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9718. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9719. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9720. "7890123456789012345678901234567890",
  9721. res->body);
  9722. EXPECT_EQ(StatusCode::OK_200, res->status);
  9723. }
  9724. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9725. Headers headers;
  9726. headers.emplace("Accept-Encoding", "");
  9727. auto res = cli_.Get("/compress", headers);
  9728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9729. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9731. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9732. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9733. "7890123456789012345678901234567890",
  9734. res->body);
  9735. EXPECT_EQ(StatusCode::OK_200, res->status);
  9736. }
  9737. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9738. Headers headers;
  9739. headers.emplace("Accept-Encoding", "zstd");
  9740. std::string body;
  9741. auto res =
  9742. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9743. EXPECT_EQ(100U, data_length);
  9744. body.append(data, data_length);
  9745. return true;
  9746. });
  9747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9748. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9749. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9750. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9751. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9752. "7890123456789012345678901234567890",
  9753. body);
  9754. EXPECT_EQ(StatusCode::OK_200, res->status);
  9755. }
  9756. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9757. Headers headers;
  9758. headers.emplace("Accept-Encoding", "zstd");
  9759. cli_.set_decompress(false);
  9760. auto res = cli_.Get("/compress", headers);
  9761. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9762. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9763. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9764. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9766. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9768. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9769. EXPECT_EQ(StatusCode::OK_200, res->status);
  9770. ASSERT_EQ(26U, res->body.size());
  9771. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9772. 0);
  9773. }
  9774. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9775. Headers headers;
  9776. headers.emplace("Accept-Encoding", "");
  9777. std::string body;
  9778. auto res =
  9779. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9780. EXPECT_EQ(100U, data_length);
  9781. body.append(data, data_length);
  9782. return true;
  9783. });
  9784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9785. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9786. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9787. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9788. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9789. "7890123456789012345678901234567890",
  9790. body);
  9791. EXPECT_EQ(StatusCode::OK_200, res->status);
  9792. }
  9793. TEST_F(ServerTest, NoZstd) {
  9794. Headers headers;
  9795. headers.emplace("Accept-Encoding", "zstd");
  9796. auto res = cli_.Get("/nocompress", headers);
  9797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9798. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9799. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9800. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9801. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9802. "7890123456789012345678901234567890",
  9803. res->body);
  9804. EXPECT_EQ(StatusCode::OK_200, res->status);
  9805. }
  9806. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9807. Headers headers;
  9808. headers.emplace("Accept-Encoding", "zstd");
  9809. std::string body;
  9810. auto res = cli_.Get("/nocompress", headers,
  9811. [&](const char *data, size_t data_length) {
  9812. EXPECT_EQ(100U, data_length);
  9813. body.append(data, data_length);
  9814. return true;
  9815. });
  9816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9817. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9818. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9819. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9820. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9821. "7890123456789012345678901234567890",
  9822. body);
  9823. EXPECT_EQ(StatusCode::OK_200, res->status);
  9824. }
  9825. // TODO: How to enable zstd ??
  9826. TEST_F(ServerTest, MultipartFormDataZstd) {
  9827. UploadFormDataItems items = {
  9828. {"key1", "test", "", ""},
  9829. {"key2", "--abcdefg123", "", ""},
  9830. };
  9831. Headers headers;
  9832. headers.emplace("Accept-Encoding", "zstd");
  9833. cli_.set_compress(true);
  9834. auto res = cli_.Post("/compress-multipart", headers, items);
  9835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9836. EXPECT_EQ(StatusCode::OK_200, res->status);
  9837. }
  9838. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9839. Headers headers;
  9840. headers.emplace("Accept-Encoding", "zstd");
  9841. cli_.set_compress(true);
  9842. auto res = cli_.Put(
  9843. "/put", headers, 3,
  9844. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9845. sink.os << "PUT";
  9846. return true;
  9847. },
  9848. "text/plain");
  9849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9850. EXPECT_EQ(StatusCode::OK_200, res->status);
  9851. EXPECT_EQ("PUT", res->body);
  9852. }
  9853. // Pre-compression logging tests
  9854. TEST_F(ServerTest, PreCompressionLogging) {
  9855. // Test data for compression (matches the actual /compress endpoint content)
  9856. const std::string test_content =
  9857. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9858. "3456789012345678901234567890";
  9859. // Variables to capture logging data
  9860. std::string pre_compression_body;
  9861. std::string pre_compression_content_type;
  9862. std::string pre_compression_content_encoding;
  9863. std::string post_compression_body;
  9864. std::string post_compression_content_type;
  9865. std::string post_compression_content_encoding;
  9866. // Set up pre-compression logger
  9867. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9868. const Response &res) {
  9869. pre_compression_body = res.body;
  9870. pre_compression_content_type = res.get_header_value("Content-Type");
  9871. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9872. });
  9873. // Set up post-compression logger
  9874. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9875. post_compression_body = res.body;
  9876. post_compression_content_type = res.get_header_value("Content-Type");
  9877. post_compression_content_encoding =
  9878. res.get_header_value("Content-Encoding");
  9879. });
  9880. // Test with gzip compression
  9881. Headers headers;
  9882. headers.emplace("Accept-Encoding", "gzip");
  9883. auto res = cli_.Get("/compress", headers);
  9884. // Verify response was compressed
  9885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9886. EXPECT_EQ(StatusCode::OK_200, res->status);
  9887. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9888. // Verify pre-compression logger captured uncompressed content
  9889. EXPECT_EQ(test_content, pre_compression_body);
  9890. EXPECT_EQ("text/plain", pre_compression_content_type);
  9891. EXPECT_TRUE(pre_compression_content_encoding
  9892. .empty()); // No encoding header before compression
  9893. // Verify post-compression logger captured compressed content
  9894. EXPECT_NE(test_content,
  9895. post_compression_body); // Should be different after compression
  9896. EXPECT_EQ("text/plain", post_compression_content_type);
  9897. EXPECT_EQ("gzip", post_compression_content_encoding);
  9898. // Verify compressed content is smaller
  9899. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9900. }
  9901. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9902. const std::string test_content =
  9903. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9904. "3456789012345678901234567890";
  9905. std::string pre_compression_body;
  9906. std::string post_compression_body;
  9907. svr_.set_pre_compression_logger(
  9908. [&](const Request & /*req*/, const Response &res) {
  9909. pre_compression_body = res.body;
  9910. });
  9911. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9912. post_compression_body = res.body;
  9913. });
  9914. Headers headers;
  9915. headers.emplace("Accept-Encoding", "br");
  9916. auto res = cli_.Get("/compress", headers);
  9917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9918. EXPECT_EQ(StatusCode::OK_200, res->status);
  9919. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9920. // Verify pre-compression content is uncompressed
  9921. EXPECT_EQ(test_content, pre_compression_body);
  9922. // Verify post-compression content is compressed
  9923. EXPECT_NE(test_content, post_compression_body);
  9924. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9925. }
  9926. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9927. const std::string test_content =
  9928. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9929. "3456789012345678901234567890";
  9930. std::string pre_compression_body;
  9931. std::string post_compression_body;
  9932. svr_.set_pre_compression_logger(
  9933. [&](const Request & /*req*/, const Response &res) {
  9934. pre_compression_body = res.body;
  9935. });
  9936. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9937. post_compression_body = res.body;
  9938. });
  9939. // Request without compression (use /nocompress endpoint)
  9940. Headers headers;
  9941. auto res = cli_.Get("/nocompress", headers);
  9942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9943. EXPECT_EQ(StatusCode::OK_200, res->status);
  9944. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9945. // Pre-compression logger should not be called when no compression is applied
  9946. EXPECT_TRUE(
  9947. pre_compression_body.empty()); // Pre-compression logger not called
  9948. EXPECT_EQ(
  9949. test_content,
  9950. post_compression_body); // Post-compression logger captures final content
  9951. }
  9952. TEST_F(ServerTest, LoggerSeesContentLength) {
  9953. size_t logged_content_length = 0;
  9954. std::string logged_content_length_header;
  9955. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9956. logged_content_length = res.content_length_;
  9957. logged_content_length_header = res.get_header_value("Content-Length");
  9958. });
  9959. auto res = cli_.Get("/nocompress");
  9960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9961. EXPECT_EQ(StatusCode::OK_200, res->status);
  9962. EXPECT_EQ(res->body.size(), logged_content_length);
  9963. EXPECT_EQ(std::to_string(logged_content_length),
  9964. logged_content_length_header);
  9965. }
  9966. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9967. const std::string test_content =
  9968. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9969. "3456789012345678901234567890";
  9970. std::string pre_compression_body;
  9971. bool pre_logger_called = false;
  9972. // Set only pre-compression logger
  9973. svr_.set_pre_compression_logger(
  9974. [&](const Request & /*req*/, const Response &res) {
  9975. pre_compression_body = res.body;
  9976. pre_logger_called = true;
  9977. });
  9978. Headers headers;
  9979. headers.emplace("Accept-Encoding", "gzip");
  9980. auto res = cli_.Get("/compress", headers);
  9981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9982. EXPECT_EQ(StatusCode::OK_200, res->status);
  9983. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9984. // Verify pre-compression logger was called
  9985. EXPECT_TRUE(pre_logger_called);
  9986. EXPECT_EQ(test_content, pre_compression_body);
  9987. }
  9988. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9989. {
  9990. // Test with Expect: 100-continue header - success case
  9991. // Server returns 100 Continue, client sends body, server returns 200 OK
  9992. Request req;
  9993. req.method = "POST";
  9994. req.path = "/post-large";
  9995. req.set_header("Expect", "100-continue");
  9996. req.body = LARGE_DATA;
  9997. Response res;
  9998. auto error = Error::Success;
  9999. cli_.set_keep_alive(true);
  10000. auto ret = cli_.send(req, res, error);
  10001. EXPECT_TRUE(ret);
  10002. EXPECT_EQ(StatusCode::OK_200, res.status);
  10003. EXPECT_EQ(LARGE_DATA, res.body);
  10004. }
  10005. {
  10006. // Test with Expect: 100-continue header - error case
  10007. // Client should not send the body when server returns an error
  10008. Request req;
  10009. req.method = "POST";
  10010. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  10011. req.set_header("Expect", "100-continue");
  10012. req.body = LARGE_DATA;
  10013. Response res;
  10014. auto error = Error::Success;
  10015. auto start = std::chrono::high_resolution_clock::now();
  10016. cli_.set_keep_alive(true);
  10017. auto ret = cli_.send(req, res, error);
  10018. auto end = std::chrono::high_resolution_clock::now();
  10019. auto elapsed =
  10020. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  10021. .count();
  10022. // With Expect: 100-continue, request completes successfully but with error
  10023. EXPECT_TRUE(ret);
  10024. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  10025. EXPECT_EQ("close", res.get_header_value("Connection"));
  10026. EXPECT_FALSE(cli_.is_socket_open());
  10027. EXPECT_LE(elapsed, 2000);
  10028. }
  10029. {
  10030. // Send an extra GET request to ensure error recovery without hanging
  10031. Request req;
  10032. req.method = "GET";
  10033. req.path = "/hi";
  10034. auto start = std::chrono::high_resolution_clock::now();
  10035. auto res = cli_.send(req);
  10036. auto end = std::chrono::high_resolution_clock::now();
  10037. auto elapsed =
  10038. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  10039. .count();
  10040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10041. EXPECT_EQ(StatusCode::OK_200, res->status);
  10042. EXPECT_EQ("Hello World!", res->body);
  10043. EXPECT_LE(elapsed, 500);
  10044. }
  10045. }
  10046. TEST(ZstdDecompressor, ChunkedDecompression) {
  10047. std::string data;
  10048. for (size_t i = 0; i < 32 * 1024; ++i) {
  10049. data.push_back(static_cast<char>('a' + i % 26));
  10050. }
  10051. std::string compressed_data;
  10052. {
  10053. httplib::detail::zstd_compressor compressor;
  10054. bool result = compressor.compress(
  10055. data.data(), data.size(),
  10056. /*last=*/true,
  10057. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  10058. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  10059. compressed_data_size);
  10060. return true;
  10061. });
  10062. ASSERT_TRUE(result);
  10063. }
  10064. std::string decompressed_data;
  10065. {
  10066. httplib::detail::zstd_decompressor decompressor;
  10067. // Chunk size is chosen specifically to have a decompressed chunk size equal
  10068. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  10069. size_t chunk_size = 130;
  10070. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  10071. chunk_begin += chunk_size) {
  10072. size_t current_chunk_size =
  10073. std::min(compressed_data.size() - chunk_begin, chunk_size);
  10074. bool result = decompressor.decompress(
  10075. compressed_data.data() + chunk_begin, current_chunk_size,
  10076. [&](const char *decompressed_data_chunk,
  10077. size_t decompressed_data_chunk_size) {
  10078. decompressed_data.insert(decompressed_data.size(),
  10079. decompressed_data_chunk,
  10080. decompressed_data_chunk_size);
  10081. return true;
  10082. });
  10083. ASSERT_TRUE(result);
  10084. }
  10085. }
  10086. ASSERT_EQ(data, decompressed_data);
  10087. }
  10088. TEST(ZstdDecompressor, Decompress) {
  10089. std::string original_text = "Compressed with ZSTD";
  10090. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  10091. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  10092. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  10093. 0x20, 0x5a, 0x53, 0x54, 0x44};
  10094. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  10095. std::string decompressed_data;
  10096. {
  10097. httplib::detail::zstd_decompressor decompressor;
  10098. bool result = decompressor.decompress(
  10099. compressed_data.data(), compressed_data.size(),
  10100. [&](const char *decompressed_data_chunk,
  10101. size_t decompressed_data_chunk_size) {
  10102. decompressed_data.insert(decompressed_data.size(),
  10103. decompressed_data_chunk,
  10104. decompressed_data_chunk_size);
  10105. return true;
  10106. });
  10107. ASSERT_TRUE(result);
  10108. }
  10109. ASSERT_EQ(original_text, decompressed_data);
  10110. }
  10111. #endif
  10112. // Sends a raw request to a server listening at HOST:PORT, writing it in
  10113. // separate chunks so that the server sees each part in its own read(). Used to
  10114. // place a read boundary at a specific offset of a request body.
  10115. static bool send_request_in_parts(time_t read_timeout_sec,
  10116. const std::vector<std::string> &parts,
  10117. std::string *resp = nullptr,
  10118. int port = PORT) {
  10119. auto error = Error::Success;
  10120. auto client_sock = detail::create_client_socket(
  10121. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10122. /*connection_timeout_sec=*/5, 0,
  10123. /*read_timeout_sec=*/5, 0,
  10124. /*write_timeout_sec=*/5, 0, std::string(), error);
  10125. if (client_sock == INVALID_SOCKET) { return false; }
  10126. auto ret = detail::process_client_socket(
  10127. client_sock, read_timeout_sec, 0, 0, 0, 0,
  10128. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  10129. for (size_t i = 0; i < parts.size(); i++) {
  10130. const auto &part = parts[i];
  10131. if (part.size() !=
  10132. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  10133. return false;
  10134. }
  10135. if (i + 1 < parts.size()) {
  10136. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10137. }
  10138. }
  10139. char buf[512];
  10140. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  10141. while (line_reader.getline()) {
  10142. if (resp) { *resp += line_reader.ptr(); }
  10143. }
  10144. return true;
  10145. });
  10146. detail::close_socket(client_sock);
  10147. return ret;
  10148. }
  10149. // Sends a raw request to a server listening at HOST:PORT.
  10150. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10151. std::string *resp = nullptr, int port = PORT) {
  10152. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10153. }
  10154. #ifdef CPPHTTPLIB_SSL_ENABLED
  10155. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10157. ASSERT_TRUE(svr.is_valid());
  10158. svr.set_read_timeout(1, 0);
  10159. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10160. auto se = detail::scope_exit([&] {
  10161. svr.stop();
  10162. t.join();
  10163. ASSERT_FALSE(svr.is_running());
  10164. });
  10165. svr.wait_until_ready();
  10166. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10167. // keeps each wait well within the read timeout. The server gives up a
  10168. // second in, so the bytes sent after that fail.
  10169. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10170. parts.resize(26, std::string(1, '\0'));
  10171. EXPECT_FALSE(send_request_in_parts(5, parts));
  10172. }
  10173. #endif
  10174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10175. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10176. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10177. const std::vector<std::string> &parts,
  10178. std::string *resp = nullptr,
  10179. int port = PORT) {
  10180. auto error = Error::Success;
  10181. auto sock = detail::create_client_socket(
  10182. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10183. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10184. /*write_timeout_sec=*/5, 0, std::string(), error);
  10185. if (sock == INVALID_SOCKET) { return false; }
  10186. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10187. auto ctx = SSL_CTX_new(TLS_client_method());
  10188. auto ssl = SSL_new(ctx);
  10189. auto ssl_se = detail::scope_exit([&] {
  10190. SSL_free(ssl);
  10191. SSL_CTX_free(ctx);
  10192. });
  10193. SSL_set_fd(ssl, static_cast<int>(sock));
  10194. if (SSL_connect(ssl) != 1) { return false; }
  10195. for (size_t i = 0; i < parts.size(); i++) {
  10196. const auto &part = parts[i];
  10197. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10198. static_cast<int>(part.size())) {
  10199. return false;
  10200. }
  10201. if (i + 1 < parts.size()) {
  10202. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10203. }
  10204. }
  10205. char buf[512];
  10206. int n;
  10207. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10208. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10209. }
  10210. return true;
  10211. }
  10212. #endif
  10213. // The request line, then a header value a byte at a time.
  10214. static std::vector<std::string> slow_request_head_parts() {
  10215. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10216. parts.resize(26, "a");
  10217. parts.emplace_back("\r\n\r\n");
  10218. return parts;
  10219. }
  10220. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10221. // within the one-second read timeout. The server gives up a second in, before
  10222. // the head is complete.
  10223. static void
  10224. expect_slow_request_head_dropped(Server &svr,
  10225. const std::function<std::string()> &send) {
  10226. std::atomic<bool> handled(false);
  10227. svr.Get("/", [&](const Request &, Response &res) {
  10228. handled = true;
  10229. res.set_content("ok", "text/plain");
  10230. });
  10231. svr.set_read_timeout(1, 0);
  10232. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10233. auto se = detail::scope_exit([&] {
  10234. svr.stop();
  10235. t.join();
  10236. ASSERT_FALSE(svr.is_running());
  10237. });
  10238. svr.wait_until_ready();
  10239. auto resp = send();
  10240. EXPECT_FALSE(handled);
  10241. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10242. }
  10243. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10244. Server svr;
  10245. expect_slow_request_head_dropped(svr, [] {
  10246. std::string resp;
  10247. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10248. return resp;
  10249. });
  10250. }
  10251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10252. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10254. ASSERT_TRUE(svr.is_valid());
  10255. expect_slow_request_head_dropped(svr, [] {
  10256. std::string resp;
  10257. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10258. return resp;
  10259. });
  10260. }
  10261. #endif
  10262. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10263. Server svr;
  10264. std::string header_value;
  10265. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10266. header_value = req.get_header_value("foo");
  10267. res.set_content("ok", "text/plain");
  10268. });
  10269. thread t = thread([&] { svr.listen(HOST, PORT); });
  10270. auto se = detail::scope_exit([&] {
  10271. svr.stop();
  10272. t.join();
  10273. ASSERT_FALSE(svr.is_running());
  10274. });
  10275. svr.wait_until_ready();
  10276. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10277. // like characters are not treated the same - use vertical tab and escape.
  10278. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10279. "foo: \t \v bar \x1B\t \r\n"
  10280. "Connection: close\r\n"
  10281. "\r\n";
  10282. std::string res;
  10283. ASSERT_TRUE(send_request(5, req, &res));
  10284. EXPECT_EQ(header_value, "");
  10285. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10286. }
  10287. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10288. Server svr;
  10289. std::string received;
  10290. svr.Get("/order", [&](const Request &req, Response &res) {
  10291. received = entries_to_string(req.headers);
  10292. res.set_content("ok", "text/plain");
  10293. });
  10294. auto port = svr.bind_to_any_port(HOST);
  10295. thread t = thread([&] { svr.listen_after_bind(); });
  10296. auto se = detail::scope_exit([&] {
  10297. svr.stop();
  10298. t.join();
  10299. ASSERT_FALSE(svr.is_running());
  10300. });
  10301. svr.wait_until_ready();
  10302. const std::string req = "GET /order HTTP/1.1\r\n"
  10303. "Host: localhost\r\n"
  10304. "X-First: 1\r\n"
  10305. "X-Dup: a\r\n"
  10306. "X-Second: 2\r\n"
  10307. "X-Dup: b\r\n"
  10308. "Connection: close\r\n"
  10309. "\r\n";
  10310. std::string res;
  10311. ASSERT_TRUE(send_request(5, req, &res, port));
  10312. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10313. EXPECT_EQ(
  10314. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10315. received);
  10316. }
  10317. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10318. Server svr;
  10319. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10320. res.set_header("Set-Cookie", "first=1");
  10321. res.set_header("X-Between", "y");
  10322. res.set_header("Set-Cookie", "second=2");
  10323. res.set_content("ok", "text/plain");
  10324. });
  10325. auto port = svr.bind_to_any_port(HOST);
  10326. thread t = thread([&] { svr.listen_after_bind(); });
  10327. auto se = detail::scope_exit([&] {
  10328. svr.stop();
  10329. t.join();
  10330. ASSERT_FALSE(svr.is_running());
  10331. });
  10332. svr.wait_until_ready();
  10333. Client cli(HOST, port);
  10334. auto res = cli.Get("/cookies");
  10335. ASSERT_TRUE(res);
  10336. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10337. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10338. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10339. }
  10340. // A stream may send a byte at a time with a small extension on each chunk,
  10341. // however long it runs
  10342. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10343. Server svr;
  10344. svr.Post("/count", [](const Request &req, Response &res) {
  10345. res.set_content(std::to_string(req.body.size()), "text/plain");
  10346. });
  10347. auto port = svr.bind_to_any_port(HOST);
  10348. ASSERT_LT(0, port);
  10349. thread t = thread([&] { svr.listen_after_bind(); });
  10350. auto se = detail::scope_exit([&] {
  10351. svr.stop();
  10352. t.join();
  10353. ASSERT_FALSE(svr.is_running());
  10354. });
  10355. svr.wait_until_ready();
  10356. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10357. "\r\nTransfer-Encoding: chunked\r\n"
  10358. "Connection: close\r\n\r\n";
  10359. for (auto i = 0; i < 4096; i++) {
  10360. req += "1;a=b\r\nx\r\n";
  10361. }
  10362. req += "0\r\n\r\n";
  10363. std::string res;
  10364. ASSERT_TRUE(send_request(5, req, &res, port));
  10365. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10366. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10367. }
  10368. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10369. Server svr;
  10370. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10371. auto i = new int(0);
  10372. res.set_header("Trailer", "X-Safe, X-Reflected");
  10373. res.set_chunked_content_provider(
  10374. "text/plain",
  10375. [i](size_t /*offset*/, DataSink &sink) {
  10376. if (*i == 0) {
  10377. sink.os << "body";
  10378. } else {
  10379. Headers trailer;
  10380. // A valid trailer that must survive.
  10381. trailer.emplace("X-Safe", "safe");
  10382. // Attacker-controlled value carrying CR/LF (response splitting).
  10383. trailer.emplace("X-Reflected",
  10384. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10385. // Attacker-controlled name carrying CR/LF.
  10386. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10387. sink.done_with_trailer(trailer);
  10388. }
  10389. (*i)++;
  10390. return true;
  10391. },
  10392. [i](bool /*success*/) { delete i; });
  10393. });
  10394. thread t = thread([&] { svr.listen(HOST, PORT); });
  10395. auto se = detail::scope_exit([&] {
  10396. svr.stop();
  10397. t.join();
  10398. ASSERT_FALSE(svr.is_running());
  10399. });
  10400. svr.wait_until_ready();
  10401. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10402. "Host: " + HOST +
  10403. "\r\n"
  10404. "Connection: close\r\n"
  10405. "\r\n";
  10406. std::string res;
  10407. ASSERT_TRUE(send_request(5, req, &res));
  10408. // The injected fields must not appear anywhere in the raw response.
  10409. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10410. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10411. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10412. // Invalid trailers are dropped entirely, matching set_header().
  10413. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10414. // The valid trailer still passes through.
  10415. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10416. }
  10417. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10418. // A custom header writer gets only the fields the default one writes
  10419. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10420. std::string s;
  10421. for (const auto &h : hdrs) {
  10422. s += h.first + ": " + h.second + "\r\n";
  10423. }
  10424. s += "\r\n";
  10425. return strm.write(s.data(), s.size());
  10426. };
  10427. for (auto custom_writer : {false, true}) {
  10428. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10429. Server svr;
  10430. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10431. svr.set_post_routing_handler([](const Request &, Response &res) {
  10432. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10433. });
  10434. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10435. // res.headers is a public field an application can populate directly,
  10436. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10437. // A valid header that must survive.
  10438. res.headers.emplace("X-Safe", "safe");
  10439. // Attacker-controlled value carrying CR/LF (response splitting).
  10440. res.headers.emplace("X-Reflected",
  10441. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10442. // Attacker-controlled name carrying CR/LF.
  10443. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10444. res.set_content("body", "text/plain");
  10445. });
  10446. thread t = thread([&] { svr.listen(HOST, PORT); });
  10447. auto se = detail::scope_exit([&] {
  10448. svr.stop();
  10449. t.join();
  10450. ASSERT_FALSE(svr.is_running());
  10451. });
  10452. svr.wait_until_ready();
  10453. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10454. "Host: " + HOST +
  10455. "\r\n"
  10456. "Connection: close\r\n"
  10457. "\r\n";
  10458. std::string res;
  10459. ASSERT_TRUE(send_request(5, req, &res));
  10460. // The injected fields must not appear anywhere in the raw response.
  10461. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10462. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10463. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10464. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10465. // Invalid headers are dropped entirely, matching set_header().
  10466. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10467. // The valid header still passes through.
  10468. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10469. }
  10470. }
  10471. // Forward declaration: in split builds split.py strips `inline` and moves the
  10472. // definition into httplib.cc, so detail::write_request_line is not visible from
  10473. // the public httplib.h. Re-declaring it here lets the tests link against the
  10474. // symbol in both header-only and split builds.
  10475. namespace httplib {
  10476. namespace detail {
  10477. ssize_t write_request_line(Stream &strm, const std::string &method,
  10478. const std::string &path);
  10479. } // namespace detail
  10480. } // namespace httplib
  10481. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10482. // A well-formed target is written verbatim.
  10483. {
  10484. detail::BufferStream strm;
  10485. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10486. EXPECT_GT(n, 0);
  10487. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10488. }
  10489. // A target carrying CR/LF, SP or other control octets must be rejected
  10490. // before anything reaches the wire, otherwise it splits the request line and
  10491. // injects a header or a whole request.
  10492. const std::string evil_targets[] = {
  10493. "/a\r\nInjected: pwned",
  10494. "/a\rInjected",
  10495. "/a\nInjected",
  10496. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10497. "/a b",
  10498. "/a\tb",
  10499. "/a\x7f",
  10500. };
  10501. for (const auto &evil : evil_targets) {
  10502. detail::BufferStream strm;
  10503. auto n = detail::write_request_line(strm, "GET", evil);
  10504. EXPECT_LT(n, 0);
  10505. EXPECT_TRUE(strm.get_buffer().empty());
  10506. }
  10507. }
  10508. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10509. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10510. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10511. // target reaches write_request. The client must fail cleanly with
  10512. // Error::Write instead of putting a request-line-less, header-injecting
  10513. // request on the wire.
  10514. Server svr;
  10515. svr.Get("/a", [](const Request &, Response &res) {
  10516. res.set_content("ok", "text/plain");
  10517. });
  10518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10519. auto se = detail::scope_exit([&] {
  10520. svr.stop();
  10521. thread.join();
  10522. ASSERT_FALSE(svr.is_running());
  10523. });
  10524. svr.wait_until_ready();
  10525. {
  10526. Client cli(HOST, PORT);
  10527. cli.set_path_encode(false);
  10528. // The request is rejected before anything is written, so the connection
  10529. // stays silent and the subsequent response read would otherwise block for
  10530. // the full default read timeout. Shorten it -- the assertion is on the
  10531. // error, not the timeout.
  10532. cli.set_read_timeout(1, 0);
  10533. auto res = cli.Get("/a\r\nInjected: pwned");
  10534. EXPECT_FALSE(res);
  10535. EXPECT_EQ(Error::Write, res.error());
  10536. }
  10537. }
  10538. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10539. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10540. // including extension methods.
  10541. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10542. for (const auto &method : good_methods) {
  10543. detail::BufferStream strm;
  10544. auto n = detail::write_request_line(strm, method, "/");
  10545. EXPECT_GT(n, 0);
  10546. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10547. }
  10548. // A method carrying CR/LF would split the request line and smuggle a whole
  10549. // request ahead of the real one. A space or an empty method corrupts the
  10550. // request line. All must be rejected before anything reaches the wire.
  10551. const std::string evil_methods[] = {
  10552. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10553. "GET\r\nInjected: pwned",
  10554. "GET\r",
  10555. "GET\n",
  10556. "GE T",
  10557. "",
  10558. };
  10559. for (const auto &evil : evil_methods) {
  10560. detail::BufferStream strm;
  10561. auto n = detail::write_request_line(strm, evil, "/");
  10562. EXPECT_LT(n, 0);
  10563. EXPECT_TRUE(strm.get_buffer().empty());
  10564. }
  10565. }
  10566. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10567. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10568. // through Client::send must fail with Error::Write and no request, neither
  10569. // the smuggled one nor the real one, may reach the server.
  10570. Server svr;
  10571. std::atomic<int> request_count(0);
  10572. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10573. request_count++;
  10574. res.status = StatusCode::OK_200;
  10575. return Server::HandlerResponse::Handled;
  10576. });
  10577. auto port = svr.bind_to_any_port(HOST);
  10578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10579. auto se = detail::scope_exit([&] {
  10580. svr.stop();
  10581. thread.join();
  10582. ASSERT_FALSE(svr.is_running());
  10583. });
  10584. svr.wait_until_ready();
  10585. {
  10586. Client cli(HOST, port);
  10587. const std::string evil_methods[] = {
  10588. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10589. "GE T",
  10590. "",
  10591. };
  10592. for (const auto &evil : evil_methods) {
  10593. Request req;
  10594. req.method = evil;
  10595. req.path = "/";
  10596. auto res = cli.send(req);
  10597. EXPECT_FALSE(res);
  10598. EXPECT_EQ(Error::Write, res.error());
  10599. }
  10600. auto handle =
  10601. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10602. EXPECT_FALSE(handle.is_valid());
  10603. EXPECT_EQ(Error::Write, handle.error);
  10604. // A valid request on the same client still goes through.
  10605. auto res = cli.Get("/");
  10606. ASSERT_TRUE(res);
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. }
  10609. EXPECT_EQ(1, request_count.load());
  10610. }
  10611. // Sends a raw request and verifies that there isn't a crash or exception.
  10612. static void test_raw_request(const std::string &req,
  10613. std::string *out = nullptr) {
  10614. Server svr;
  10615. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10616. res.set_content("ok", "text/plain");
  10617. });
  10618. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10619. res.set_content("ok", "text/plain");
  10620. });
  10621. svr.Get("/header_field_value_check",
  10622. [&](const Request & /*req*/, Response &res) {
  10623. res.set_content("ok", "text/plain");
  10624. });
  10625. svr.CustomRoute("PROPFIND", "/dav",
  10626. [&](const Request & /*req*/, Response &res) {
  10627. res.status = StatusCode::MultiStatus_207;
  10628. });
  10629. // Server read timeout must be longer than the client read timeout for the
  10630. // bug to reproduce, probably to force the server to process a request
  10631. // without a trailing blank line.
  10632. const time_t client_read_timeout_sec = 1;
  10633. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10634. bool listen_thread_ok = false;
  10635. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10636. auto se = detail::scope_exit([&] {
  10637. svr.stop();
  10638. t.join();
  10639. ASSERT_FALSE(svr.is_running());
  10640. EXPECT_TRUE(listen_thread_ok);
  10641. });
  10642. svr.wait_until_ready();
  10643. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10644. }
  10645. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10646. // A certain header line causes an exception if the header property is parsed
  10647. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10648. test_raw_request(
  10649. "GET /hi HTTP/1.1\r\n"
  10650. " : "
  10651. " "
  10652. " ");
  10653. }
  10654. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10655. // A certain header line causes an exception if the header property *name* is
  10656. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10657. // greedy matcher and requires backtracking when there are a lot of ":"
  10658. // characters.
  10659. // This occurs with libc++ but not libstdc++.
  10660. test_raw_request(
  10661. "GET /hi HTTP/1.1\r\n"
  10662. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10663. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10664. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10665. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10666. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10667. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10668. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10669. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10670. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10671. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10672. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10673. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10674. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10675. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10676. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10677. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10678. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10679. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10680. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10681. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10682. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10683. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10684. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10685. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10686. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10687. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10688. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10689. "&&&%%%");
  10690. }
  10691. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10692. // Make sure this doesn't crash the server.
  10693. // In a previous version of the header line regex, the "\r" rendered the line
  10694. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10695. // a new position where the leading white space ended and the field value
  10696. // began.
  10697. // The crash occurs with libc++ but not libstdc++.
  10698. test_raw_request("GET /hi HTTP/1.1\r\n"
  10699. "a:" +
  10700. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10701. "\r\n"
  10702. "\r\n");
  10703. }
  10704. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10705. const char *rejected[] = {
  10706. // RFC 9112 §3: one SP between the parts, and nothing else
  10707. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10708. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10709. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10710. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10711. // A request-target has no fragment
  10712. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10713. // An HTTP/1.1 request needs a Host
  10714. "GET /hi HTTP/1.1\r\n\r\n",
  10715. };
  10716. for (auto request : rejected) {
  10717. std::string out;
  10718. test_raw_request(request, &out);
  10719. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10720. }
  10721. std::string out;
  10722. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10723. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10724. }
  10725. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10726. // RFC 9112 §6.1
  10727. const char *requests[] = {
  10728. "PUT /put_hi HTTP/1.1\r\n"
  10729. "Host: localhost\r\n"
  10730. "Content-Length: 0\r\n"
  10731. "Transfer-Encoding: chunked\r\n"
  10732. "\r\n"
  10733. "0\r\n\r\n",
  10734. "PUT /put_hi HTTP/1.0\r\n"
  10735. "Connection: keep-alive\r\n"
  10736. "Transfer-Encoding: chunked\r\n"
  10737. "\r\n"
  10738. "0\r\n\r\n",
  10739. };
  10740. for (auto request : requests) {
  10741. std::string out;
  10742. test_raw_request(request, &out);
  10743. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10744. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10745. }
  10746. }
  10747. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10748. std::string out;
  10749. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10750. "Content-Type: text/plain\r\n"
  10751. "Transfer-Encoding: chunked\r\n"
  10752. "\r\n"
  10753. "nothex\r\n",
  10754. &out);
  10755. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10756. }
  10757. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10758. std::string out;
  10759. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10760. "Content-Type: text/plain\r\n"
  10761. "Transfer-Encoding: chunked\r\n"
  10762. "\r\n"
  10763. "3\r\n"
  10764. "xyz\r\n"
  10765. "NaN\r\n",
  10766. &out);
  10767. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10768. }
  10769. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10770. std::string out;
  10771. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10772. "Content-Type: text/plain\r\n"
  10773. "Transfer-Encoding: chunked\r\n"
  10774. "\r\n"
  10775. // Length is too large for 64 bits.
  10776. "1ffffffffffffffff\r\n"
  10777. "xyz\r\n",
  10778. &out);
  10779. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10780. }
  10781. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10782. test_raw_request("GET /hi HTTP/1.1\r\n"
  10783. "Content-Type: text/plain\r\n\r");
  10784. }
  10785. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10786. std::string out;
  10787. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10788. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10789. }
  10790. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10791. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10792. std::string out;
  10793. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10794. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10795. }
  10796. }
  10797. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10798. std::string out;
  10799. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10800. "Host: localhost\r\n"
  10801. "Connection: close\r\n\r\n",
  10802. &out);
  10803. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10804. }
  10805. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10806. Server svr;
  10807. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10808. EXPECT_TRUE(!req.remote_addr.empty());
  10809. });
  10810. thread t = thread([&] { svr.listen(HOST, PORT); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. t.join();
  10814. ASSERT_FALSE(svr.is_running());
  10815. });
  10816. svr.wait_until_ready();
  10817. // Send an invalid request line to trigger Bad Request
  10818. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10819. std::string out;
  10820. ASSERT_TRUE(send_request(5, bad_req, &out));
  10821. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10822. }
  10823. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10824. // answered right away rather than blocking on a read that waits for EOF.
  10825. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10826. std::string out;
  10827. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10828. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10829. }
  10830. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10831. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10832. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10833. for (const auto *method : methods) {
  10834. Server svr;
  10835. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10836. EXPECT_FALSE(svr.is_valid()) << method;
  10837. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10838. }
  10839. }
  10840. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10841. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10842. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10843. for (const auto *method : methods) {
  10844. Server svr;
  10845. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10846. EXPECT_FALSE(svr.is_valid()) << method;
  10847. }
  10848. }
  10849. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10850. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10851. "COPY", "MOVE", "LOCK",
  10852. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10853. Server svr;
  10854. for (const auto *method : methods) {
  10855. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10856. }
  10857. EXPECT_TRUE(svr.is_valid());
  10858. }
  10859. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10860. Server svr;
  10861. svr.CustomRoute("POST", "/x",
  10862. [](const Request &, Response &, const ContentReader &) {});
  10863. EXPECT_FALSE(svr.is_valid());
  10864. }
  10865. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10866. Server svr;
  10867. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10868. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10869. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10870. EXPECT_FALSE(svr.is_valid());
  10871. }
  10872. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10873. Server svr;
  10874. auto captured = Error::Success;
  10875. svr.set_error_logger(
  10876. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10877. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10878. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10879. }
  10880. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10881. std::string out;
  10882. std::string request(
  10883. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10884. test_raw_request(request, &out);
  10885. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10886. }
  10887. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10888. std::string out;
  10889. std::string request(
  10890. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10891. test_raw_request(request, &out);
  10892. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10893. }
  10894. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10895. std::string out;
  10896. std::string request(
  10897. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10898. test_raw_request(request, &out);
  10899. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10900. }
  10901. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10902. std::string out;
  10903. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10904. "Host: localhost\r\n"
  10905. "Test: \r\n\r\n",
  10906. &out);
  10907. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10908. }
  10909. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10910. Server svr;
  10911. std::string x_custom;
  10912. std::string cookie;
  10913. std::string xff;
  10914. std::string x_unicode;
  10915. std::string x_iis;
  10916. svr.Get("/check", [&](const Request &req, Response &res) {
  10917. x_custom = req.get_header_value("X-Custom");
  10918. cookie = req.get_header_value("Cookie");
  10919. xff = req.get_header_value("X-Forwarded-For");
  10920. x_unicode = req.get_header_value("X-Unicode");
  10921. x_iis = req.get_header_value("X-IIS");
  10922. res.set_content("ok", "text/plain");
  10923. });
  10924. thread t = thread([&] { svr.listen(HOST, PORT); });
  10925. auto se = detail::scope_exit([&] {
  10926. svr.stop();
  10927. t.join();
  10928. ASSERT_FALSE(svr.is_running());
  10929. });
  10930. svr.wait_until_ready();
  10931. const std::string req = "GET /check HTTP/1.1\r\n"
  10932. "Host: localhost\r\n"
  10933. "X-Custom: a%0D%0AInjected: b\r\n"
  10934. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10935. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10936. "X-Unicode: %E3%81%82\r\n"
  10937. "X-IIS: %u00E9\r\n"
  10938. "Connection: close\r\n"
  10939. "\r\n";
  10940. std::string res;
  10941. ASSERT_TRUE(send_request(5, req, &res));
  10942. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10943. // Every value must be returned verbatim (wire form), with no decoding.
  10944. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10945. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10946. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10947. EXPECT_EQ("%E3%81%82", x_unicode);
  10948. EXPECT_EQ("%u00E9", x_iis);
  10949. }
  10950. // Applications that previously relied on automatic percent-decoding can
  10951. // reproduce the old behavior by explicitly calling decode_path_component()
  10952. // or, for RFC 3986 conformance, decode_uri_component().
  10953. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10954. Server svr;
  10955. std::string decoded;
  10956. svr.Get("/check", [&](const Request &req, Response &res) {
  10957. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10958. res.set_content("ok", "text/plain");
  10959. });
  10960. thread t = thread([&] { svr.listen(HOST, PORT); });
  10961. auto se = detail::scope_exit([&] {
  10962. svr.stop();
  10963. t.join();
  10964. ASSERT_FALSE(svr.is_running());
  10965. });
  10966. svr.wait_until_ready();
  10967. const std::string req = "GET /check HTTP/1.1\r\n"
  10968. "Host: localhost\r\n"
  10969. "X-Custom: hello%20world\r\n"
  10970. "Connection: close\r\n"
  10971. "\r\n";
  10972. std::string res;
  10973. ASSERT_TRUE(send_request(5, req, &res));
  10974. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10975. EXPECT_EQ("hello world", decoded);
  10976. }
  10977. // Regression test for #2033. Browsers send Referer values that include
  10978. // percent-encoded characters such as %0A inside the URL. Decoding the
  10979. // header value would either trip the post-decode CR/LF/NUL guard (the
  10980. // original bug, returning 400) or, after that guard was relaxed, silently
  10981. // store a literal LF — both unacceptable. The wire form must round-trip.
  10982. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10983. Server svr;
  10984. std::string referer;
  10985. svr.Get("/check", [&](const Request &req, Response &res) {
  10986. referer = req.get_header_value("Referer");
  10987. res.set_content("ok", "text/plain");
  10988. });
  10989. thread t = thread([&] { svr.listen(HOST, PORT); });
  10990. auto se = detail::scope_exit([&] {
  10991. svr.stop();
  10992. t.join();
  10993. ASSERT_FALSE(svr.is_running());
  10994. });
  10995. svr.wait_until_ready();
  10996. const std::string req = "GET /check HTTP/1.1\r\n"
  10997. "Host: localhost\r\n"
  10998. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10999. "Connection: close\r\n"
  11000. "\r\n";
  11001. std::string res;
  11002. ASSERT_TRUE(send_request(5, req, &res));
  11003. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  11004. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  11005. }
  11006. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  11007. Server svr;
  11008. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  11009. res.set_header("Cache-Control", "no-cache");
  11010. res.set_chunked_content_provider(
  11011. "text/event-stream", [](size_t offset, DataSink &sink) {
  11012. std::string s = "data:";
  11013. s += std::to_string(offset);
  11014. s += "\n\n";
  11015. auto ret = sink.write(s.data(), s.size());
  11016. EXPECT_TRUE(ret);
  11017. std::this_thread::sleep_for(std::chrono::seconds(1));
  11018. return true;
  11019. });
  11020. });
  11021. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11022. svr.wait_until_ready();
  11023. Client client(HOST, PORT);
  11024. const Headers headers = {{"Accept", "text/event-stream"}};
  11025. auto get_thread = std::thread([&client, &headers]() {
  11026. auto res = client.Get(
  11027. "/events", headers,
  11028. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  11029. });
  11030. auto se = detail::scope_exit([&] {
  11031. svr.stop();
  11032. get_thread.join();
  11033. listen_thread.join();
  11034. ASSERT_FALSE(svr.is_running());
  11035. });
  11036. // Give GET time to get a few messages.
  11037. std::this_thread::sleep_for(std::chrono::seconds(2));
  11038. }
  11039. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  11040. httplib::Server svr;
  11041. svr.Post("/hi",
  11042. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11043. res.status = StatusCode::OK_200;
  11044. });
  11045. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11046. svr.wait_until_ready();
  11047. Client cli(HOST, PORT);
  11048. auto res = cli.Post("/hi", "data", "text/plain");
  11049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11050. EXPECT_EQ(StatusCode::OK_200, res->status);
  11051. svr.stop();
  11052. thread.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. res = cli.Post("/hi", "data", "text/plain");
  11055. ASSERT_FALSE(res);
  11056. }
  11057. TEST(ServerStopTest, ListenFailure) {
  11058. Server svr;
  11059. auto t = thread([&]() {
  11060. auto ret = svr.listen("????", PORT);
  11061. EXPECT_FALSE(ret);
  11062. });
  11063. svr.wait_until_ready();
  11064. svr.stop();
  11065. t.join();
  11066. }
  11067. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11068. TEST(ServerStopTest, Decommision) {
  11069. Server svr;
  11070. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  11071. for (int i = 0; i < 4; i++) {
  11072. auto is_even = !(i % 2);
  11073. std::thread t{[&] {
  11074. try {
  11075. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11076. if (is_even) {
  11077. throw std::runtime_error("Some thing that happens to go wrong.");
  11078. }
  11079. svr.listen(HOST, PORT);
  11080. } catch (...) { svr.decommission(); }
  11081. }};
  11082. svr.wait_until_ready();
  11083. // Server is up
  11084. {
  11085. Client cli(HOST, PORT);
  11086. auto res = cli.Get("/hi");
  11087. if (is_even) {
  11088. EXPECT_FALSE(res);
  11089. } else {
  11090. EXPECT_TRUE(res);
  11091. EXPECT_EQ("hi...", res->body);
  11092. }
  11093. }
  11094. svr.stop();
  11095. t.join();
  11096. // Server is down...
  11097. {
  11098. Client cli(HOST, PORT);
  11099. auto res = cli.Get("/hi");
  11100. EXPECT_FALSE(res);
  11101. }
  11102. }
  11103. }
  11104. #endif
  11105. // Helper function for string body upload progress tests
  11106. template <typename SetupHandler, typename ClientCall>
  11107. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  11108. ClientCall &&client_call,
  11109. const string &body) {
  11110. Server svr;
  11111. setup_handler(svr);
  11112. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11113. auto se = detail::scope_exit([&] {
  11114. svr.stop();
  11115. t.join();
  11116. });
  11117. svr.wait_until_ready();
  11118. Client cli(HOST, PORT);
  11119. vector<uint64_t> progress_values;
  11120. bool progress_called = false;
  11121. auto res =
  11122. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11123. progress_values.push_back(current);
  11124. progress_called = true;
  11125. return true;
  11126. });
  11127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11128. EXPECT_EQ(200, res->status);
  11129. EXPECT_TRUE(progress_called);
  11130. }
  11131. TEST(UploadProgressTest, PostStringBodyBasic) {
  11132. TestStringBodyUploadProgress(
  11133. [](Server &svr) {
  11134. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11135. res.set_content("received", "text/plain");
  11136. });
  11137. },
  11138. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11139. return cli.Post("/test", body, "text/plain", progress_callback);
  11140. },
  11141. "test data for upload progress");
  11142. }
  11143. TEST(UploadProgressTest, PutStringBodyBasic) {
  11144. TestStringBodyUploadProgress(
  11145. [](Server &svr) {
  11146. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  11147. res.set_content("put received", "text/plain");
  11148. });
  11149. },
  11150. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11151. return cli.Put("/test", body, "text/plain", progress_callback);
  11152. },
  11153. "put test data for upload progress");
  11154. }
  11155. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11156. TestStringBodyUploadProgress(
  11157. [](Server &svr) {
  11158. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11159. res.set_content("patch received", "text/plain");
  11160. });
  11161. },
  11162. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11163. return cli.Patch("/test", body, "text/plain", progress_callback);
  11164. },
  11165. "patch test data for upload progress");
  11166. }
  11167. // Helper function for content provider upload progress tests
  11168. template <typename SetupHandler, typename ClientCall>
  11169. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11170. ClientCall &&client_call) {
  11171. Server svr;
  11172. setup_handler(svr);
  11173. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11174. auto se = detail::scope_exit([&] {
  11175. svr.stop();
  11176. t.join();
  11177. });
  11178. svr.wait_until_ready();
  11179. Client cli(HOST, PORT);
  11180. vector<uint64_t> progress_values;
  11181. auto res =
  11182. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11183. progress_values.push_back(current);
  11184. return true;
  11185. });
  11186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11187. EXPECT_EQ(200, res->status);
  11188. EXPECT_FALSE(progress_values.empty());
  11189. }
  11190. TEST(UploadProgressTest, PostContentProviderProgress) {
  11191. TestContentProviderUploadProgress(
  11192. [](Server &svr) {
  11193. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11194. res.set_content("provider received", "text/plain");
  11195. });
  11196. },
  11197. [](Client &cli, UploadProgress progress_callback) {
  11198. return cli.Post(
  11199. "/test", 9,
  11200. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11201. sink.os << "test data";
  11202. return true;
  11203. },
  11204. "text/plain", progress_callback);
  11205. });
  11206. }
  11207. // Helper function for multipart upload progress tests
  11208. template <typename SetupHandler, typename ClientCall>
  11209. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11210. ClientCall &&client_call,
  11211. const string &endpoint) {
  11212. Server svr;
  11213. setup_handler(svr);
  11214. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11215. auto se = detail::scope_exit([&] {
  11216. svr.stop();
  11217. t.join();
  11218. });
  11219. svr.wait_until_ready();
  11220. Client cli(HOST, PORT);
  11221. vector<uint64_t> progress_values;
  11222. UploadFormDataItems items = {
  11223. {"field1", "value1", "", ""},
  11224. {"field2", "longer value for progress tracking test", "", ""},
  11225. {"file1", "file content data for upload progress", "test.txt",
  11226. "text/plain"}};
  11227. auto res = client_call(cli, endpoint, items,
  11228. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11229. progress_values.push_back(current);
  11230. return true;
  11231. });
  11232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11233. EXPECT_EQ(200, res->status);
  11234. EXPECT_FALSE(progress_values.empty());
  11235. }
  11236. TEST(UploadProgressTest, PostMultipartProgress) {
  11237. TestMultipartUploadProgress(
  11238. [](Server &svr) {
  11239. svr.Post("/multipart", [](const Request &req, Response &res) {
  11240. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11241. res.set_content("multipart received", "text/plain");
  11242. });
  11243. },
  11244. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11245. UploadProgress progress_callback) {
  11246. return cli.Post(endpoint, items, progress_callback);
  11247. },
  11248. "/multipart");
  11249. }
  11250. // Helper function for basic download progress tests
  11251. template <typename SetupHandler, typename ClientCall>
  11252. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11253. ClientCall &&client_call, const string &endpoint,
  11254. size_t expected_content_size) {
  11255. Server svr;
  11256. setup_handler(svr);
  11257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11258. auto se = detail::scope_exit([&] {
  11259. svr.stop();
  11260. t.join();
  11261. });
  11262. svr.wait_until_ready();
  11263. Client cli(HOST, PORT);
  11264. vector<uint64_t> progress_values;
  11265. auto res = client_call(cli, endpoint,
  11266. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11267. progress_values.push_back(current);
  11268. return true;
  11269. });
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. EXPECT_EQ(200, res->status);
  11272. EXPECT_FALSE(progress_values.empty());
  11273. EXPECT_EQ(expected_content_size, res->body.size());
  11274. }
  11275. TEST(DownloadProgressTest, GetBasic) {
  11276. TestBasicDownloadProgress(
  11277. [](Server &svr) {
  11278. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11279. string content(1000, 'D');
  11280. res.set_content(content, "text/plain");
  11281. });
  11282. },
  11283. [](Client &cli, const string &endpoint,
  11284. DownloadProgress progress_callback) {
  11285. return cli.Get(endpoint, progress_callback);
  11286. },
  11287. "/download", 1000u);
  11288. }
  11289. // Helper function for content receiver download progress tests
  11290. template <typename SetupHandler, typename ClientCall>
  11291. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11292. ClientCall &&client_call,
  11293. const string &endpoint,
  11294. size_t expected_content_size) {
  11295. Server svr;
  11296. setup_handler(svr);
  11297. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. t.join();
  11301. });
  11302. svr.wait_until_ready();
  11303. Client cli(HOST, PORT);
  11304. vector<uint64_t> progress_values;
  11305. string received_body;
  11306. auto res = client_call(
  11307. cli, endpoint,
  11308. [&](const char *data, size_t data_length) -> bool {
  11309. received_body.append(data, data_length);
  11310. return true;
  11311. },
  11312. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11313. progress_values.push_back(current);
  11314. return true;
  11315. });
  11316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11317. EXPECT_EQ(200, res->status);
  11318. EXPECT_FALSE(progress_values.empty());
  11319. EXPECT_EQ(expected_content_size, received_body.size());
  11320. EXPECT_TRUE(res->body.empty());
  11321. }
  11322. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11323. TestContentReceiverDownloadProgress(
  11324. [](Server &svr) {
  11325. svr.Get("/download-receiver",
  11326. [](const Request & /*req*/, Response &res) {
  11327. string content(2000, 'R');
  11328. res.set_content(content, "text/plain");
  11329. });
  11330. },
  11331. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11332. DownloadProgress progress_callback) {
  11333. return cli.Get(endpoint, content_receiver, progress_callback);
  11334. },
  11335. "/download-receiver", 2000u);
  11336. }
  11337. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11338. // A provider reaching a pass with nothing to hand over - an empty buffer
  11339. // popped off a queue, say - must not be taken to mean the body is finished.
  11340. // It used to end the loop with the terminating chunk unwritten while the
  11341. // server still considered the response complete, so the peer waited for an
  11342. // end that never arrived.
  11343. Server svr;
  11344. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11345. auto step = std::make_shared<int>(0);
  11346. res.set_chunked_content_provider("text/plain",
  11347. [step](size_t /*offset*/, DataSink &sink) {
  11348. switch ((*step)++) {
  11349. case 0: sink.write("", 0); break;
  11350. case 1: sink.write("hello", 5); break;
  11351. default: sink.done(); break;
  11352. }
  11353. return true;
  11354. });
  11355. });
  11356. auto port = svr.bind_to_any_port(HOST);
  11357. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11358. auto listen_se = detail::scope_exit([&] {
  11359. svr.stop();
  11360. listen_thread.join();
  11361. ASSERT_FALSE(svr.is_running());
  11362. });
  11363. svr.wait_until_ready();
  11364. Client cli(HOST, port);
  11365. // Without the fix the body is never terminated, so bound the wait rather
  11366. // than letting the test hang on the default read timeout.
  11367. cli.set_read_timeout(5, 0);
  11368. auto res = cli.Get("/stream");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::OK_200, res->status);
  11371. EXPECT_EQ("hello", res->body);
  11372. }
  11373. TEST(StreamingTest, NoContentLengthStreaming) {
  11374. Server svr;
  11375. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11376. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11377. if (offset < 6) {
  11378. sink.os << (offset < 3 ? "a" : "b");
  11379. } else {
  11380. sink.done();
  11381. }
  11382. return true;
  11383. });
  11384. });
  11385. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11386. auto listen_se = detail::scope_exit([&] {
  11387. svr.stop();
  11388. listen_thread.join();
  11389. ASSERT_FALSE(svr.is_running());
  11390. });
  11391. svr.wait_until_ready();
  11392. Client client(HOST, PORT);
  11393. auto get_thread = std::thread([&client]() {
  11394. std::string s;
  11395. auto res =
  11396. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11397. s += std::string(data, len);
  11398. return true;
  11399. });
  11400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11401. EXPECT_EQ(StatusCode::OK_200, res->status);
  11402. EXPECT_EQ("aaabbb", s);
  11403. });
  11404. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11405. // Give GET time to get a few messages.
  11406. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11407. }
  11408. TEST(MountTest, Unmount) {
  11409. Server svr;
  11410. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11411. auto se = detail::scope_exit([&] {
  11412. svr.stop();
  11413. listen_thread.join();
  11414. ASSERT_FALSE(svr.is_running());
  11415. });
  11416. svr.wait_until_ready();
  11417. Client cli("localhost", PORT);
  11418. svr.set_mount_point("/mount2", "./www2");
  11419. auto res = cli.Get("/");
  11420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11422. res = cli.Get("/mount2/dir/test.html");
  11423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11424. EXPECT_EQ(StatusCode::OK_200, res->status);
  11425. svr.set_mount_point("/", "./www");
  11426. res = cli.Get("/dir/");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status);
  11429. svr.remove_mount_point("/");
  11430. res = cli.Get("/dir/");
  11431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11432. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11433. svr.remove_mount_point("/mount2");
  11434. res = cli.Get("/mount2/dir/test.html");
  11435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11436. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11437. }
  11438. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11439. Server svr;
  11440. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11441. svr.Get("/api/hello", [](const Request &, Response &res) {
  11442. res.set_content("api", "text/plain");
  11443. });
  11444. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11445. auto se = detail::scope_exit([&] {
  11446. svr.stop();
  11447. listen_thread.join();
  11448. ASSERT_FALSE(svr.is_running());
  11449. });
  11450. svr.wait_until_ready();
  11451. Client cli(HOST, PORT);
  11452. auto res = cli.Get("/dir/test.html");
  11453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11454. EXPECT_EQ(StatusCode::OK_200, res->status);
  11455. res = cli.Get("/api/hello");
  11456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11457. EXPECT_EQ(StatusCode::OK_200, res->status);
  11458. EXPECT_EQ("api", res->body);
  11459. }
  11460. TEST(MountTest, PathSegmentBoundary) {
  11461. Server svr;
  11462. svr.set_mount_point("/mount2", "./www2");
  11463. svr.set_mount_point("/", "./www");
  11464. auto port = svr.bind_to_any_port(HOST);
  11465. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11466. auto se = detail::scope_exit([&] {
  11467. svr.stop();
  11468. listen_thread.join();
  11469. ASSERT_FALSE(svr.is_running());
  11470. });
  11471. svr.wait_until_ready();
  11472. Client cli(HOST, port);
  11473. auto res = cli.Get("/mount2/dir/test.html");
  11474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11475. EXPECT_EQ(StatusCode::OK_200, res->status);
  11476. // "/mount2" must not match part-way through a path segment.
  11477. res = cli.Get("/mount2dir/test.html");
  11478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11480. // A mount point ending in '/' keeps matching every path below it.
  11481. res = cli.Get("/dir/test.html");
  11482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11483. EXPECT_EQ(StatusCode::OK_200, res->status);
  11484. }
  11485. TEST(MountTest, Redicect) {
  11486. Server svr;
  11487. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11488. auto se = detail::scope_exit([&] {
  11489. svr.stop();
  11490. listen_thread.join();
  11491. ASSERT_FALSE(svr.is_running());
  11492. });
  11493. svr.set_mount_point("/", "./www");
  11494. svr.wait_until_ready();
  11495. Client cli("localhost", PORT);
  11496. auto res = cli.Get("/dir/");
  11497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11498. EXPECT_EQ(StatusCode::OK_200, res->status);
  11499. res = cli.Get("/dir");
  11500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11501. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11502. res = cli.Get("/file");
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. EXPECT_EQ(StatusCode::OK_200, res->status);
  11505. res = cli.Get("/file/");
  11506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11508. cli.set_follow_location(true);
  11509. res = cli.Get("/dir");
  11510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11511. EXPECT_EQ(StatusCode::OK_200, res->status);
  11512. }
  11513. TEST(MountTest, MultibytesPathName) {
  11514. Server svr;
  11515. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11516. auto se = detail::scope_exit([&] {
  11517. svr.stop();
  11518. listen_thread.join();
  11519. ASSERT_FALSE(svr.is_running());
  11520. });
  11521. svr.set_mount_point("/", "./www");
  11522. svr.wait_until_ready();
  11523. Client cli("localhost", PORT);
  11524. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11526. EXPECT_EQ(StatusCode::OK_200, res->status);
  11527. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11528. }
  11529. // A mount point serves no path with an empty segment or one ending in '.' or
  11530. // a space, so a guard in the pre-routing handler sees the path of every file
  11531. // that is served
  11532. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11533. Server svr;
  11534. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11535. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11536. if (req.path == "/dir/test.html") {
  11537. res.status = StatusCode::Unauthorized_401;
  11538. return Server::HandlerResponse::Handled;
  11539. }
  11540. return Server::HandlerResponse::Unhandled;
  11541. });
  11542. auto port = svr.bind_to_any_port(HOST);
  11543. ASSERT_LT(0, port);
  11544. thread t = thread([&] { svr.listen_after_bind(); });
  11545. auto se = detail::scope_exit([&] {
  11546. svr.stop();
  11547. t.join();
  11548. ASSERT_FALSE(svr.is_running());
  11549. });
  11550. svr.wait_until_ready();
  11551. Client cli(HOST, port);
  11552. for (auto path :
  11553. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11554. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11555. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11556. "/dir/test.html%3A%3A$DATA"}) {
  11557. SCOPED_TRACE(path);
  11558. auto res = cli.Get(path);
  11559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11561. }
  11562. }
  11563. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11564. Server svr;
  11565. svr.set_mount_point("/", "./www");
  11566. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11567. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11568. auto port = svr.bind_to_any_port(HOST);
  11569. ASSERT_GT(port, 0);
  11570. thread t = thread([&] { svr.listen_after_bind(); });
  11571. auto se = detail::scope_exit([&] {
  11572. svr.stop();
  11573. t.join();
  11574. ASSERT_FALSE(svr.is_running());
  11575. });
  11576. svr.wait_until_ready();
  11577. Client cli(HOST, port);
  11578. auto res = cli.Get("/dir/test.abcde");
  11579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11580. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11581. res = cli.Get("/dir/test.html");
  11582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11583. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11584. }
  11585. #ifdef _WIN32
  11586. // Issue #2435: mmap::open() must succeed even when another handle holds
  11587. // the file open for writing (e.g. an active log file).
  11588. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11589. const char *path = "mmap_concurrent_writer_test.txt";
  11590. const char *content = "hello";
  11591. {
  11592. std::ofstream f(path, std::ios::binary);
  11593. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11594. }
  11595. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11596. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11597. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11598. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11599. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11600. detail::mmap m(path);
  11601. ASSERT_TRUE(m.is_open());
  11602. EXPECT_EQ(strlen(content), m.size());
  11603. char buf[8];
  11604. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11605. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11606. }
  11607. #endif
  11608. #ifndef _WIN32
  11609. // A directory or a device has no size to serve.
  11610. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11611. const char *path = "./mmap_not_regular_test_dir";
  11612. ASSERT_EQ(0, ::mkdir(path, 0755));
  11613. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11614. for (auto p : {path, "/dev/null"}) {
  11615. detail::mmap m(p);
  11616. EXPECT_FALSE(m.is_open()) << p;
  11617. EXPECT_EQ(0U, m.size()) << p;
  11618. }
  11619. Server svr;
  11620. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11621. res.set_file_content("/dev/null");
  11622. });
  11623. auto port = svr.bind_to_any_port(HOST);
  11624. thread t = thread([&] { svr.listen_after_bind(); });
  11625. auto se = detail::scope_exit([&] {
  11626. svr.stop();
  11627. t.join();
  11628. });
  11629. svr.wait_until_ready();
  11630. auto res = Client(HOST, port).Get("/null");
  11631. ASSERT_TRUE(res);
  11632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11633. }
  11634. #endif
  11635. #ifdef __linux__
  11636. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11637. TEST(MmapTest, FileIsNotMapped) {
  11638. const char *path = "mmap_not_mapped_test.txt";
  11639. {
  11640. std::ofstream f(path, std::ios::binary);
  11641. f << "hello";
  11642. }
  11643. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11644. detail::mmap m(path);
  11645. ASSERT_TRUE(m.is_open());
  11646. std::ifstream maps("/proc/self/maps");
  11647. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11648. std::istreambuf_iterator<char>());
  11649. EXPECT_EQ(std::string::npos, mappings.find(path));
  11650. }
  11651. #endif
  11652. TEST(KeepAliveTest, ReadTimeout) {
  11653. Server svr;
  11654. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11655. std::this_thread::sleep_for(std::chrono::seconds(2));
  11656. res.set_content("a", "text/plain");
  11657. });
  11658. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11659. res.set_content("b", "text/plain");
  11660. });
  11661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11662. auto se = detail::scope_exit([&] {
  11663. svr.stop();
  11664. listen_thread.join();
  11665. ASSERT_FALSE(svr.is_running());
  11666. });
  11667. svr.wait_until_ready();
  11668. Client cli("localhost", PORT);
  11669. cli.set_keep_alive(true);
  11670. cli.set_read_timeout(std::chrono::seconds(1));
  11671. auto resa = cli.Get("/a");
  11672. ASSERT_FALSE(resa);
  11673. EXPECT_EQ(Error::Read, resa.error());
  11674. auto resb = cli.Get("/b");
  11675. ASSERT_TRUE(resb);
  11676. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11677. EXPECT_EQ("b", resb->body);
  11678. }
  11679. TEST(KeepAliveTest, MaxCount) {
  11680. size_t keep_alive_max_count = 3;
  11681. Server svr;
  11682. svr.set_keep_alive_max_count(keep_alive_max_count);
  11683. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11684. res.set_content("Hello World!", "text/plain");
  11685. });
  11686. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11687. auto se = detail::scope_exit([&] {
  11688. svr.stop();
  11689. listen_thread.join();
  11690. ASSERT_FALSE(svr.is_running());
  11691. });
  11692. svr.wait_until_ready();
  11693. Client cli(HOST, PORT);
  11694. cli.set_keep_alive(true);
  11695. for (size_t i = 0; i < 5; i++) {
  11696. auto result = cli.Get("/hi");
  11697. ASSERT_TRUE(result);
  11698. EXPECT_EQ(StatusCode::OK_200, result->status);
  11699. if (i == keep_alive_max_count - 1) {
  11700. EXPECT_EQ("close", result->get_header_value("Connection"));
  11701. } else {
  11702. EXPECT_FALSE(result->has_header("Connection"));
  11703. }
  11704. }
  11705. }
  11706. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11707. // can pull the next one into the server's buffer. The server must serve it
  11708. // without waiting for the socket to become readable again. The keep-alive
  11709. // timeout outlasts the client's read timeout, so a request left waiting for it
  11710. // shows up as a missing response.
  11711. static void serve_pipelining_routes(Server &svr,
  11712. const std::function<void(int)> &client) {
  11713. svr.set_keep_alive_timeout(5);
  11714. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11715. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11716. });
  11717. svr.Post("/echo", [](const Request &req, Response &res) {
  11718. res.set_content("echo " + req.body, "text/plain");
  11719. });
  11720. auto port = svr.bind_to_any_port(HOST);
  11721. thread t = thread([&] { svr.listen_after_bind(); });
  11722. auto se = detail::scope_exit([&] {
  11723. svr.stop();
  11724. t.join();
  11725. });
  11726. svr.wait_until_ready();
  11727. client(port);
  11728. }
  11729. static std::string
  11730. send_pipelined_requests(const std::vector<std::string> &parts) {
  11731. Server svr;
  11732. std::string res;
  11733. serve_pipelining_routes(svr, [&](int port) {
  11734. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11735. });
  11736. return res;
  11737. }
  11738. static void expect_in_order(const std::string &res,
  11739. const std::vector<std::string> &bodies) {
  11740. size_t pos = 0;
  11741. for (const auto &body : bodies) {
  11742. pos = res.find(body, pos);
  11743. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11744. pos += body.size();
  11745. }
  11746. }
  11747. TEST(KeepAliveTest, PipelinedRequests) {
  11748. auto res = send_pipelined_requests(
  11749. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11750. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11751. "Content-Length: 4\r\n\r\nbody"
  11752. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11753. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11754. }
  11755. // The second request starts in the server's buffer and ends on the socket.
  11756. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11757. auto res =
  11758. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11759. "GET /hi/2 HTTP/1.1\r\nHo",
  11760. "st: localhost\r\nConnection: close\r\n\r\n"});
  11761. expect_in_order(res, {"hi 1", "hi 2"});
  11762. }
  11763. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11764. // CRLF after a body does not turn into a 400 for the next request.
  11765. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11766. auto res = send_pipelined_requests(
  11767. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11768. "Content-Length: 4\r\n\r\nbody\r\n"
  11769. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11770. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11771. expect_in_order(res, {"echo body", "hi 2"});
  11772. }
  11773. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11774. // must not be served as the next request.
  11775. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11776. auto res = send_pipelined_requests(
  11777. {"INVALID REQUEST LINE\r\n\r\n"
  11778. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11779. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11780. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11781. }
  11782. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11783. // Over TLS, the next request is held by the TLS library as already decrypted
  11784. // data rather than on the socket.
  11785. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11787. std::string res;
  11788. serve_pipelining_routes(svr, [&](int port) {
  11789. // One part, so all three requests arrive in one TLS record
  11790. EXPECT_TRUE(send_ssl_request_in_parts(
  11791. 2,
  11792. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11793. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11794. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11795. &res, port));
  11796. });
  11797. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11798. }
  11799. #endif
  11800. TEST(KeepAliveTest, Issue1041) {
  11801. Server svr;
  11802. svr.set_keep_alive_timeout(3);
  11803. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11804. res.set_content("Hello World!", "text/plain");
  11805. });
  11806. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11807. auto se = detail::scope_exit([&] {
  11808. svr.stop();
  11809. listen_thread.join();
  11810. ASSERT_FALSE(svr.is_running());
  11811. });
  11812. svr.wait_until_ready();
  11813. Client cli(HOST, PORT);
  11814. cli.set_keep_alive(true);
  11815. auto result = cli.Get("/hi");
  11816. ASSERT_TRUE(result);
  11817. EXPECT_EQ(StatusCode::OK_200, result->status);
  11818. std::this_thread::sleep_for(std::chrono::seconds(5));
  11819. result = cli.Get("/hi");
  11820. ASSERT_TRUE(result);
  11821. EXPECT_EQ(StatusCode::OK_200, result->status);
  11822. }
  11823. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11824. Server svr;
  11825. svr.set_keep_alive_max_count(0);
  11826. std::set<int> remote_ports;
  11827. svr.Get("/hi", [&](const Request &req, Response &res) {
  11828. remote_ports.insert(req.remote_port);
  11829. res.set_content("hi", "text/plain");
  11830. });
  11831. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11832. auto se = detail::scope_exit([&] {
  11833. svr.stop();
  11834. listen_thread.join();
  11835. ASSERT_FALSE(svr.is_running());
  11836. });
  11837. svr.wait_until_ready();
  11838. Client cli(HOST, PORT);
  11839. cli.set_keep_alive(true);
  11840. for (int i = 0; i < 3; i++) {
  11841. auto res = cli.Get("/hi");
  11842. ASSERT_TRUE(res);
  11843. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11844. }
  11845. // All three over one connection
  11846. EXPECT_EQ(1u, remote_ports.size());
  11847. }
  11848. // Forward declaration (see the base64_encode note).
  11849. namespace httplib {
  11850. namespace detail {
  11851. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11852. } // namespace detail
  11853. } // namespace httplib
  11854. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11855. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11856. #ifndef _WIN32
  11857. signal(SIGPIPE, SIG_IGN);
  11858. #endif
  11859. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11860. ASSERT_NE(INVALID_SOCKET, srv);
  11861. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11862. default_socket_options(srv);
  11863. sockaddr_in addr{};
  11864. addr.sin_family = AF_INET;
  11865. addr.sin_port = 0;
  11866. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11867. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11868. ASSERT_EQ(0, ::listen(srv, 2));
  11869. socklen_t addr_len = sizeof(addr);
  11870. ASSERT_EQ(0,
  11871. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11872. auto port = ntohs(addr.sin_port);
  11873. struct Peer {
  11874. socket_t sock = INVALID_SOCKET;
  11875. #ifdef CPPHTTPLIB_SSL_ENABLED
  11876. tls::session_t session = nullptr;
  11877. #endif
  11878. };
  11879. #ifdef CPPHTTPLIB_SSL_ENABLED
  11880. tls::ctx_t ctx = nullptr;
  11881. if (use_tls) {
  11882. ctx = tls::create_server_context();
  11883. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11884. nullptr);
  11885. }
  11886. auto ctx_se = detail::scope_exit([&] {
  11887. if (ctx) { tls::free_context(ctx); }
  11888. });
  11889. #endif
  11890. auto close_peer = [](Peer &peer) {
  11891. #ifdef CPPHTTPLIB_SSL_ENABLED
  11892. if (peer.session) { tls::free_session(peer.session); }
  11893. #endif
  11894. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11895. };
  11896. auto accept_peer = [&]() {
  11897. Peer peer;
  11898. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11899. peer.sock = ::accept(srv, nullptr, nullptr);
  11900. if (peer.sock == INVALID_SOCKET) { return peer; }
  11901. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11902. #ifdef CPPHTTPLIB_SSL_ENABLED
  11903. if (use_tls) {
  11904. peer.session = tls::create_session(ctx, peer.sock);
  11905. tls::TlsError err;
  11906. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11907. nullptr)) {
  11908. close_peer(peer);
  11909. return Peer();
  11910. }
  11911. }
  11912. #endif
  11913. return peer;
  11914. };
  11915. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11916. #ifdef CPPHTTPLIB_SSL_ENABLED
  11917. tls::TlsError err;
  11918. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11919. #endif
  11920. return detail::read_socket(peer.sock, buf, len, 0);
  11921. };
  11922. auto read_head = [&](const Peer &peer) {
  11923. std::string head;
  11924. char buf[1024];
  11925. while (head.find("\r\n\r\n") == std::string::npos) {
  11926. auto n = read_some(peer, buf, sizeof(buf));
  11927. if (n <= 0) { break; }
  11928. head.append(buf, static_cast<size_t>(n));
  11929. }
  11930. };
  11931. auto send_text = [](const Peer &peer, const std::string &text) {
  11932. #ifdef CPPHTTPLIB_SSL_ENABLED
  11933. tls::TlsError err;
  11934. if (peer.session) {
  11935. tls::write(peer.session, text.data(), text.size(), err);
  11936. return;
  11937. }
  11938. #endif
  11939. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11940. };
  11941. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11942. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11943. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11944. // Sent once the first response is read, so that it lands on an idle socket
  11945. std::promise<void> first_response_read;
  11946. auto first_response_read_future = first_response_read.get_future();
  11947. auto server_thread = std::thread([&] {
  11948. auto peer1 = accept_peer();
  11949. if (peer1.sock == INVALID_SOCKET) { return; }
  11950. read_head(peer1);
  11951. if (same_write) {
  11952. send_text(peer1, first + stray);
  11953. } else {
  11954. send_text(peer1, first);
  11955. first_response_read_future.wait_for(std::chrono::seconds(5));
  11956. send_text(peer1, stray);
  11957. }
  11958. // peer1 stays open, so only the unread data can tell the client
  11959. auto peer2 = accept_peer();
  11960. if (peer2.sock != INVALID_SOCKET) {
  11961. read_head(peer2);
  11962. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11963. "Connection: close\r\n\r\nsecond");
  11964. close_peer(peer2);
  11965. }
  11966. close_peer(peer1);
  11967. });
  11968. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11969. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11970. std::to_string(port));
  11971. #ifdef CPPHTTPLIB_SSL_ENABLED
  11972. cli.enable_server_certificate_verification(false);
  11973. #endif
  11974. cli.set_keep_alive(true);
  11975. cli.set_read_timeout(5, 0);
  11976. auto res = cli.Get("/1");
  11977. first_response_read.set_value();
  11978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11979. EXPECT_EQ("first", res->body);
  11980. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11981. res = cli.Get("/2");
  11982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11983. EXPECT_EQ(StatusCode::OK_200, res->status);
  11984. EXPECT_EQ("second", res->body);
  11985. }
  11986. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11987. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11988. }
  11989. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11990. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11991. }
  11992. #ifdef CPPHTTPLIB_SSL_ENABLED
  11993. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11994. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11995. }
  11996. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11997. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11998. }
  11999. #endif
  12000. TEST(KeepAliveTest, Issue1959) {
  12001. Server svr;
  12002. svr.set_keep_alive_timeout(5);
  12003. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12004. res.set_content("a", "text/plain");
  12005. });
  12006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12007. auto se = detail::scope_exit([&] {
  12008. if (!svr.is_running()) return;
  12009. svr.stop();
  12010. listen_thread.join();
  12011. ASSERT_FALSE(svr.is_running());
  12012. });
  12013. svr.wait_until_ready();
  12014. Client cli("localhost", PORT);
  12015. cli.set_keep_alive(true);
  12016. using namespace std::chrono;
  12017. auto start = steady_clock::now();
  12018. cli.Get("/a");
  12019. svr.stop();
  12020. listen_thread.join();
  12021. auto end = steady_clock::now();
  12022. auto elapsed = duration_cast<milliseconds>(end - start).count();
  12023. EXPECT_LT(elapsed, 5000);
  12024. }
  12025. #ifdef CPPHTTPLIB_SSL_ENABLED
  12026. TEST(KeepAliveTest, SSLClientReconnection) {
  12027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12028. ASSERT_TRUE(svr.is_valid());
  12029. svr.set_keep_alive_timeout(1);
  12030. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  12031. res.set_content("Hello World!", "text/plain");
  12032. });
  12033. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12034. auto se = detail::scope_exit([&] {
  12035. svr.stop();
  12036. listen_thread.join();
  12037. ASSERT_FALSE(svr.is_running());
  12038. });
  12039. svr.wait_until_ready();
  12040. SSLClient cli(HOST, PORT);
  12041. cli.enable_server_certificate_verification(false);
  12042. cli.set_keep_alive(true);
  12043. auto result = cli.Get("/hi");
  12044. ASSERT_TRUE(result);
  12045. EXPECT_EQ(StatusCode::OK_200, result->status);
  12046. result = cli.Get("/hi");
  12047. ASSERT_TRUE(result);
  12048. EXPECT_EQ(StatusCode::OK_200, result->status);
  12049. std::this_thread::sleep_for(std::chrono::seconds(2));
  12050. // Recoonect
  12051. result = cli.Get("/hi");
  12052. ASSERT_TRUE(result);
  12053. EXPECT_EQ(StatusCode::OK_200, result->status);
  12054. result = cli.Get("/hi");
  12055. ASSERT_TRUE(result);
  12056. EXPECT_EQ(StatusCode::OK_200, result->status);
  12057. }
  12058. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  12059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12060. ASSERT_TRUE(svr.is_valid());
  12061. svr.set_keep_alive_timeout(1);
  12062. std::string content = "reconnect";
  12063. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  12064. res.set_content("Hello World!", "text/plain");
  12065. });
  12066. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12067. auto se = detail::scope_exit([&] {
  12068. svr.stop();
  12069. listen_thread.join();
  12070. ASSERT_FALSE(svr.is_running());
  12071. });
  12072. svr.wait_until_ready();
  12073. SSLClient cli(HOST, PORT);
  12074. cli.enable_server_certificate_verification(false);
  12075. cli.set_keep_alive(true);
  12076. auto result = cli.Post(
  12077. "/hi", content.size(),
  12078. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12079. sink.write(content.c_str(), content.size());
  12080. return true;
  12081. },
  12082. "text/plain");
  12083. ASSERT_TRUE(result);
  12084. EXPECT_EQ(200, result->status);
  12085. std::this_thread::sleep_for(std::chrono::seconds(2));
  12086. // Recoonect
  12087. result = cli.Post(
  12088. "/hi", content.size(),
  12089. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12090. sink.write(content.c_str(), content.size());
  12091. return true;
  12092. },
  12093. "text/plain");
  12094. ASSERT_TRUE(result);
  12095. EXPECT_EQ(200, result->status);
  12096. result = cli.Post(
  12097. "/hi", content.size(),
  12098. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12099. sink.write(content.c_str(), content.size());
  12100. return true;
  12101. },
  12102. "text/plain");
  12103. ASSERT_TRUE(result);
  12104. EXPECT_EQ(200, result->status);
  12105. }
  12106. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  12107. using namespace httplib::tls;
  12108. {
  12109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12110. ASSERT_TRUE(svr.is_valid());
  12111. svr.Get("/sni", [&](const Request &req, Response &res) {
  12112. std::string expected = req.sni();
  12113. EXPECT_EQ(expected, req.get_param_value("expected"));
  12114. res.set_content("ok", "text/plain");
  12115. });
  12116. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12117. auto se = detail::scope_exit([&] {
  12118. svr.stop();
  12119. listen_thread.join();
  12120. ASSERT_FALSE(svr.is_running());
  12121. });
  12122. svr.wait_until_ready();
  12123. {
  12124. SSLClient cli("localhost", PORT);
  12125. cli.enable_server_certificate_verification(false);
  12126. auto res = cli.Get("/sni?expected=localhost");
  12127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12128. }
  12129. {
  12130. SSLClient cli("::1", PORT);
  12131. cli.enable_server_certificate_verification(false);
  12132. auto res = cli.Get("/sni?expected=");
  12133. // NOTE: This may fail if the server is listening on IPv4 only
  12134. // (e.g., when localhost resolves to 127.0.0.1 only)
  12135. if (res) {
  12136. EXPECT_EQ(StatusCode::OK_200, res->status);
  12137. } else {
  12138. EXPECT_EQ(Error::Connection, res.error());
  12139. }
  12140. }
  12141. }
  12142. }
  12143. // The SNI of a failed handshake does not reach the next connection that the
  12144. // same worker thread serves
  12145. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  12146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12147. ASSERT_TRUE(svr.is_valid());
  12148. svr.new_task_queue = [] { return new ThreadPool(1); };
  12149. svr.Get("/sni", [](const Request &req, Response &res) {
  12150. res.set_content(req.sni(), "text/plain");
  12151. });
  12152. auto port = svr.bind_to_any_port("127.0.0.1");
  12153. ASSERT_LT(0, port);
  12154. thread t = thread([&] { svr.listen_after_bind(); });
  12155. auto se = detail::scope_exit([&] {
  12156. svr.stop();
  12157. t.join();
  12158. ASSERT_FALSE(svr.is_running());
  12159. });
  12160. svr.wait_until_ready();
  12161. {
  12162. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12163. SSLClient cli("localhost", port);
  12164. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12165. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12166. auto res = cli.Get("/sni");
  12167. ASSERT_FALSE(res);
  12168. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12169. }
  12170. // An IP host sends no SNI (RFC 6066)
  12171. SSLClient cli("127.0.0.1", port);
  12172. cli.enable_server_certificate_verification(false);
  12173. auto res = cli.Get("/sni");
  12174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12175. EXPECT_EQ("", res->body);
  12176. }
  12177. #endif
  12178. TEST(ClientProblemDetectionTest, ContentProvider) {
  12179. Server svr;
  12180. size_t content_length = 1024 * 1024;
  12181. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12182. res.set_content_provider(
  12183. content_length, "text/plain",
  12184. [&](size_t offset, size_t length, DataSink &sink) {
  12185. auto out_len = std::min(length, static_cast<size_t>(1024));
  12186. std::string out(out_len, '@');
  12187. sink.write(out.data(), out_len);
  12188. return offset < 4096;
  12189. },
  12190. [](bool success) { ASSERT_FALSE(success); });
  12191. });
  12192. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12193. res.set_content_provider(
  12194. 0, "text/plain",
  12195. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12196. EXPECT_TRUE(false);
  12197. return true;
  12198. },
  12199. [](bool success) { ASSERT_FALSE(success); });
  12200. });
  12201. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12202. auto se = detail::scope_exit([&] {
  12203. svr.stop();
  12204. listen_thread.join();
  12205. ASSERT_FALSE(svr.is_running());
  12206. });
  12207. svr.wait_until_ready();
  12208. Client cli("localhost", PORT);
  12209. {
  12210. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12211. size_t /*data_length*/) { return false; });
  12212. ASSERT_FALSE(res);
  12213. }
  12214. {
  12215. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12216. size_t /*data_length*/) { return false; });
  12217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12218. }
  12219. }
  12220. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12221. // A provider that reports success without writing anything and without
  12222. // calling done() used to be handed the same offset and length again on every
  12223. // pass, so it spun for as long as the peer stayed connected.
  12224. Server svr;
  12225. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12226. res.set_content("ok", "text/plain");
  12227. });
  12228. auto port = svr.bind_to_any_port(HOST);
  12229. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12230. auto se = detail::scope_exit([&] {
  12231. svr.stop();
  12232. listen_thread.join();
  12233. ASSERT_FALSE(svr.is_running());
  12234. });
  12235. svr.wait_until_ready();
  12236. std::atomic<int> call_count{0};
  12237. Client cli(HOST, port);
  12238. auto res = cli.Post(
  12239. "/", 1024,
  12240. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12241. // Give up after enough passes to show the spin, so that losing the
  12242. // check below fails this test instead of hanging it.
  12243. return ++call_count < 100;
  12244. },
  12245. "text/plain");
  12246. ASSERT_FALSE(res);
  12247. EXPECT_EQ(Error::Write, res.error());
  12248. EXPECT_EQ(1, call_count.load());
  12249. }
  12250. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12251. // A writer only has to assign `write`. The other three used to be left as
  12252. // empty std::functions, so a provider calling one threw
  12253. // std::bad_function_call out of the thread running it and took the whole
  12254. // process down.
  12255. DataSink sink;
  12256. std::string written;
  12257. sink.write = [&](const char *data, size_t data_len) {
  12258. written.append(data, data_len);
  12259. return true;
  12260. };
  12261. EXPECT_TRUE(sink.is_writable());
  12262. sink.done();
  12263. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12264. EXPECT_TRUE(written.empty());
  12265. }
  12266. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12267. // A sink that cannot carry trailers still has to finish.
  12268. DataSink sink;
  12269. auto done_count = 0;
  12270. sink.done = [&]() { done_count++; };
  12271. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12272. EXPECT_EQ(1, done_count);
  12273. }
  12274. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12275. Server svr;
  12276. const std::string body(4096, 'x');
  12277. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12278. res.set_content_provider(body.size(), "text/plain",
  12279. [&](size_t offset, size_t length, DataSink &sink) {
  12280. sink.write(body.data() + offset, length);
  12281. sink.done();
  12282. return true;
  12283. });
  12284. });
  12285. auto port = svr.bind_to_any_port(HOST);
  12286. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12287. auto se = detail::scope_exit([&] {
  12288. svr.stop();
  12289. listen_thread.join();
  12290. ASSERT_FALSE(svr.is_running());
  12291. });
  12292. svr.wait_until_ready();
  12293. Client cli(HOST, port);
  12294. auto res = cli.Get("/");
  12295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12296. EXPECT_EQ(StatusCode::OK_200, res->status);
  12297. EXPECT_EQ(body, res->body);
  12298. }
  12299. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12300. Server svr;
  12301. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12302. res.set_content_provider(
  12303. 1024, "text/plain",
  12304. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12305. sink.write("hello", 5);
  12306. sink.done(); // short of the 1024 bytes the response promised
  12307. return true;
  12308. });
  12309. });
  12310. auto port = svr.bind_to_any_port(HOST);
  12311. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12312. auto se = detail::scope_exit([&] {
  12313. svr.stop();
  12314. listen_thread.join();
  12315. ASSERT_FALSE(svr.is_running());
  12316. });
  12317. svr.wait_until_ready();
  12318. Client cli(HOST, port);
  12319. cli.set_read_timeout(5, 0);
  12320. // The response is short of its Content-Length, so the client cannot read a
  12321. // complete body. What matters is that this returns at all: a no-op done()
  12322. // would leave the writer looping over a provider that never makes progress.
  12323. auto res = cli.Get("/");
  12324. EXPECT_FALSE(res);
  12325. }
  12326. // Read as the next response by a peer that sees it after a framed body.
  12327. static const std::string smuggled_response =
  12328. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12329. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12330. Server svr;
  12331. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12332. res.set_content_provider(
  12333. 5, "text/plain",
  12334. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12335. auto data = "AAAAA" + smuggled_response;
  12336. sink.write(data.data(), data.size());
  12337. return true;
  12338. });
  12339. });
  12340. thread t = thread([&] { svr.listen(HOST, PORT); });
  12341. auto se = detail::scope_exit([&] {
  12342. svr.stop();
  12343. t.join();
  12344. ASSERT_FALSE(svr.is_running());
  12345. });
  12346. svr.wait_until_ready();
  12347. std::string resp;
  12348. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12349. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12350. resp.clear();
  12351. ASSERT_TRUE(send_request(
  12352. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12353. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12354. }
  12355. TEST(NoContentTest, BodyIsNotSent) {
  12356. Server svr;
  12357. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12358. res.status = StatusCode::NoContent_204;
  12359. res.set_content(smuggled_response, "text/plain");
  12360. });
  12361. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12362. res.status = StatusCode::NotModified_304;
  12363. res.set_chunked_content_provider(
  12364. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12365. sink.write(smuggled_response.data(), smuggled_response.size());
  12366. sink.done();
  12367. return true;
  12368. });
  12369. });
  12370. thread t = thread([&] { svr.listen(HOST, PORT); });
  12371. auto se = detail::scope_exit([&] {
  12372. svr.stop();
  12373. t.join();
  12374. ASSERT_FALSE(svr.is_running());
  12375. });
  12376. svr.wait_until_ready();
  12377. for (auto path : {"/204", "/304"}) {
  12378. std::string resp;
  12379. ASSERT_TRUE(send_request(
  12380. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12381. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12382. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12383. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12384. }
  12385. }
  12386. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12387. Server svr;
  12388. std::atomic<bool> smuggled(false);
  12389. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12390. res.set_content("ok", "text/plain");
  12391. });
  12392. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12393. smuggled = true;
  12394. });
  12395. auto port = svr.bind_to_any_port(HOST);
  12396. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12397. auto se = detail::scope_exit([&] {
  12398. svr.stop();
  12399. listen_thread.join();
  12400. ASSERT_FALSE(svr.is_running());
  12401. });
  12402. svr.wait_until_ready();
  12403. // What follows the body would be read as the next request.
  12404. Client cli(HOST, port);
  12405. auto res = cli.Post(
  12406. "/", 5,
  12407. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12408. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12409. sink.write(data.data(), data.size());
  12410. return true;
  12411. },
  12412. "text/plain");
  12413. ASSERT_FALSE(res);
  12414. EXPECT_EQ(Error::Write, res.error());
  12415. EXPECT_FALSE(smuggled);
  12416. }
  12417. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12418. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12419. // The compressed path builds the whole body before connecting, so this
  12420. // fails client-side and never reaches a server.
  12421. Client cli(HOST, PORT);
  12422. cli.set_compress(true);
  12423. auto res = cli.Post(
  12424. "/", 1024,
  12425. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12426. sink.write("hello", 5);
  12427. sink.done(); // short of the 1024 bytes the request announced
  12428. return true;
  12429. },
  12430. "text/plain");
  12431. ASSERT_FALSE(res);
  12432. EXPECT_EQ(Error::Write, res.error());
  12433. }
  12434. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12435. Server svr;
  12436. std::string received;
  12437. size_t content_length_count = 0;
  12438. bool has_transfer_encoding = true;
  12439. svr.Post("/echo", [&](const Request &req, Response &res) {
  12440. received = req.body;
  12441. content_length_count = req.get_header_value_count("Content-Length");
  12442. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12443. res.set_content("ok", "text/plain");
  12444. });
  12445. svr.Get("/next", [](const Request &, Response &res) {
  12446. res.set_content("next", "text/plain");
  12447. });
  12448. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12449. auto se = detail::scope_exit([&] {
  12450. svr.stop();
  12451. listen_thread.join();
  12452. ASSERT_FALSE(svr.is_running());
  12453. });
  12454. svr.wait_until_ready();
  12455. Client cli(HOST, PORT);
  12456. cli.set_keep_alive(true);
  12457. cli.set_compress(true);
  12458. const std::string body = "hello world";
  12459. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12460. auto res = cli.Post("/echo", headers, body, "text/plain");
  12461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12462. EXPECT_EQ(StatusCode::OK_200, res->status);
  12463. EXPECT_EQ(body, received);
  12464. EXPECT_EQ(1u, content_length_count);
  12465. EXPECT_FALSE(has_transfer_encoding);
  12466. // The rest of a truncated body would be read as this request
  12467. auto res2 = cli.Get("/next");
  12468. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12469. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12470. EXPECT_EQ("next", res2->body);
  12471. }
  12472. #endif
  12473. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12474. Server svr;
  12475. std::string received;
  12476. size_t content_length_count = 1;
  12477. bool has_transfer_encoding = false;
  12478. svr.Post("/echo", [&](const Request &req, Response &res) {
  12479. received = req.body;
  12480. content_length_count = req.get_header_value_count("Content-Length");
  12481. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12482. res.set_content("ok", "text/plain");
  12483. });
  12484. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12485. auto se = detail::scope_exit([&] {
  12486. svr.stop();
  12487. listen_thread.join();
  12488. ASSERT_FALSE(svr.is_running());
  12489. });
  12490. svr.wait_until_ready();
  12491. Client cli(HOST, PORT);
  12492. cli.set_keep_alive(true);
  12493. const std::string body = "hello world";
  12494. Headers headers = {{"Content-Length", "5"}};
  12495. auto res = cli.Post(
  12496. "/echo", headers,
  12497. [&](size_t /*offset*/, DataSink &sink) {
  12498. sink.write(body.data(), body.size());
  12499. sink.done();
  12500. return true;
  12501. },
  12502. "text/plain");
  12503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12504. EXPECT_EQ(StatusCode::OK_200, res->status);
  12505. EXPECT_EQ(body, received);
  12506. EXPECT_EQ(0u, content_length_count);
  12507. EXPECT_TRUE(has_transfer_encoding);
  12508. }
  12509. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12510. Server svr;
  12511. svr.set_error_handler([](Request const &, Response &res) -> void {
  12512. res.set_chunked_content_provider(
  12513. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12514. sink.os << "hello";
  12515. sink.os << "world";
  12516. sink.done();
  12517. return true;
  12518. });
  12519. });
  12520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12521. auto se = detail::scope_exit([&] {
  12522. svr.stop();
  12523. listen_thread.join();
  12524. ASSERT_FALSE(svr.is_running());
  12525. });
  12526. svr.wait_until_ready();
  12527. Client cli("localhost", PORT);
  12528. auto res = cli.Get("/");
  12529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12531. EXPECT_EQ("helloworld", res->body);
  12532. }
  12533. // A body set after a content provider must replace it, not be sent through it.
  12534. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12535. Server svr;
  12536. svr.set_mount_point("/", "./www");
  12537. svr.set_file_request_handler([](const Request &req, Response &res) {
  12538. if (req.path == "/dir/test.html") {
  12539. res.status = StatusCode::Forbidden_403;
  12540. res.set_content(std::string(5000, 'D'), "text/plain");
  12541. } else if (req.path == "/file") {
  12542. res.status = StatusCode::Forbidden_403;
  12543. res.body = "Denied";
  12544. }
  12545. });
  12546. auto port = svr.bind_to_any_port(HOST);
  12547. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12548. auto se = detail::scope_exit([&] {
  12549. svr.stop();
  12550. t.join();
  12551. ASSERT_FALSE(svr.is_running());
  12552. });
  12553. svr.wait_until_ready();
  12554. Client cli(HOST, port);
  12555. {
  12556. auto res = cli.Get("/dir/test.html");
  12557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12558. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12559. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12560. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12561. }
  12562. {
  12563. auto res = cli.Get("/file");
  12564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12565. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12566. EXPECT_EQ("Denied", res->body);
  12567. }
  12568. {
  12569. auto res = cli.Get("/dir/index.html");
  12570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12571. EXPECT_EQ(StatusCode::OK_200, res->status);
  12572. EXPECT_EQ(0U, res->body.find("<html>"));
  12573. }
  12574. }
  12575. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12576. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12577. Server svr;
  12578. std::vector<bool> released;
  12579. std::mutex released_mutex;
  12580. auto releaser = [&](bool success) {
  12581. std::lock_guard<std::mutex> guard(released_mutex);
  12582. released.push_back(success);
  12583. };
  12584. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12585. return sink.write(&"hello"[offset], length);
  12586. };
  12587. svr.Get("/sized", [&](const Request &, Response &res) {
  12588. res.status = StatusCode::NotFound_404;
  12589. res.set_content_provider(5, "text/plain", provider, releaser);
  12590. });
  12591. svr.Get("/chunked", [&](const Request &, Response &res) {
  12592. res.status = StatusCode::ServiceUnavailable_503;
  12593. res.set_chunked_content_provider(
  12594. "text/plain",
  12595. [](size_t, DataSink &sink) {
  12596. sink.os << "chunk";
  12597. sink.done();
  12598. return true;
  12599. },
  12600. releaser);
  12601. });
  12602. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12603. res.set_content_provider(5, "text/plain", provider, releaser);
  12604. throw std::runtime_error("after the provider");
  12605. });
  12606. svr.set_error_handler([](const Request &req, Response &res) {
  12607. // Leave the exception handler's content to it.
  12608. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12609. res.set_content(std::string(1000, 'E'), "text/html");
  12610. return Server::HandlerResponse::Handled;
  12611. });
  12612. svr.set_exception_handler(
  12613. [](const Request &, Response &res, std::exception_ptr) {
  12614. res.status = StatusCode::InternalServerError_500;
  12615. res.set_content(std::string(1000, 'X'), "text/html");
  12616. });
  12617. auto port = svr.bind_to_any_port(HOST);
  12618. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12619. auto se = detail::scope_exit([&] {
  12620. svr.stop();
  12621. t.join();
  12622. ASSERT_FALSE(svr.is_running());
  12623. });
  12624. svr.wait_until_ready();
  12625. Client cli(HOST, port);
  12626. {
  12627. auto res = cli.Get("/sized");
  12628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12629. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12630. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12631. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12632. }
  12633. {
  12634. auto res = cli.Get("/chunked");
  12635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12636. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12637. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12638. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12639. }
  12640. {
  12641. auto res = cli.Get("/throw");
  12642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12643. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12644. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12645. }
  12646. std::lock_guard<std::mutex> guard(released_mutex);
  12647. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12648. }
  12649. #endif
  12650. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12651. Server svr;
  12652. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12653. return sink.write(&"abc"[offset], length);
  12654. };
  12655. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12656. res.set_file_content("./www/dir/test.html");
  12657. res.set_content("body", "text/plain");
  12658. });
  12659. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12660. res.set_content(std::string(100, 'B'), "text/plain");
  12661. res.set_file_content("./www/dir/test.html");
  12662. });
  12663. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12664. res.set_content(std::string(100, 'B'), "text/plain");
  12665. res.set_content_provider(3, "text/x-provider", abc);
  12666. });
  12667. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12668. res.set_content_provider(3, "text/x-provider", abc);
  12669. res.set_content(std::string(100, 'B'), "text/plain");
  12670. });
  12671. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12672. res.set_content_provider(3, "text/x-provider", abc);
  12673. res.set_file_content("./www/dir/test.html", "text/x-file");
  12674. });
  12675. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12676. res.set_file_content("./www/dir/test.html");
  12677. res.set_header("Content-Type", "text/x-handler");
  12678. });
  12679. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12680. res.set_content_provider(3, "text/plain", abc);
  12681. res.body = "direct";
  12682. });
  12683. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12684. res.set_file_content("./www/dir/test.html");
  12685. res.body = "direct";
  12686. });
  12687. auto port = svr.bind_to_any_port(HOST);
  12688. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12689. auto se = detail::scope_exit([&] {
  12690. svr.stop();
  12691. t.join();
  12692. ASSERT_FALSE(svr.is_running());
  12693. });
  12694. svr.wait_until_ready();
  12695. Client cli(HOST, port);
  12696. auto expect_body = [&](const char *path, const std::string &body,
  12697. const std::string &type) {
  12698. // Uncompressed, so Content-Length can be compared with the body.
  12699. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12700. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12701. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12702. EXPECT_EQ(body, res->body) << path;
  12703. EXPECT_EQ(std::to_string(body.size()),
  12704. res->get_header_value("Content-Length"))
  12705. << path;
  12706. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12707. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12708. };
  12709. expect_body("/file-then-body", "body", "text/plain");
  12710. expect_body("/body-then-file", "test.html", "text/html");
  12711. expect_body("/body-then-provider", "abc", "text/x-provider");
  12712. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12713. expect_body("/provider-then-file", "test.html", "text/x-file");
  12714. expect_body("/file-then-header", "test.html", "text/x-handler");
  12715. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12716. expect_body("/file-then-direct-body", "direct", "text/plain");
  12717. // Ranges are checked against the body, not the dropped provider.
  12718. {
  12719. auto res = cli.Get("/provider-then-direct-body",
  12720. Headers{{make_range_header({{1, 2}})}});
  12721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12723. EXPECT_EQ("ir", res->body);
  12724. }
  12725. {
  12726. auto res = cli.Get("/file-then-direct-body",
  12727. Headers{{make_range_header({{7, 8}})}});
  12728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12729. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12730. }
  12731. }
  12732. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12733. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12734. const char *path = "./truncated_while_served.txt";
  12735. const size_t size = 32 * 1024 * 1024;
  12736. {
  12737. std::ofstream f(path, std::ios::binary);
  12738. f << std::string(size, 'x');
  12739. }
  12740. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12741. // Over TLS, where the bytes are encrypted in this process rather than
  12742. // copied by send().
  12743. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12744. svr.Get("/file", [&](const Request &, Response &res) {
  12745. res.set_file_content(path, "text/plain");
  12746. });
  12747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12748. auto se = detail::scope_exit([&] {
  12749. svr.stop();
  12750. thread.join();
  12751. ASSERT_FALSE(svr.is_running());
  12752. });
  12753. svr.wait_until_ready();
  12754. // The file shrinks once the first bytes are in, as a rewrite in place
  12755. // would, and reading the mapping past its new end used to raise SIGBUS.
  12756. SSLClient cli(HOST, PORT);
  12757. cli.enable_server_certificate_verification(false);
  12758. size_t received = 0;
  12759. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12760. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12761. received += len;
  12762. return true;
  12763. });
  12764. EXPECT_FALSE(res);
  12765. EXPECT_LT(received, size);
  12766. }
  12767. #endif
  12768. // Forward declaration (see the base64_encode note).
  12769. namespace httplib {
  12770. namespace detail {
  12771. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12772. const std::string &content_type,
  12773. EncodingType encoding);
  12774. } // namespace detail
  12775. } // namespace httplib
  12776. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12777. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12778. ASSERT_TRUE(mm->is_open());
  12779. Response res;
  12780. detail::set_file_content_provider(res, mm, "text/html",
  12781. detail::EncodingType::None);
  12782. std::string out;
  12783. DataSink sink;
  12784. sink.write = [&](const char *d, size_t l) {
  12785. out.append(d, l);
  12786. return true;
  12787. };
  12788. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12789. EXPECT_EQ("test.html", out);
  12790. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12791. EXPECT_EQ("test.html", out);
  12792. }
  12793. TEST(LongPollingTest, ClientCloseDetection) {
  12794. Server svr;
  12795. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12796. res.set_chunked_content_provider(
  12797. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12798. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12799. sink.os << "hello";
  12800. auto count = 10;
  12801. while (count > 0 && sink.is_writable()) {
  12802. this_thread::sleep_for(chrono::milliseconds(10));
  12803. count--;
  12804. }
  12805. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12806. return true;
  12807. });
  12808. });
  12809. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12810. auto se = detail::scope_exit([&] {
  12811. svr.stop();
  12812. listen_thread.join();
  12813. ASSERT_FALSE(svr.is_running());
  12814. });
  12815. svr.wait_until_ready();
  12816. Client cli("localhost", PORT);
  12817. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12818. EXPECT_EQ("hello", string(data, data_length));
  12819. return false; // close the socket immediately.
  12820. });
  12821. ASSERT_FALSE(res);
  12822. }
  12823. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12824. Server svr;
  12825. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12826. res.set_chunked_content_provider(
  12827. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12828. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12829. sink.os << "hello";
  12830. EXPECT_TRUE(sink.os.good());
  12831. // Wait for the client to close the connection
  12832. auto count = 10;
  12833. while (count > 0 && sink.is_writable()) {
  12834. this_thread::sleep_for(chrono::milliseconds(10));
  12835. count--;
  12836. }
  12837. // After client disconnect, write repeatedly until the socket
  12838. // write actually fails (small writes may be absorbed by the
  12839. // kernel buffer)
  12840. std::string chunk(1024, 'x');
  12841. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12842. sink.os << chunk;
  12843. }
  12844. EXPECT_TRUE(sink.os.fail());
  12845. return true;
  12846. });
  12847. });
  12848. auto port = svr.bind_to_any_port("localhost");
  12849. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12850. auto se = detail::scope_exit([&] {
  12851. svr.stop();
  12852. listen_thread.join();
  12853. ASSERT_FALSE(svr.is_running());
  12854. });
  12855. svr.wait_until_ready();
  12856. Client cli("localhost", port);
  12857. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12858. EXPECT_EQ("hello", string(data, data_length));
  12859. return false; // close the socket immediately.
  12860. });
  12861. ASSERT_FALSE(res);
  12862. }
  12863. TEST(GetWithParametersTest, GetWithParameters) {
  12864. Server svr;
  12865. svr.Get("/", [&](const Request &req, Response &) {
  12866. EXPECT_EQ("world", req.get_param_value("hello"));
  12867. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12868. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12869. });
  12870. svr.Get("/params", [&](const Request &req, Response &) {
  12871. EXPECT_EQ("world", req.get_param_value("hello"));
  12872. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12873. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12874. });
  12875. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12876. EXPECT_EQ("resource-id", req.matches[1]);
  12877. EXPECT_EQ("foo", req.get_param_value("param1"));
  12878. EXPECT_EQ("bar", req.get_param_value("param2"));
  12879. });
  12880. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12881. EXPECT_EQ("user-id", req.path_params.at("id"));
  12882. EXPECT_EQ("foo", req.get_param_value("param1"));
  12883. EXPECT_EQ("bar", req.get_param_value("param2"));
  12884. });
  12885. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12886. auto se = detail::scope_exit([&] {
  12887. svr.stop();
  12888. listen_thread.join();
  12889. ASSERT_FALSE(svr.is_running());
  12890. });
  12891. svr.wait_until_ready();
  12892. {
  12893. Client cli(HOST, PORT);
  12894. Params params;
  12895. params.emplace("hello", "world");
  12896. params.emplace("hello2", "world2");
  12897. params.emplace("hello3", "world3");
  12898. auto res = cli.Get("/", params, Headers{});
  12899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12900. EXPECT_EQ(StatusCode::OK_200, res->status);
  12901. }
  12902. {
  12903. Client cli(HOST, PORT);
  12904. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12906. EXPECT_EQ(StatusCode::OK_200, res->status);
  12907. }
  12908. {
  12909. Client cli(HOST, PORT);
  12910. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12912. EXPECT_EQ(StatusCode::OK_200, res->status);
  12913. }
  12914. {
  12915. Client cli(HOST, PORT);
  12916. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12918. EXPECT_EQ(StatusCode::OK_200, res->status);
  12919. }
  12920. }
  12921. TEST(GetWithParametersTest, GetWithParameters2) {
  12922. Server svr;
  12923. svr.Get("/", [&](const Request &req, Response &res) {
  12924. auto text = req.get_param_value("hello");
  12925. res.set_content(text, "text/plain");
  12926. });
  12927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12928. auto se = detail::scope_exit([&] {
  12929. svr.stop();
  12930. listen_thread.join();
  12931. ASSERT_FALSE(svr.is_running());
  12932. });
  12933. svr.wait_until_ready();
  12934. Client cli("localhost", PORT);
  12935. Params params;
  12936. params.emplace("hello", "world");
  12937. std::string body;
  12938. auto res = cli.Get("/", params, Headers{},
  12939. [&](const char *data, size_t data_length) {
  12940. body.append(data, data_length);
  12941. return true;
  12942. });
  12943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12944. EXPECT_EQ(StatusCode::OK_200, res->status);
  12945. EXPECT_EQ("world", body);
  12946. }
  12947. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12948. Server svr;
  12949. svr.Get("/search", [&](const Request &req, Response &res) {
  12950. auto q = req.get_param_value("q");
  12951. res.set_content(q, "text/plain");
  12952. });
  12953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12954. auto se = detail::scope_exit([&] {
  12955. svr.stop();
  12956. listen_thread.join();
  12957. ASSERT_FALSE(svr.is_running());
  12958. });
  12959. svr.wait_until_ready();
  12960. Client cli("localhost", PORT);
  12961. // Verify that Get(path, params) works without requiring Headers argument
  12962. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12964. EXPECT_EQ(StatusCode::OK_200, res->status);
  12965. EXPECT_EQ("cpp-httplib", res->body);
  12966. }
  12967. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12968. auto host = "httpbingo.org";
  12969. auto path = std::string{"/range/32"};
  12970. #ifdef CPPHTTPLIB_SSL_ENABLED
  12971. SSLClient cli(host);
  12972. #else
  12973. Client cli(host);
  12974. #endif
  12975. cli.set_default_headers({make_range_header({{1, 10}})});
  12976. cli.set_connection_timeout(5);
  12977. {
  12978. auto res = retry_service_failures([&] { return cli.Get(path); });
  12979. SKIP_ON_SERVICE_FAILURE(res);
  12980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12981. EXPECT_EQ("bcdefghijk", res->body);
  12982. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12983. }
  12984. {
  12985. auto res = retry_service_failures([&] { return cli.Get(path); });
  12986. SKIP_ON_SERVICE_FAILURE(res);
  12987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12988. EXPECT_EQ("bcdefghijk", res->body);
  12989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12990. }
  12991. }
  12992. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12993. Server svr;
  12994. svr.set_default_headers({{"Hello", "World"}});
  12995. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12996. res.set_content("ok", "text/plain");
  12997. });
  12998. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12999. auto se = detail::scope_exit([&] {
  13000. svr.stop();
  13001. listen_thread.join();
  13002. ASSERT_FALSE(svr.is_running());
  13003. });
  13004. svr.wait_until_ready();
  13005. Client cli("localhost", PORT);
  13006. auto res = cli.Get("/");
  13007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13008. EXPECT_EQ(StatusCode::OK_200, res->status);
  13009. EXPECT_EQ("ok", res->body);
  13010. EXPECT_EQ("World", res->get_header_value("Hello"));
  13011. }
  13012. #ifdef CPPHTTPLIB_SSL_ENABLED
  13013. TEST(KeepAliveTest, ReadTimeoutSSL) {
  13014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13015. ASSERT_TRUE(svr.is_valid());
  13016. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  13017. std::this_thread::sleep_for(std::chrono::seconds(2));
  13018. res.set_content("a", "text/plain");
  13019. });
  13020. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  13021. res.set_content("b", "text/plain");
  13022. });
  13023. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. listen_thread.join();
  13027. ASSERT_FALSE(svr.is_running());
  13028. });
  13029. svr.wait_until_ready();
  13030. SSLClient cli("localhost", PORT);
  13031. cli.enable_server_certificate_verification(false);
  13032. cli.set_keep_alive(true);
  13033. cli.set_read_timeout(std::chrono::seconds(1));
  13034. auto resa = cli.Get("/a");
  13035. ASSERT_TRUE(!resa);
  13036. EXPECT_EQ(Error::Read, resa.error());
  13037. auto resb = cli.Get("/b");
  13038. ASSERT_TRUE(resb);
  13039. EXPECT_EQ(StatusCode::OK_200, resb->status);
  13040. EXPECT_EQ("b", resb->body);
  13041. }
  13042. // Closing an idle keep-alive connection sends close_notify and returns. The
  13043. // server must not wait for the client's close_notify: an idle client never
  13044. // sends one, so the worker would be held until the read timeout expires, and
  13045. // stop() would wait for it.
  13046. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  13047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13048. ASSERT_TRUE(svr.is_valid());
  13049. svr.set_keep_alive_timeout(1);
  13050. svr.set_read_timeout(10, 0);
  13051. svr.Get("/", [](const Request &, Response &res) {
  13052. res.set_content("ok", "text/plain");
  13053. });
  13054. auto port = svr.bind_to_any_port(HOST);
  13055. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  13056. auto se = detail::scope_exit([&] {
  13057. if (listen_thread.joinable()) {
  13058. svr.stop();
  13059. listen_thread.join();
  13060. }
  13061. });
  13062. svr.wait_until_ready();
  13063. SSLClient cli(HOST, port);
  13064. cli.enable_server_certificate_verification(false);
  13065. cli.set_keep_alive(true);
  13066. auto res = cli.Get("/");
  13067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13068. EXPECT_EQ(StatusCode::OK_200, res->status);
  13069. // Stay idle past the keep-alive timeout so the server closes the connection.
  13070. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13071. auto start = std::chrono::steady_clock::now();
  13072. svr.stop();
  13073. listen_thread.join();
  13074. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13075. std::chrono::steady_clock::now() - start)
  13076. .count();
  13077. EXPECT_LT(elapsed, 3000);
  13078. }
  13079. #endif
  13080. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  13081. protected:
  13082. ServerTestWithAI_PASSIVE()
  13083. : cli_(HOST, PORT)
  13084. #ifdef CPPHTTPLIB_SSL_ENABLED
  13085. ,
  13086. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13087. #endif
  13088. {
  13089. #ifdef CPPHTTPLIB_SSL_ENABLED
  13090. cli_.enable_server_certificate_verification(false);
  13091. #endif
  13092. }
  13093. virtual void SetUp() {
  13094. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  13095. res.set_content("Hello World!", "text/plain");
  13096. });
  13097. t_ = thread(
  13098. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  13099. svr_.wait_until_ready();
  13100. }
  13101. virtual void TearDown() {
  13102. svr_.stop();
  13103. t_.join();
  13104. }
  13105. #ifdef CPPHTTPLIB_SSL_ENABLED
  13106. SSLClient cli_;
  13107. SSLServer svr_;
  13108. #else
  13109. Client cli_;
  13110. Server svr_;
  13111. #endif
  13112. thread t_;
  13113. };
  13114. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  13115. auto res = cli_.Get("/hi");
  13116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13117. EXPECT_EQ(StatusCode::OK_200, res->status);
  13118. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  13119. EXPECT_EQ("Hello World!", res->body);
  13120. }
  13121. class ServerUpDownTest : public ::testing::Test {
  13122. protected:
  13123. ServerUpDownTest() : cli_(HOST, PORT) {}
  13124. virtual void SetUp() {
  13125. t_ = thread([&]() {
  13126. svr_.bind_to_any_port(HOST);
  13127. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13128. ASSERT_TRUE(svr_.listen_after_bind());
  13129. });
  13130. svr_.wait_until_ready();
  13131. }
  13132. virtual void TearDown() {
  13133. svr_.stop();
  13134. t_.join();
  13135. }
  13136. Client cli_;
  13137. Server svr_;
  13138. thread t_;
  13139. };
  13140. TEST_F(ServerUpDownTest, QuickStartStop) {
  13141. // Should not crash, especially when run with
  13142. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  13143. }
  13144. class PayloadMaxLengthTest : public ::testing::Test {
  13145. protected:
  13146. PayloadMaxLengthTest()
  13147. : cli_(HOST, PORT)
  13148. #ifdef CPPHTTPLIB_SSL_ENABLED
  13149. ,
  13150. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13151. #endif
  13152. {
  13153. #ifdef CPPHTTPLIB_SSL_ENABLED
  13154. cli_.enable_server_certificate_verification(false);
  13155. #endif
  13156. }
  13157. virtual void SetUp() {
  13158. svr_.set_payload_max_length(8);
  13159. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13160. res.set_content("test", "text/plain");
  13161. });
  13162. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13163. svr_.wait_until_ready();
  13164. }
  13165. virtual void TearDown() {
  13166. svr_.stop();
  13167. t_.join();
  13168. }
  13169. #ifdef CPPHTTPLIB_SSL_ENABLED
  13170. SSLClient cli_;
  13171. SSLServer svr_;
  13172. #else
  13173. Client cli_;
  13174. Server svr_;
  13175. #endif
  13176. thread t_;
  13177. };
  13178. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13179. auto res = cli_.Post("/test", "123456789", "text/plain");
  13180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13181. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13182. res = cli_.Post("/test", "12345678", "text/plain");
  13183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13184. EXPECT_EQ(StatusCode::OK_200, res->status);
  13185. }
  13186. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13187. // Test chunked encoding with payload exceeding the 8-byte limit
  13188. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13189. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13191. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13192. }
  13193. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13194. // Test chunked encoding with payload within the 8-byte limit
  13195. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13196. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13198. EXPECT_EQ(StatusCode::OK_200, res->status);
  13199. }
  13200. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13201. // Test using send_request to send chunked data exceeding payload limit
  13202. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13203. "Host: " +
  13204. std::string(HOST) + ":" + std::to_string(PORT) +
  13205. "\r\n"
  13206. "Transfer-Encoding: chunked\r\n"
  13207. "Connection: close\r\n"
  13208. "\r\n"
  13209. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13210. "0123456789\r\n"
  13211. "0\r\n" // End chunk
  13212. "\r\n";
  13213. std::string response;
  13214. bool result = send_request(1, chunked_request, &response);
  13215. if (!result) {
  13216. // If send_request fails, it might be because the server closed the
  13217. // connection due to payload limit enforcement, which is acceptable
  13218. SUCCEED()
  13219. << "Server rejected oversized chunked request (connection closed)";
  13220. } else {
  13221. // If we got a response, check if it's an error response or connection was
  13222. // closed early Short response length indicates connection was closed due to
  13223. // payload limit
  13224. if (response.length() <= 10) {
  13225. SUCCEED() << "Server closed connection for oversized chunked request";
  13226. } else {
  13227. // Check for error status codes
  13228. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13229. response.find("Payload Too Large") != std::string::npos ||
  13230. response.find("400") != std::string::npos);
  13231. }
  13232. }
  13233. }
  13234. class LargePayloadMaxLengthTest : public ::testing::Test {
  13235. protected:
  13236. LargePayloadMaxLengthTest()
  13237. : cli_(HOST, PORT)
  13238. #ifdef CPPHTTPLIB_SSL_ENABLED
  13239. ,
  13240. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13241. #endif
  13242. {
  13243. #ifdef CPPHTTPLIB_SSL_ENABLED
  13244. cli_.enable_server_certificate_verification(false);
  13245. #endif
  13246. }
  13247. virtual void SetUp() {
  13248. // Set 10MB payload limit
  13249. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13250. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13251. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13252. res.set_content("Large payload test", "text/plain");
  13253. });
  13254. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13255. svr_.wait_until_ready();
  13256. }
  13257. virtual void TearDown() {
  13258. svr_.stop();
  13259. t_.join();
  13260. }
  13261. #ifdef CPPHTTPLIB_SSL_ENABLED
  13262. SSLClient cli_;
  13263. SSLServer svr_;
  13264. #else
  13265. Client cli_;
  13266. Server svr_;
  13267. #endif
  13268. thread t_;
  13269. };
  13270. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13271. // Test chunked encoding with payload within 10MB limit
  13272. std::string medium_payload(5 * 1024 * 1024,
  13273. 'A'); // 5MB payload, within 10MB limit
  13274. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. EXPECT_EQ(StatusCode::OK_200, res->status);
  13277. }
  13278. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13279. // Test chunked encoding with payload exceeding 10MB limit
  13280. std::string large_payload(12 * 1024 * 1024,
  13281. 'B'); // 12MB payload, exceeds 10MB limit
  13282. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13283. // Server may either return 413 or close the connection
  13284. if (res) {
  13285. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13286. } else {
  13287. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13288. }
  13289. }
  13290. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13291. Server svr;
  13292. svr.Get("/", [](const Request &, Response &res) {
  13293. // Claims the most the client accepts, far more than it sends, then drops
  13294. // the connection.
  13295. res.set_content_provider(std::string().max_size(), "text/plain",
  13296. [](size_t, size_t, DataSink &sink) {
  13297. sink.write("abc", 3);
  13298. return false;
  13299. });
  13300. });
  13301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13302. auto se = detail::scope_exit([&] {
  13303. svr.stop();
  13304. thread.join();
  13305. ASSERT_FALSE(svr.is_running());
  13306. });
  13307. svr.wait_until_ready();
  13308. Client cli(HOST, PORT);
  13309. cli.set_payload_max_length(0);
  13310. EXPECT_FALSE(cli.Get("/"));
  13311. }
  13312. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13313. // Stream API does, not as a plain read failure
  13314. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13315. Server svr;
  13316. svr.Get("/big", [](const Request &, Response &res) {
  13317. res.set_content(std::string(100000, 'b'), "text/plain");
  13318. });
  13319. auto port = svr.bind_to_any_port(HOST);
  13320. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13321. auto se = detail::scope_exit([&] {
  13322. svr.stop();
  13323. thread.join();
  13324. });
  13325. svr.wait_until_ready();
  13326. Client cli(HOST, port);
  13327. cli.set_payload_max_length(1000);
  13328. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13329. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13330. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13331. [](const char *, size_t) { return true; });
  13332. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13333. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13334. // Small on the wire, over the limit once decompressed
  13335. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13336. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13337. #endif
  13338. }
  13339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13340. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13341. // path.
  13342. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13343. Server svr;
  13344. const size_t LIMIT = 64 * 1024; // 64KB
  13345. svr.set_payload_max_length(LIMIT);
  13346. size_t total = 0;
  13347. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13348. const ContentReader &content_reader) {
  13349. content_reader([&](const char * /*data*/, size_t len) {
  13350. total += len;
  13351. return true;
  13352. });
  13353. res.status = 200;
  13354. res.set_content("stream_ok", "text/plain");
  13355. });
  13356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. thread.join();
  13360. ASSERT_FALSE(svr.is_running());
  13361. });
  13362. svr.wait_until_ready();
  13363. // Prepare 256KB raw data and gzip-compress it
  13364. std::string raw(256 * 1024, 'A');
  13365. std::string gz;
  13366. {
  13367. z_stream zs{};
  13368. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13369. Z_DEFAULT_STRATEGY);
  13370. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13371. zs.avail_in = static_cast<uInt>(raw.size());
  13372. char outbuf[4096];
  13373. int ret;
  13374. do {
  13375. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13376. zs.avail_out = sizeof(outbuf);
  13377. ret = deflate(&zs, Z_FINISH);
  13378. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13379. } while (ret != Z_STREAM_END);
  13380. deflateEnd(&zs);
  13381. }
  13382. Client cli(HOST, PORT);
  13383. cli.set_connection_timeout(std::chrono::seconds(5));
  13384. Headers headers = {{"Content-Encoding", "gzip"}};
  13385. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13386. "application/octet-stream");
  13387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13388. // Server must reject oversized decompressed payloads with 413.
  13389. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13390. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13391. EXPECT_LE(total, LIMIT);
  13392. }
  13393. #endif
  13394. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13395. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13396. // the payload must be passed through untouched instead of being rejected.
  13397. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13398. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13399. Server svr;
  13400. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13401. res.set_content(body, "image/jpeg");
  13402. res.set_header("Content-Encoding", "UTF-8");
  13403. });
  13404. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13405. res.set_content(body, "image/jpeg");
  13406. res.set_header("Content-Encoding", "identity");
  13407. });
  13408. svr.Post("/echo", [](const Request &req, Response &res) {
  13409. res.set_content(req.body, "image/jpeg");
  13410. });
  13411. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13412. auto se = detail::scope_exit([&] {
  13413. svr.stop();
  13414. t.join();
  13415. ASSERT_FALSE(svr.is_running());
  13416. });
  13417. svr.wait_until_ready();
  13418. Client cli(HOST, PORT);
  13419. {
  13420. auto res = cli.Get("/image");
  13421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13422. EXPECT_EQ(StatusCode::OK_200, res->status);
  13423. EXPECT_EQ(body, res->body);
  13424. }
  13425. {
  13426. auto res = cli.Get("/identity");
  13427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13428. EXPECT_EQ(StatusCode::OK_200, res->status);
  13429. EXPECT_EQ(body, res->body);
  13430. }
  13431. {
  13432. // The same applies to a request body reaching the server.
  13433. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13434. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. EXPECT_EQ(StatusCode::OK_200, res->status);
  13437. EXPECT_EQ(body, res->body);
  13438. }
  13439. }
  13440. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13441. // gzip-encoded response even when the build has no zlib support.
  13442. static const char GZIPPED_HELLO_WORLD[] = {
  13443. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13444. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13445. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13446. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13447. // A content coding is a whole token, not something the field value merely
  13448. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13449. // as "fibre" look like Brotli, and turned a multi-coding value like
  13450. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13451. // it was never meant to see.
  13452. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13453. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13454. Server svr;
  13455. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13456. res.set_content(body, "image/jpeg");
  13457. res.set_header("Content-Encoding", "fibre");
  13458. });
  13459. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13460. res.set_content(body, "image/jpeg");
  13461. res.set_header("Content-Encoding", "gzip, br");
  13462. });
  13463. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13464. res.set_content(body, "image/jpeg");
  13465. res.set_header("Content-Encoding", "x-zstd-ish");
  13466. });
  13467. auto port = svr.bind_to_any_port(HOST);
  13468. thread t = thread([&]() { svr.listen_after_bind(); });
  13469. auto se = detail::scope_exit([&] {
  13470. svr.stop();
  13471. t.join();
  13472. ASSERT_FALSE(svr.is_running());
  13473. });
  13474. svr.wait_until_ready();
  13475. Client cli(HOST, port);
  13476. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13477. auto res = cli.Get(path);
  13478. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13479. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13480. // Not a coding we recognize, so the payload comes back untouched
  13481. EXPECT_EQ(body, res->body) << path;
  13482. }
  13483. }
  13484. // A content coding cpp-httplib recognizes but was not built with must be
  13485. // reported as such. Handing the still-compressed payload back to the caller
  13486. // would silently corrupt it.
  13487. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13488. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13489. Server svr;
  13490. // "image/jpeg" keeps the server from applying a content coding of its own,
  13491. // so the hand-crafted Content-Encoding below survives.
  13492. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13493. res.set_content(gzipped, "image/jpeg");
  13494. res.set_header("Content-Encoding", "gzip");
  13495. });
  13496. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13497. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13498. res.set_content(gzipped, "image/jpeg");
  13499. res.set_header("Content-Encoding", "GZIP");
  13500. });
  13501. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13502. auto se = detail::scope_exit([&] {
  13503. svr.stop();
  13504. t.join();
  13505. ASSERT_FALSE(svr.is_running());
  13506. });
  13507. svr.wait_until_ready();
  13508. Client cli(HOST, PORT);
  13509. {
  13510. auto res = cli.Get("/gzipped");
  13511. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13513. EXPECT_EQ("Hello World!", res->body);
  13514. #else
  13515. ASSERT_FALSE(res);
  13516. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13517. #endif
  13518. }
  13519. {
  13520. // open_stream() must behave the same way.
  13521. auto handle = cli.open_stream("GET", "/gzipped");
  13522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13523. ASSERT_TRUE(handle.is_valid());
  13524. std::string received;
  13525. char buf[256];
  13526. ssize_t n;
  13527. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13528. received.append(buf, static_cast<size_t>(n));
  13529. }
  13530. EXPECT_EQ("Hello World!", received);
  13531. #else
  13532. EXPECT_FALSE(handle.is_valid());
  13533. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13534. #endif
  13535. }
  13536. {
  13537. // A differently-cased coding must not be mistaken for an unknown one, or
  13538. // the body would be handed back still compressed.
  13539. auto res = cli.Get("/gzipped-uppercase");
  13540. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13542. EXPECT_EQ("Hello World!", res->body);
  13543. #else
  13544. ASSERT_FALSE(res);
  13545. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13546. #endif
  13547. }
  13548. }
  13549. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13550. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13551. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13552. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13553. // body a second time and appending a second Content-Encoding field line, so
  13554. // clients that decode one coding per listed value handed back raw gzip bytes.
  13555. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13556. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13557. Server svr;
  13558. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13559. // keeps the server from applying a coding of its own.
  13560. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13561. res.set_content(gzipped, "text/plain");
  13562. res.set_header("Content-Encoding", "gzip");
  13563. });
  13564. auto port = svr.bind_to_any_port(HOST);
  13565. thread t = thread([&]() { svr.listen_after_bind(); });
  13566. auto se = detail::scope_exit([&] {
  13567. svr.stop();
  13568. t.join();
  13569. ASSERT_FALSE(svr.is_running());
  13570. });
  13571. svr.wait_until_ready();
  13572. Client cli(HOST, port);
  13573. Headers headers = {{"Accept-Encoding", "gzip"}};
  13574. auto res = cli.Get("/pre-gzipped", headers);
  13575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13576. EXPECT_EQ(StatusCode::OK_200, res->status);
  13577. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13578. EXPECT_EQ("Hello World!", res->body);
  13579. }
  13580. // set_compress(false) sends every handler response as it is, buffered or
  13581. // streamed
  13582. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13583. const std::string text(1000, 'a');
  13584. Server svr;
  13585. svr.set_compress(false);
  13586. svr.Get("/buffered", [&](const Request &, Response &res) {
  13587. res.set_content(text, "text/plain");
  13588. });
  13589. svr.Get("/streamed", [&](const Request &, Response &res) {
  13590. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13591. sink.write(text.data(), text.size());
  13592. sink.done();
  13593. return true;
  13594. });
  13595. });
  13596. auto port = svr.bind_to_any_port(HOST);
  13597. ASSERT_LT(0, port);
  13598. thread t = thread([&] { svr.listen_after_bind(); });
  13599. auto se = detail::scope_exit([&] {
  13600. svr.stop();
  13601. t.join();
  13602. ASSERT_FALSE(svr.is_running());
  13603. });
  13604. svr.wait_until_ready();
  13605. Client cli(HOST, port);
  13606. cli.set_decompress(false);
  13607. for (auto path : {"/buffered", "/streamed"}) {
  13608. SCOPED_TRACE(path);
  13609. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13611. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13612. EXPECT_EQ(text, res->body);
  13613. }
  13614. }
  13615. // A chunked provider settles its coding where the headers are written and
  13616. // reuses it at write time. Both ends of that have to hold: a handler's own
  13617. // Content-Encoding suppresses the coding, and a response without one is still
  13618. // compressed as it always was.
  13619. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13620. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13621. const std::string plain = "Hello World! Hello World! Hello World!";
  13622. Server svr;
  13623. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13624. res.set_header("Content-Encoding", "gzip");
  13625. res.set_chunked_content_provider(
  13626. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13627. sink.write(gzipped.data(), gzipped.size());
  13628. sink.done();
  13629. return true;
  13630. });
  13631. });
  13632. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13633. res.set_chunked_content_provider(
  13634. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13635. sink.write(plain.data(), plain.size());
  13636. sink.done();
  13637. return true;
  13638. });
  13639. });
  13640. auto port = svr.bind_to_any_port(HOST);
  13641. thread t = thread([&]() { svr.listen_after_bind(); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. });
  13647. svr.wait_until_ready();
  13648. Client cli(HOST, port);
  13649. Headers headers = {{"Accept-Encoding", "gzip"}};
  13650. {
  13651. auto res = cli.Get("/pre-gzipped", headers);
  13652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13653. EXPECT_EQ(StatusCode::OK_200, res->status);
  13654. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13655. EXPECT_EQ("Hello World!", res->body);
  13656. }
  13657. {
  13658. auto res = cli.Get("/negotiated", headers);
  13659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13660. EXPECT_EQ(StatusCode::OK_200, res->status);
  13661. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13662. EXPECT_EQ(plain, res->body);
  13663. }
  13664. }
  13665. #endif
  13666. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13667. // the same message as the comma-joined one, so both have to be read the same
  13668. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13669. // single gzip coding, and a body the sender says was encoded twice was handed
  13670. // back after one pass, still compressed but presented as decoded.
  13671. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13672. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13673. Server svr;
  13674. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13675. res.set_content(body, "image/jpeg");
  13676. res.headers.emplace("Content-Encoding", "gzip");
  13677. res.headers.emplace("Content-Encoding", "gzip");
  13678. });
  13679. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13680. res.set_content(body, "image/jpeg");
  13681. res.set_header("Content-Encoding", "gzip, gzip");
  13682. });
  13683. auto port = svr.bind_to_any_port(HOST);
  13684. thread t = thread([&]() { svr.listen_after_bind(); });
  13685. auto se = detail::scope_exit([&] {
  13686. svr.stop();
  13687. t.join();
  13688. ASSERT_FALSE(svr.is_running());
  13689. });
  13690. svr.wait_until_ready();
  13691. Client cli(HOST, port);
  13692. // Two codings is not something cpp-httplib decodes, so both representations
  13693. // take the pass-through path rather than one of them being gunzipped once.
  13694. for (const char *path : {"/split", "/joined"}) {
  13695. auto res = cli.Get(path);
  13696. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13697. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13698. EXPECT_EQ(body, res->body) << path;
  13699. }
  13700. }
  13701. // Regression test for DoS vulnerability: a malicious server sending a response
  13702. // without Content-Length header must not cause unbounded memory consumption on
  13703. // the client side. The client should stop reading after a reasonable limit,
  13704. // similar to the server-side set_payload_max_length protection.
  13705. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13706. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13707. #ifndef _WIN32
  13708. signal(SIGPIPE, SIG_IGN);
  13709. #endif
  13710. auto server_thread = std::thread([] {
  13711. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13713. default_socket_options(srv);
  13714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13716. sockaddr_in addr{};
  13717. addr.sin_family = AF_INET;
  13718. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13720. int opt = 1;
  13721. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13722. #ifdef _WIN32
  13723. reinterpret_cast<const char *>(&opt),
  13724. #else
  13725. &opt,
  13726. #endif
  13727. sizeof(opt));
  13728. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13729. ::listen(srv, 1);
  13730. sockaddr_in cli_addr{};
  13731. socklen_t cli_len = sizeof(cli_addr);
  13732. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13733. if (cli != INVALID_SOCKET) {
  13734. char buf[4096];
  13735. ::recv(cli, buf, sizeof(buf), 0);
  13736. // Malicious response: no Content-Length, no chunked encoding
  13737. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13738. "Connection: close\r\n"
  13739. "\r\n";
  13740. ::send(cli,
  13741. #ifdef _WIN32
  13742. static_cast<const char *>(response_header.c_str()),
  13743. static_cast<int>(response_header.size()),
  13744. #else
  13745. response_header.c_str(), response_header.size(),
  13746. #endif
  13747. 0);
  13748. // Send 10MB of data
  13749. std::string chunk(64 * 1024, 'A');
  13750. size_t total_sent = 0;
  13751. while (total_sent < MALICIOUS_DATA_SIZE) {
  13752. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13753. auto sent = ::send(cli,
  13754. #ifdef _WIN32
  13755. static_cast<const char *>(chunk.c_str()),
  13756. static_cast<int>(to_send),
  13757. #else
  13758. chunk.c_str(), to_send,
  13759. #endif
  13760. 0);
  13761. if (sent <= 0) break;
  13762. total_sent += static_cast<size_t>(sent);
  13763. }
  13764. detail::close_socket(cli);
  13765. }
  13766. detail::close_socket(srv);
  13767. });
  13768. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13769. size_t total_read = 0;
  13770. {
  13771. Client cli("127.0.0.1", PORT + 2);
  13772. cli.set_read_timeout(5, 0);
  13773. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13774. auto stream = cli.open_stream("GET", "/malicious");
  13775. ASSERT_TRUE(stream.is_valid());
  13776. char buffer[64 * 1024];
  13777. ssize_t n;
  13778. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13779. total_read += static_cast<size_t>(n);
  13780. }
  13781. } // StreamHandle and Client destroyed here, closing the socket
  13782. server_thread.join();
  13783. // With set_payload_max_length, the client must stop reading before consuming
  13784. // all 10MB. The read loop should be cut off at or near the configured limit.
  13785. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13786. << "Client read " << total_read << " bytes, exceeding the configured "
  13787. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13788. }
  13789. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13790. // the entire response body without truncation.
  13791. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13792. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13793. #ifndef _WIN32
  13794. signal(SIGPIPE, SIG_IGN);
  13795. #endif
  13796. auto server_thread = std::thread([] {
  13797. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13798. default_socket_options(srv);
  13799. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13800. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13801. sockaddr_in addr{};
  13802. addr.sin_family = AF_INET;
  13803. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13804. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13805. int opt = 1;
  13806. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13807. #ifdef _WIN32
  13808. reinterpret_cast<const char *>(&opt),
  13809. #else
  13810. &opt,
  13811. #endif
  13812. sizeof(opt));
  13813. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13814. ::listen(srv, 1);
  13815. sockaddr_in cli_addr{};
  13816. socklen_t cli_len = sizeof(cli_addr);
  13817. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13818. if (cli != INVALID_SOCKET) {
  13819. char buf[4096];
  13820. ::recv(cli, buf, sizeof(buf), 0);
  13821. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13822. "Connection: close\r\n"
  13823. "\r\n";
  13824. ::send(cli,
  13825. #ifdef _WIN32
  13826. static_cast<const char *>(response_header.c_str()),
  13827. static_cast<int>(response_header.size()),
  13828. #else
  13829. response_header.c_str(), response_header.size(),
  13830. #endif
  13831. 0);
  13832. std::string chunk(64 * 1024, 'A');
  13833. size_t total_sent = 0;
  13834. while (total_sent < DATA_SIZE) {
  13835. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13836. auto sent = ::send(cli,
  13837. #ifdef _WIN32
  13838. static_cast<const char *>(chunk.c_str()),
  13839. static_cast<int>(to_send),
  13840. #else
  13841. chunk.c_str(), to_send,
  13842. #endif
  13843. 0);
  13844. if (sent <= 0) break;
  13845. total_sent += static_cast<size_t>(sent);
  13846. }
  13847. #ifdef _WIN32
  13848. ::shutdown(cli, SD_SEND);
  13849. #else
  13850. ::shutdown(cli, SHUT_WR);
  13851. #endif
  13852. // Drain until the client closes its end, ensuring all data is delivered
  13853. char drain[1024];
  13854. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13855. detail::close_socket(cli);
  13856. }
  13857. detail::close_socket(srv);
  13858. });
  13859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13860. size_t total_read = 0;
  13861. {
  13862. Client cli("127.0.0.1", PORT + 2);
  13863. cli.set_read_timeout(5, 0);
  13864. cli.set_payload_max_length(0); // 0 means no limit
  13865. auto stream = cli.open_stream("GET", "/data");
  13866. ASSERT_TRUE(stream.is_valid());
  13867. char buffer[64 * 1024];
  13868. ssize_t n;
  13869. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13870. total_read += static_cast<size_t>(n);
  13871. }
  13872. }
  13873. server_thread.join();
  13874. EXPECT_EQ(total_read, DATA_SIZE)
  13875. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13876. << " bytes without truncation, but only read " << total_read << " bytes.";
  13877. }
  13878. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13879. // enormous Content-Length must not cause the client to pre-allocate a huge
  13880. // response body buffer. The reservation is capped at payload_max_length_, and
  13881. // the read itself fails when the body exceeds the limit.
  13882. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13883. #ifndef _WIN32
  13884. signal(SIGPIPE, SIG_IGN);
  13885. #endif
  13886. auto server_thread = std::thread([] {
  13887. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13888. default_socket_options(srv);
  13889. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13890. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13891. sockaddr_in addr{};
  13892. addr.sin_family = AF_INET;
  13893. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13894. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13895. int opt = 1;
  13896. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13897. #ifdef _WIN32
  13898. reinterpret_cast<const char *>(&opt),
  13899. #else
  13900. &opt,
  13901. #endif
  13902. sizeof(opt));
  13903. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13904. ::listen(srv, 1);
  13905. sockaddr_in cli_addr{};
  13906. socklen_t cli_len = sizeof(cli_addr);
  13907. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13908. if (cli != INVALID_SOCKET) {
  13909. char buf[4096];
  13910. ::recv(cli, buf, sizeof(buf), 0);
  13911. // Malicious response: claim a 20GB body but send only a tiny payload.
  13912. std::string response = "HTTP/1.1 200 OK\r\n"
  13913. "Content-Length: 20000000000\r\n"
  13914. "\r\n"
  13915. "abc";
  13916. ::send(cli,
  13917. #ifdef _WIN32
  13918. static_cast<const char *>(response.c_str()),
  13919. static_cast<int>(response.size()),
  13920. #else
  13921. response.c_str(), response.size(),
  13922. #endif
  13923. 0);
  13924. detail::close_socket(cli);
  13925. }
  13926. detail::close_socket(srv);
  13927. });
  13928. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13929. {
  13930. Client cli("127.0.0.1", PORT + 2);
  13931. cli.set_read_timeout(5, 0);
  13932. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13933. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13934. // (server claims more bytes than payload_max_length permits), but it must
  13935. // not exhaust memory before getting there.
  13936. auto res = cli.Get("/malicious");
  13937. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13938. }
  13939. server_thread.join();
  13940. }
  13941. // Verify that content_receiver bypasses the default payload_max_length,
  13942. // allowing streaming downloads larger than 100MB without requiring an explicit
  13943. // set_payload_max_length call.
  13944. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13945. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13946. #ifndef _WIN32
  13947. signal(SIGPIPE, SIG_IGN);
  13948. #endif
  13949. auto server_thread = std::thread([] {
  13950. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13951. default_socket_options(srv);
  13952. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13954. sockaddr_in addr{};
  13955. addr.sin_family = AF_INET;
  13956. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13957. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13958. int opt = 1;
  13959. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13960. #ifdef _WIN32
  13961. reinterpret_cast<const char *>(&opt),
  13962. #else
  13963. &opt,
  13964. #endif
  13965. sizeof(opt));
  13966. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13967. ::listen(srv, 1);
  13968. sockaddr_in cli_addr{};
  13969. socklen_t cli_len = sizeof(cli_addr);
  13970. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13971. if (cli != INVALID_SOCKET) {
  13972. char buf[4096];
  13973. ::recv(cli, buf, sizeof(buf), 0);
  13974. // Response with Content-Length larger than default 100MB limit
  13975. auto content_length = std::to_string(DATA_SIZE);
  13976. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13977. "Content-Length: " +
  13978. content_length +
  13979. "\r\n"
  13980. "Connection: close\r\n"
  13981. "\r\n";
  13982. ::send(cli,
  13983. #ifdef _WIN32
  13984. static_cast<const char *>(response_header.c_str()),
  13985. static_cast<int>(response_header.size()),
  13986. #else
  13987. response_header.c_str(), response_header.size(),
  13988. #endif
  13989. 0);
  13990. std::string chunk(64 * 1024, 'A');
  13991. size_t total_sent = 0;
  13992. while (total_sent < DATA_SIZE) {
  13993. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13994. auto sent = ::send(cli,
  13995. #ifdef _WIN32
  13996. static_cast<const char *>(chunk.c_str()),
  13997. static_cast<int>(to_send),
  13998. #else
  13999. chunk.c_str(), to_send,
  14000. #endif
  14001. 0);
  14002. if (sent <= 0) break;
  14003. total_sent += static_cast<size_t>(sent);
  14004. }
  14005. detail::close_socket(cli);
  14006. }
  14007. detail::close_socket(srv);
  14008. });
  14009. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14010. size_t total_received = 0;
  14011. {
  14012. Client cli("127.0.0.1", PORT + 2);
  14013. cli.set_read_timeout(10, 0);
  14014. // Do NOT call set_payload_max_length — use the default 100MB limit
  14015. auto res =
  14016. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14017. total_received += data_length;
  14018. return true;
  14019. });
  14020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14021. EXPECT_EQ(StatusCode::OK_200, res->status);
  14022. }
  14023. server_thread.join();
  14024. EXPECT_EQ(total_received, DATA_SIZE)
  14025. << "With content_receiver, the client should read all " << DATA_SIZE
  14026. << " bytes despite the default 100MB payload_max_length, but only read "
  14027. << total_received << " bytes.";
  14028. }
  14029. // Verify that an explicit set_payload_max_length smaller than the response is
  14030. // enforced even when a content_receiver is used.
  14031. TEST(ClientVulnerabilityTest,
  14032. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  14033. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14034. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  14035. #ifndef _WIN32
  14036. signal(SIGPIPE, SIG_IGN);
  14037. #endif
  14038. auto server_thread = std::thread([] {
  14039. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14040. default_socket_options(srv);
  14041. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14042. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14043. sockaddr_in addr{};
  14044. addr.sin_family = AF_INET;
  14045. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14046. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14047. int opt = 1;
  14048. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14049. #ifdef _WIN32
  14050. reinterpret_cast<const char *>(&opt),
  14051. #else
  14052. &opt,
  14053. #endif
  14054. sizeof(opt));
  14055. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14056. ::listen(srv, 1);
  14057. sockaddr_in cli_addr{};
  14058. socklen_t cli_len = sizeof(cli_addr);
  14059. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14060. if (cli != INVALID_SOCKET) {
  14061. char buf[4096];
  14062. ::recv(cli, buf, sizeof(buf), 0);
  14063. auto content_length = std::to_string(DATA_SIZE);
  14064. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14065. "Content-Length: " +
  14066. content_length +
  14067. "\r\n"
  14068. "Connection: close\r\n"
  14069. "\r\n";
  14070. ::send(cli,
  14071. #ifdef _WIN32
  14072. static_cast<const char *>(response_header.c_str()),
  14073. static_cast<int>(response_header.size()),
  14074. #else
  14075. response_header.c_str(), response_header.size(),
  14076. #endif
  14077. 0);
  14078. std::string chunk(64 * 1024, 'A');
  14079. size_t total_sent = 0;
  14080. while (total_sent < DATA_SIZE) {
  14081. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14082. auto sent = ::send(cli,
  14083. #ifdef _WIN32
  14084. static_cast<const char *>(chunk.c_str()),
  14085. static_cast<int>(to_send),
  14086. #else
  14087. chunk.c_str(), to_send,
  14088. #endif
  14089. 0);
  14090. if (sent <= 0) break;
  14091. total_sent += static_cast<size_t>(sent);
  14092. }
  14093. detail::close_socket(cli);
  14094. }
  14095. detail::close_socket(srv);
  14096. });
  14097. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14098. size_t total_received = 0;
  14099. {
  14100. Client cli("127.0.0.1", PORT + 2);
  14101. cli.set_read_timeout(10, 0);
  14102. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  14103. auto res =
  14104. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14105. total_received += data_length;
  14106. return true;
  14107. });
  14108. // Should fail because 200MB exceeds the explicit 150MB limit
  14109. EXPECT_FALSE(res);
  14110. }
  14111. server_thread.join();
  14112. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  14113. << "Client with content_receiver should respect the explicit "
  14114. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  14115. << total_received << " bytes.";
  14116. }
  14117. // Verify that an explicit set_payload_max_length larger than the response
  14118. // allows the content_receiver to read all data successfully.
  14119. TEST(ClientVulnerabilityTest,
  14120. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  14121. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14122. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  14123. #ifndef _WIN32
  14124. signal(SIGPIPE, SIG_IGN);
  14125. #endif
  14126. auto server_thread = std::thread([] {
  14127. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14128. default_socket_options(srv);
  14129. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14130. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14131. sockaddr_in addr{};
  14132. addr.sin_family = AF_INET;
  14133. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14134. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14135. int opt = 1;
  14136. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14137. #ifdef _WIN32
  14138. reinterpret_cast<const char *>(&opt),
  14139. #else
  14140. &opt,
  14141. #endif
  14142. sizeof(opt));
  14143. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14144. ::listen(srv, 1);
  14145. sockaddr_in cli_addr{};
  14146. socklen_t cli_len = sizeof(cli_addr);
  14147. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14148. if (cli != INVALID_SOCKET) {
  14149. char buf[4096];
  14150. ::recv(cli, buf, sizeof(buf), 0);
  14151. auto content_length = std::to_string(DATA_SIZE);
  14152. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14153. "Content-Length: " +
  14154. content_length +
  14155. "\r\n"
  14156. "Connection: close\r\n"
  14157. "\r\n";
  14158. ::send(cli,
  14159. #ifdef _WIN32
  14160. static_cast<const char *>(response_header.c_str()),
  14161. static_cast<int>(response_header.size()),
  14162. #else
  14163. response_header.c_str(), response_header.size(),
  14164. #endif
  14165. 0);
  14166. std::string chunk(64 * 1024, 'A');
  14167. size_t total_sent = 0;
  14168. while (total_sent < DATA_SIZE) {
  14169. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14170. auto sent = ::send(cli,
  14171. #ifdef _WIN32
  14172. static_cast<const char *>(chunk.c_str()),
  14173. static_cast<int>(to_send),
  14174. #else
  14175. chunk.c_str(), to_send,
  14176. #endif
  14177. 0);
  14178. if (sent <= 0) break;
  14179. total_sent += static_cast<size_t>(sent);
  14180. }
  14181. #ifdef _WIN32
  14182. ::shutdown(cli, SD_SEND);
  14183. #else
  14184. ::shutdown(cli, SHUT_WR);
  14185. #endif
  14186. char drain[1024];
  14187. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14188. detail::close_socket(cli);
  14189. }
  14190. detail::close_socket(srv);
  14191. });
  14192. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14193. size_t total_received = 0;
  14194. {
  14195. Client cli("127.0.0.1", PORT + 2);
  14196. cli.set_read_timeout(10, 0);
  14197. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14198. auto res =
  14199. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14200. total_received += data_length;
  14201. return true;
  14202. });
  14203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14204. EXPECT_EQ(StatusCode::OK_200, res->status);
  14205. }
  14206. server_thread.join();
  14207. EXPECT_EQ(total_received, DATA_SIZE)
  14208. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14209. << " bytes (larger than " << DATA_SIZE
  14210. << " bytes response), content_receiver should read all data, but only "
  14211. "read "
  14212. << total_received << " bytes.";
  14213. }
  14214. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14215. // Regression test for "zip bomb" attack on the client side: a malicious server
  14216. // sends a small gzip-compressed response that decompresses to a huge payload.
  14217. // The client must enforce payload_max_length on the decompressed size.
  14218. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14219. constexpr size_t DECOMPRESSED_SIZE =
  14220. 10 * 1024 * 1024; // 10MB after decompression
  14221. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14222. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14223. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14224. std::string compressed;
  14225. {
  14226. httplib::detail::gzip_compressor compressor;
  14227. bool ok =
  14228. compressor.compress(uncompressed.data(), uncompressed.size(),
  14229. /*last=*/true, [&](const char *buf, size_t len) {
  14230. compressed.append(buf, len);
  14231. return true;
  14232. });
  14233. ASSERT_TRUE(ok);
  14234. }
  14235. // Sanity: compressed data should be much smaller than the decompressed size
  14236. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14237. #ifndef _WIN32
  14238. signal(SIGPIPE, SIG_IGN);
  14239. #endif
  14240. // Set up the listening socket in the main thread so the server is guaranteed
  14241. // to be ready before the client connects (eliminates race condition).
  14242. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14243. default_socket_options(srv);
  14244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14245. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14246. sockaddr_in addr{};
  14247. addr.sin_family = AF_INET;
  14248. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14249. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14250. int opt = 1;
  14251. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14252. #ifdef _WIN32
  14253. reinterpret_cast<const char *>(&opt),
  14254. #else
  14255. &opt,
  14256. #endif
  14257. sizeof(opt));
  14258. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14259. ASSERT_EQ(0, ::listen(srv, 1));
  14260. auto server_thread = std::thread([&compressed, srv] {
  14261. sockaddr_in cli_addr{};
  14262. socklen_t cli_len = sizeof(cli_addr);
  14263. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14264. if (cli != INVALID_SOCKET) {
  14265. // Read the full HTTP request (until \r\n\r\n)
  14266. char buf[4096];
  14267. size_t total = 0;
  14268. while (total < sizeof(buf)) {
  14269. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14270. if (n <= 0) break;
  14271. total += static_cast<size_t>(n);
  14272. // Check for end of headers
  14273. if (total >= 4) {
  14274. std::string req(buf, total);
  14275. if (req.find("\r\n\r\n") != std::string::npos) break;
  14276. }
  14277. }
  14278. // Malicious response: gzip-compressed body, no Content-Length
  14279. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14280. "Content-Encoding: gzip\r\n"
  14281. "Connection: close\r\n"
  14282. "\r\n";
  14283. ::send(cli,
  14284. #ifdef _WIN32
  14285. static_cast<const char *>(response_header.c_str()),
  14286. static_cast<int>(response_header.size()),
  14287. #else
  14288. response_header.c_str(), response_header.size(),
  14289. #endif
  14290. 0);
  14291. // Send the compressed payload (small on the wire, huge when decompressed)
  14292. size_t total_sent = 0;
  14293. while (total_sent < compressed.size()) {
  14294. auto to_send = std::min(compressed.size() - total_sent,
  14295. static_cast<size_t>(64 * 1024));
  14296. auto sent =
  14297. ::send(cli,
  14298. #ifdef _WIN32
  14299. static_cast<const char *>(compressed.c_str() + total_sent),
  14300. static_cast<int>(to_send),
  14301. #else
  14302. compressed.c_str() + total_sent, to_send,
  14303. #endif
  14304. 0);
  14305. if (sent <= 0) break;
  14306. total_sent += static_cast<size_t>(sent);
  14307. }
  14308. detail::close_socket(cli);
  14309. }
  14310. });
  14311. auto se = detail::scope_exit([&] {
  14312. detail::close_socket(srv);
  14313. server_thread.join();
  14314. });
  14315. size_t total_decompressed = 0;
  14316. {
  14317. Client cli("127.0.0.1", PORT + 3);
  14318. cli.set_read_timeout(5, 0);
  14319. cli.set_decompress(true);
  14320. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14321. auto stream = cli.open_stream("GET", "/zipbomb");
  14322. ASSERT_TRUE(stream.is_valid());
  14323. char buffer[64 * 1024];
  14324. ssize_t n;
  14325. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14326. total_decompressed += static_cast<size_t>(n);
  14327. }
  14328. }
  14329. // The decompressed size must be capped by payload_max_length. Without
  14330. // protection, the client would decompress the full 10MB from a tiny
  14331. // compressed payload, enabling a zip bomb DoS attack.
  14332. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14333. << "Client decompressed " << total_decompressed
  14334. << " bytes from a gzip response. The decompressed size should be "
  14335. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14336. }
  14337. #endif
  14338. TEST(HostAndPortPropertiesTest, NoSSL) {
  14339. httplib::Client cli("www.google.com", 1234);
  14340. ASSERT_EQ("www.google.com", cli.host());
  14341. ASSERT_EQ(1234, cli.port());
  14342. }
  14343. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14344. httplib::Client cli("www.google.com:1234");
  14345. ASSERT_EQ("www.google.com", cli.host());
  14346. ASSERT_EQ(1234, cli.port());
  14347. }
  14348. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14349. // Port number that overflows int — should not crash, client becomes invalid
  14350. httplib::Client cli("http://www.google.com:99999999999999999999");
  14351. ASSERT_FALSE(cli.is_valid());
  14352. }
  14353. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14354. // Port 99999 exceeds valid range (1-65535) — should not crash
  14355. httplib::Client cli("http://www.google.com:99999");
  14356. ASSERT_FALSE(cli.is_valid());
  14357. auto res = cli.Get("/");
  14358. EXPECT_FALSE(res);
  14359. EXPECT_EQ(Error::Connection, res.error());
  14360. }
  14361. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14362. httplib::Client cli("http://user:pass@localhost:1234");
  14363. ASSERT_FALSE(cli.is_valid());
  14364. EXPECT_FALSE(cli.Get("/"));
  14365. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14366. }
  14367. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14368. httplib::Client cli("http://www.google.com:80abc");
  14369. ASSERT_FALSE(cli.is_valid());
  14370. }
  14371. #ifdef CPPHTTPLIB_SSL_ENABLED
  14372. TEST(HostAndPortPropertiesTest, SSL) {
  14373. httplib::SSLClient cli("www.google.com");
  14374. ASSERT_EQ("www.google.com", cli.host());
  14375. ASSERT_EQ(443, cli.port());
  14376. }
  14377. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14378. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14379. std::string cert;
  14380. read_file(CA_CERT_FILE, cert);
  14381. httplib::SSLClient httplib_client("www.google.com");
  14382. // Load CA store first time
  14383. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14384. // Load CA store second time (update)
  14385. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14386. // Verify client is still valid and can make connections
  14387. httplib_client.enable_server_certificate_verification(true);
  14388. auto res = httplib_client.Get("/");
  14389. // Any status: Google may redirect or rate-limit CI runners.
  14390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14391. }
  14392. TEST(SSLClientTest, ServerNameIndication_Online) {
  14393. auto host = "httpbingo.org";
  14394. auto path = std::string{"/get"};
  14395. SSLClient cli(host, 443);
  14396. auto res = retry_service_failures([&] { return cli.Get(path); });
  14397. SKIP_ON_SERVICE_FAILURE(res);
  14398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14399. ASSERT_EQ(StatusCode::OK_200, res->status);
  14400. }
  14401. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14402. // Use a site that will cause SSL verification failure due to self-signed cert
  14403. SSLClient cli("self-signed.badssl.com", 443);
  14404. cli.enable_server_certificate_verification(true);
  14405. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14406. SKIP_ON_SERVICE_FAILURE(res);
  14407. ASSERT_TRUE(!res);
  14408. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14409. // Verify backend error is captured for SSLServerVerification
  14410. // This occurs when certificate verification fails
  14411. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14412. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14413. EXPECT_NE(0UL, res.ssl_backend_error());
  14414. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14415. res.ssl_error());
  14416. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14417. #if !defined(_WIN32) || \
  14418. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14419. // On non-Windows or when Windows Schannel is disabled, the error comes
  14420. // from OpenSSL's verification
  14421. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14422. res.ssl_backend_error());
  14423. #endif
  14424. #endif
  14425. }
  14426. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14427. // Use a site where hostname doesn't match the certificate
  14428. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14429. SSLClient cli("wrong.host.badssl.com", 443);
  14430. cli.enable_server_certificate_verification(true);
  14431. cli.enable_server_hostname_verification(true);
  14432. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14433. SKIP_ON_SERVICE_FAILURE(res);
  14434. ASSERT_TRUE(!res);
  14435. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14436. // Verify backend error is captured for hostname verification failure
  14437. EXPECT_NE(0UL, res.ssl_backend_error());
  14438. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14439. res.ssl_error());
  14440. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14441. #if !defined(_WIN32) || \
  14442. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14443. // On non-Windows or when Windows Schannel is disabled, the error comes
  14444. // from OpenSSL's hostname verification
  14445. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14446. res.ssl_backend_error());
  14447. #endif
  14448. #endif
  14449. }
  14450. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14451. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14452. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14453. SSLClient cli("www.google.com", 443);
  14454. cli.enable_server_certificate_verification(true);
  14455. auto res = cli.Get("/");
  14456. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14457. }
  14458. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14459. SSLClient cli("www.google.com", 443);
  14460. cli.enable_server_certificate_verification(true);
  14461. cli.enable_windows_certificate_verification(false);
  14462. auto res = cli.Get("/");
  14463. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14464. }
  14465. // The server sends an intermediate cross-signed by a root Windows trusts,
  14466. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14467. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14468. SSLClient cli("accounts.spotify.com", 443);
  14469. auto res = cli.Get("/");
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14471. << " ssl_backend_error=" << res.ssl_backend_error();
  14472. }
  14473. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14474. // policy status, which no backend reports for a self-signed certificate.
  14475. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14476. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14477. ASSERT_TRUE(svr.is_valid());
  14478. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14479. auto se = detail::scope_exit([&] {
  14480. svr.stop();
  14481. t.join();
  14482. ASSERT_FALSE(svr.is_running());
  14483. });
  14484. svr.wait_until_ready();
  14485. SSLClient cli("127.0.0.1", PORT);
  14486. cli.set_connection_timeout(30);
  14487. auto res = cli.Get("/");
  14488. ASSERT_FALSE(res);
  14489. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14490. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14491. }
  14492. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14493. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14494. ASSERT_TRUE(svr.is_valid());
  14495. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14496. auto se = detail::scope_exit([&] {
  14497. svr.stop();
  14498. t.join();
  14499. ASSERT_FALSE(svr.is_running());
  14500. });
  14501. svr.wait_until_ready();
  14502. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14503. {
  14504. ws::WebSocketClient client(url);
  14505. auto res = client.connect();
  14506. ASSERT_FALSE(res);
  14507. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14508. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14509. res.ssl_backend_error());
  14510. }
  14511. {
  14512. ws::WebSocketClient client(url);
  14513. client.enable_windows_certificate_verification(false);
  14514. auto res = client.connect();
  14515. ASSERT_FALSE(res);
  14516. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14517. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14518. res.ssl_backend_error());
  14519. }
  14520. }
  14521. #endif
  14522. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14523. Client cli("https://google.com");
  14524. auto res = cli.Get("/");
  14525. // Any status: Google may redirect or rate-limit CI runners.
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. }
  14528. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14529. SSLClient cli("google.com");
  14530. cli.set_ca_cert_path(CA_CERT_FILE);
  14531. auto res = cli.Get("/");
  14532. // Any status: Google may redirect or rate-limit CI runners.
  14533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14534. }
  14535. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14536. SSLClient cli("google.com");
  14537. cli.enable_server_certificate_verification(true);
  14538. cli.set_ca_cert_path("hello");
  14539. auto res = cli.Get("/");
  14540. ASSERT_TRUE(!res);
  14541. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14542. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14543. // should be set
  14544. EXPECT_EQ(0, res.ssl_error());
  14545. // Verify backend error is captured for SSLLoadingCerts
  14546. // This error occurs when loading CA certificates fails
  14547. EXPECT_NE(0UL, res.ssl_backend_error());
  14548. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14549. // OpenSSL specific error codes:
  14550. // > openssl errstr 0x80000002
  14551. // error:80000002:system library::No such file or directory
  14552. // > openssl errstr 0xA000126
  14553. // error:0A000126:SSL routines::unexpected eof while reading
  14554. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14555. res.ssl_backend_error() == 0xA000126);
  14556. #endif
  14557. }
  14558. TEST(SSLClientTest, ServerCertificateVerification4) {
  14559. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14560. ASSERT_TRUE(svr.is_valid());
  14561. svr.Get("/test", [&](const Request &, Response &res) {
  14562. res.set_content("test", "text/plain");
  14563. svr.stop();
  14564. ASSERT_TRUE(true);
  14565. });
  14566. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14567. auto se = detail::scope_exit([&] {
  14568. t.join();
  14569. ASSERT_FALSE(svr.is_running());
  14570. });
  14571. svr.wait_until_ready();
  14572. SSLClient cli("127.0.0.1", PORT);
  14573. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14574. cli.enable_server_certificate_verification(true);
  14575. cli.set_connection_timeout(30);
  14576. auto res = cli.Get("/test");
  14577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14578. ASSERT_EQ(StatusCode::OK_200, res->status);
  14579. }
  14580. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14581. std::string cert;
  14582. read_file(CA_CERT_FILE, cert);
  14583. SSLClient cli("google.com");
  14584. cli.load_ca_cert_store(cert.data(), cert.size());
  14585. const auto res = cli.Get("/");
  14586. // Any status: Google may redirect or rate-limit CI runners.
  14587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14588. }
  14589. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14590. // clang-format off
  14591. static constexpr char cert[] =
  14592. "GlobalSign Root CA\n"
  14593. "==================\n"
  14594. "-----BEGIN CERTIFICATE-----\n"
  14595. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14596. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14597. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14598. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14599. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14600. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14601. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14602. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14603. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14604. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14605. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14606. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14607. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14608. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14609. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14610. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14611. "-----END CERTIFICATE-----\n";
  14612. // clang-format on
  14613. SSLClient cli("google.com");
  14614. cli.load_ca_cert_store(cert, sizeof(cert));
  14615. const auto res = cli.Get("/");
  14616. // Any status: Google may redirect or rate-limit CI runners.
  14617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14618. }
  14619. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14620. SSLClient cli("www.youtube.com");
  14621. cli.set_ca_cert_path(CA_CERT_FILE);
  14622. cli.enable_server_certificate_verification(true);
  14623. cli.set_follow_location(true);
  14624. auto res = cli.Get("/");
  14625. // Any status: Google may redirect or rate-limit CI runners.
  14626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14627. }
  14628. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14629. SSLClient cli("wWw.YouTube.Com");
  14630. cli.set_ca_cert_path(CA_CERT_FILE);
  14631. cli.enable_server_certificate_verification(true);
  14632. cli.enable_server_hostname_verification(true);
  14633. cli.set_follow_location(true);
  14634. auto res = cli.Get("/");
  14635. // Any status: Google may redirect or rate-limit CI runners.
  14636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14637. }
  14638. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14639. SSLClient cli("gOoGlE.COm");
  14640. cli.enable_server_certificate_verification(true);
  14641. cli.enable_server_hostname_verification(true);
  14642. cli.set_follow_location(true);
  14643. auto res = cli.Get("/");
  14644. // Any status: Google may redirect or rate-limit CI runners.
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. }
  14647. TEST(SSLClientTest, Issue2004_Online) {
  14648. Client client("https://google.com");
  14649. client.set_follow_location(true);
  14650. auto res = client.Get("/");
  14651. // Any status: Google may redirect or rate-limit CI runners.
  14652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14653. }
  14654. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14655. // Create SSLClient with invalid cert/key to make is_valid() return false
  14656. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14657. "nonexistent_key.pem");
  14658. // is_valid() should be false due to cert loading failure
  14659. ASSERT_FALSE(cli.is_valid());
  14660. auto res = cli.Get("/");
  14661. ASSERT_FALSE(res);
  14662. EXPECT_EQ(Error::SSLConnection, res.error());
  14663. }
  14664. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14665. // Test for Issue #2251: SSL error not properly reported when client cert
  14666. // and key paths are swapped or mismatched
  14667. // This simulates the scenario where user accidentally swaps the cert and key
  14668. // files
  14669. // Using client cert file as private key and vice versa (completely wrong)
  14670. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14671. // Should fail validation due to cert/key mismatch
  14672. ASSERT_FALSE(cli.is_valid());
  14673. // Attempt to make a request should fail with proper error
  14674. auto res = cli.Get("/");
  14675. ASSERT_FALSE(res);
  14676. EXPECT_EQ(Error::SSLConnection, res.error());
  14677. // SSL error should be recorded in the Result object (this is the key fix for
  14678. // Issue #2251)
  14679. auto backend_error = res.ssl_backend_error();
  14680. EXPECT_NE(0u, backend_error);
  14681. }
  14682. // Tests cert/key mismatch detection at the TLS context level
  14683. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14684. // Test that using mismatched cert/key causes connection failure.
  14685. // We verify this at the SSLClient level rather than through internal
  14686. // TLS API functions.
  14687. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14688. cli.enable_server_certificate_verification(false);
  14689. cli.set_connection_timeout(2);
  14690. // The mismatch should cause a connection or handshake error
  14691. auto res = cli.Get("/test");
  14692. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14693. // Either way, the request should fail
  14694. EXPECT_FALSE(res);
  14695. }
  14696. #endif
  14697. #if 0
  14698. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14699. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14700. ASSERT_TRUE(cli != nullptr);
  14701. cli->set_address_family(AF_INET6);
  14702. cli->set_interface("en0");
  14703. auto res = cli->Get("/get");
  14704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14705. ASSERT_EQ(StatusCode::OK_200, res->status);
  14706. }
  14707. #endif
  14708. // Client certificate tests - work with all TLS backends
  14709. #ifdef CPPHTTPLIB_SSL_ENABLED
  14710. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14711. void ClientCertPresent(
  14712. const std::string &client_cert_file,
  14713. const std::string &client_private_key_file,
  14714. const std::string &client_encrypted_private_key_pass = std::string(),
  14715. const ClientCertServerSetup &setup = nullptr) {
  14716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14717. ASSERT_TRUE(svr.is_valid());
  14718. if (setup) { setup(svr); }
  14719. svr.Get("/test", [&](const Request &req, Response &res) {
  14720. res.set_content("test", "text/plain");
  14721. auto cert = req.peer_cert();
  14722. ASSERT_TRUE(static_cast<bool>(cert));
  14723. std::string common_name = cert.subject_cn();
  14724. EXPECT_EQ("Common Name", common_name);
  14725. });
  14726. auto port = svr.bind_to_any_port(HOST);
  14727. ASSERT_LT(0, port);
  14728. thread t = thread([&]() { svr.listen_after_bind(); });
  14729. auto se = detail::scope_exit([&] {
  14730. svr.stop();
  14731. t.join();
  14732. ASSERT_FALSE(svr.is_running());
  14733. });
  14734. svr.wait_until_ready();
  14735. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14736. client_encrypted_private_key_pass);
  14737. cli.enable_server_certificate_verification(false);
  14738. cli.set_connection_timeout(30);
  14739. auto res = cli.Get("/test");
  14740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14741. ASSERT_EQ(StatusCode::OK_200, res->status);
  14742. }
  14743. TEST(SSLClientServerTest, ClientCertPresent) {
  14744. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14745. }
  14746. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14747. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14748. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14749. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14750. }
  14751. // Expects svr, which must require client certificates, to reject a client
  14752. // that has none
  14753. void RejectsClientWithoutCert(SSLServer &svr) {
  14754. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14755. auto port = svr.bind_to_any_port(HOST);
  14756. ASSERT_LT(0, port);
  14757. thread t = thread([&]() { svr.listen_after_bind(); });
  14758. auto se = detail::scope_exit([&] {
  14759. svr.stop();
  14760. t.join();
  14761. ASSERT_FALSE(svr.is_running());
  14762. });
  14763. svr.wait_until_ready();
  14764. SSLClient cli(HOST, port);
  14765. cli.set_connection_timeout(30);
  14766. // Skip the server certificate check, so that the request fails because the
  14767. // client certificate is missing rather than because cert.pem is not trusted
  14768. cli.enable_server_certificate_verification(false);
  14769. auto res = cli.Get("/test");
  14770. ASSERT_FALSE(res);
  14771. // The server rejects the client during the handshake, or on TLS 1.3 right
  14772. // after it, which the client notices on its first write or read
  14773. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14774. res.error() == Error::Write || res.error() == Error::Read)
  14775. << to_string(res.error());
  14776. if (res.error() == Error::SSLConnection) {
  14777. EXPECT_NE(0UL, res.ssl_backend_error());
  14778. }
  14779. // A rejection noticed on the write keeps the TLS error the write hit
  14780. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14781. }
  14782. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14784. ASSERT_TRUE(svr.is_valid());
  14785. if (setup) { setup(svr); }
  14786. RejectsClientWithoutCert(svr);
  14787. }
  14788. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14789. // A server that requires client certificates must keep requiring them after
  14790. // setup changes it, and keep accepting a client that has one
  14791. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14792. ClientCertMissing(setup);
  14793. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14794. setup);
  14795. }
  14796. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14797. ClientCertStillRequired([](SSLServer &svr) {
  14798. ASSERT_TRUE(tls::set_verify_callback(
  14799. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14800. });
  14801. }
  14802. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14803. ClientCertStillRequired([](SSLServer &svr) {
  14804. ASSERT_TRUE(tls::set_verify_callback(
  14805. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14806. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14807. });
  14808. }
  14809. // The client verifies the server certificate during the handshake, so a
  14810. // server that fails the check never gets the client certificate, even when a
  14811. // verifier of the client's own accepts it
  14812. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14813. struct Case {
  14814. const char *trusted_ca;
  14815. const char *host;
  14816. Error error;
  14817. };
  14818. // cert2.pem names localhost: the first client does not trust it, and the
  14819. // second trusts it but asks for another name
  14820. for (const auto &c :
  14821. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14822. Case{SERVER_CERT2_FILE, "example.com",
  14823. Error::SSLServerHostnameVerification}}) {
  14824. for (auto with_verifier : {false, true}) {
  14825. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14826. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14827. CLIENT_CA_CERT_FILE);
  14828. ASSERT_TRUE(svr.is_valid());
  14829. std::atomic<bool> got_client_cert{false};
  14830. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14831. [&](const tls::VerifyContext &) {
  14832. got_client_cert = true;
  14833. return true;
  14834. }));
  14835. auto port = svr.bind_to_any_port("127.0.0.1");
  14836. ASSERT_LT(0, port);
  14837. thread t = thread([&] { svr.listen_after_bind(); });
  14838. svr.wait_until_ready();
  14839. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14840. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14841. cli.set_ca_cert_path(c.trusted_ca);
  14842. if (with_verifier) {
  14843. cli.set_server_certificate_verifier(
  14844. [](const tls::VerifyContext &) { return true; });
  14845. }
  14846. auto res = cli.Get("/");
  14847. EXPECT_FALSE(res);
  14848. EXPECT_EQ(c.error, res.error());
  14849. svr.stop();
  14850. t.join();
  14851. EXPECT_FALSE(got_client_cert);
  14852. }
  14853. }
  14854. }
  14855. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14856. std::string cert_pem, key_pem, ca_pem;
  14857. read_file(SERVER_CERT_FILE, cert_pem);
  14858. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14859. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14860. ASSERT_TRUE(
  14861. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14862. }
  14863. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14865. ASSERT_TRUE(svr.is_valid());
  14866. UpdateCertsPemWithClientCA(svr);
  14867. RejectsClientWithoutCert(svr);
  14868. }
  14869. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14870. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14871. }
  14872. // A TLS error from one request must not show up in a later request's Result
  14873. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14875. ASSERT_TRUE(svr.is_valid());
  14876. svr.Get("/test", [](const Request &, Response &res) {
  14877. res.set_content("test", "text/plain");
  14878. });
  14879. auto port = svr.bind_to_any_port(HOST);
  14880. ASSERT_LT(0, port);
  14881. thread t = thread([&]() { svr.listen_after_bind(); });
  14882. auto se = detail::scope_exit([&] {
  14883. svr.stop();
  14884. t.join();
  14885. ASSERT_FALSE(svr.is_running());
  14886. });
  14887. svr.wait_until_ready();
  14888. SSLClient cli(HOST, port);
  14889. cli.set_connection_timeout(30);
  14890. cli.enable_server_hostname_verification(false);
  14891. // cert.pem is not trusted, so the handshake fails
  14892. ASSERT_FALSE(cli.Get("/test"));
  14893. cli.enable_server_certificate_verification(false);
  14894. auto res = cli.Get("/test");
  14895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14896. EXPECT_EQ(0, res.ssl_error());
  14897. EXPECT_EQ(0UL, res.ssl_backend_error());
  14898. }
  14899. // PEM memory-based constructor tests (works with all TLS backends).
  14900. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14901. // terminator after it.
  14902. void PemMemoryClientCertPresent(
  14903. const std::string &client_cert_file,
  14904. const std::string &client_private_key_file,
  14905. const std::string &client_encrypted_private_key_pass = std::string(),
  14906. bool exact_size = false) {
  14907. // Read PEM files into memory
  14908. std::string server_cert_pem, server_key_pem;
  14909. std::string client_ca_pem;
  14910. std::string client_cert_pem, client_key_pem;
  14911. read_file(SERVER_CERT_FILE, server_cert_pem);
  14912. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14913. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14914. read_file(client_cert_file, client_cert_pem);
  14915. read_file(client_private_key_file, client_key_pem);
  14916. std::list<std::vector<char>> exact_copies;
  14917. auto data = [&](const std::string &pem) -> const char * {
  14918. if (!exact_size) { return pem.c_str(); }
  14919. exact_copies.emplace_back(pem.begin(), pem.end());
  14920. return exact_copies.back().data();
  14921. };
  14922. // Create server with PEM memory
  14923. SSLServer::PemMemory server_pem = {
  14924. data(server_cert_pem),
  14925. server_cert_pem.size(),
  14926. data(server_key_pem),
  14927. server_key_pem.size(),
  14928. data(client_ca_pem),
  14929. client_ca_pem.size(),
  14930. nullptr // no password for server key
  14931. };
  14932. SSLServer svr(server_pem);
  14933. ASSERT_TRUE(svr.is_valid());
  14934. svr.Get("/test", [&](const Request &req, Response &res) {
  14935. res.set_content("test", "text/plain");
  14936. auto cert = req.peer_cert();
  14937. ASSERT_TRUE(static_cast<bool>(cert));
  14938. EXPECT_EQ("Common Name", cert.subject_cn());
  14939. });
  14940. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14941. auto se = detail::scope_exit([&] {
  14942. svr.stop();
  14943. t.join();
  14944. ASSERT_FALSE(svr.is_running());
  14945. });
  14946. svr.wait_until_ready();
  14947. // Create client with PEM memory
  14948. const char *password = client_encrypted_private_key_pass.empty()
  14949. ? nullptr
  14950. : client_encrypted_private_key_pass.c_str();
  14951. SSLClient::PemMemory client_pem = {
  14952. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14953. client_key_pem.size(), password};
  14954. SSLClient cli(HOST, PORT, client_pem);
  14955. cli.enable_server_certificate_verification(false);
  14956. cli.set_connection_timeout(30);
  14957. auto res = cli.Get("/test");
  14958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14959. ASSERT_EQ(StatusCode::OK_200, res->status);
  14960. }
  14961. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14962. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14963. }
  14964. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14965. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14966. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14967. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14968. }
  14969. // A server built from PEM memory with a client CA requires client certificates,
  14970. // also when the CA is a NUL-terminated string passed with a length of 0
  14971. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14972. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14973. read_file(SERVER_CERT_FILE, server_cert_pem);
  14974. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14975. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14976. SSLServer::PemMemory server_pem = {
  14977. server_cert_pem.c_str(),
  14978. server_cert_pem.size(),
  14979. server_key_pem.c_str(),
  14980. server_key_pem.size(),
  14981. client_ca_pem.c_str(),
  14982. client_ca_pem.size(),
  14983. nullptr // no password for server key
  14984. };
  14985. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14986. SCOPED_TRACE(client_ca_pem_len);
  14987. server_pem.client_ca_pem_len = client_ca_pem_len;
  14988. SSLServer svr(server_pem);
  14989. ASSERT_TRUE(svr.is_valid());
  14990. RejectsClientWithoutCert(svr);
  14991. }
  14992. // An empty CA fails to load instead of turning the check off
  14993. server_pem.client_ca_pem = "";
  14994. server_pem.client_ca_pem_len = 0;
  14995. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14996. }
  14997. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14998. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14999. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  15000. true);
  15001. }
  15002. // A length shorter than the PEM cuts it short, so it no longer loads
  15003. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  15004. std::string cert, key;
  15005. read_file(SERVER_CERT_FILE, cert);
  15006. read_file(SERVER_PRIVATE_KEY_FILE, key);
  15007. for (auto cut_cert : {true, false}) {
  15008. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  15009. auto key_len = cut_cert ? key.size() : key.size() / 2;
  15010. SSLServer::PemMemory server_pem = {
  15011. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  15012. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  15013. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  15014. key_len, nullptr};
  15015. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  15016. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  15017. key.c_str(), key_len, nullptr};
  15018. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  15019. }
  15020. }
  15021. TEST(SSLClientServerTest, SSLConnectTimeout) {
  15022. class NoListenSSLServer : public SSLServer {
  15023. public:
  15024. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  15025. const char *client_ca_cert_file_path,
  15026. const char *client_ca_cert_dir_path = nullptr)
  15027. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  15028. client_ca_cert_dir_path),
  15029. stop_(false) {}
  15030. std::atomic_bool stop_;
  15031. private:
  15032. bool process_and_close_socket(socket_t /*sock*/) override {
  15033. // Don't create SSL context
  15034. while (!stop_.load()) {
  15035. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  15036. }
  15037. return true;
  15038. }
  15039. };
  15040. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15041. CLIENT_CA_CERT_FILE);
  15042. ASSERT_TRUE(svr.is_valid());
  15043. // Keep-alive parking would bypass the override.
  15044. svr.set_keep_alive_parking(false);
  15045. svr.Get("/test", [&](const Request &, Response &res) {
  15046. res.set_content("test", "text/plain");
  15047. });
  15048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15049. auto se = detail::scope_exit([&] {
  15050. svr.stop_ = true;
  15051. svr.stop();
  15052. t.join();
  15053. ASSERT_FALSE(svr.is_running());
  15054. });
  15055. svr.wait_until_ready();
  15056. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15057. cli.enable_server_certificate_verification(false);
  15058. cli.set_connection_timeout(1);
  15059. auto res = cli.Get("/test");
  15060. ASSERT_TRUE(!res);
  15061. EXPECT_EQ(Error::SSLConnection, res.error());
  15062. // Timeout results in WantRead error code (maps to backend-specific value)
  15063. EXPECT_NE(0, res.ssl_error());
  15064. }
  15065. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  15066. // Test SSLServer with client certificate verification using the standard
  15067. // constructor (ContextSetupCallback is tested by backend-specific tests)
  15068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  15069. CLIENT_CA_CERT_DIR);
  15070. ASSERT_TRUE(svr.is_valid());
  15071. svr.Get("/test", [&](const Request &req, Response &res) {
  15072. res.set_content("test", "text/plain");
  15073. auto cert = req.peer_cert();
  15074. ASSERT_TRUE(static_cast<bool>(cert));
  15075. auto common_name = cert.subject_cn();
  15076. EXPECT_EQ("Common Name", common_name);
  15077. });
  15078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15079. auto se = detail::scope_exit([&] {
  15080. svr.stop();
  15081. t.join();
  15082. ASSERT_FALSE(svr.is_running());
  15083. });
  15084. svr.wait_until_ready();
  15085. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15086. cli.enable_server_certificate_verification(false);
  15087. cli.set_connection_timeout(30);
  15088. auto res = cli.Get("/test");
  15089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15090. ASSERT_EQ(StatusCode::OK_200, res->status);
  15091. }
  15092. // Test verify_hostname on every backend: a host is named by a SAN only
  15093. TEST(SSLClientServerTest, TlsVerifyHostname) {
  15094. using namespace httplib::tls;
  15095. // We need a running server to test against
  15096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15097. ASSERT_TRUE(svr.is_valid());
  15098. svr.Get("/test", [](const Request &, Response &res) {
  15099. res.set_content("ok", "text/plain");
  15100. });
  15101. thread t([&]() { svr.listen(HOST, PORT); });
  15102. auto se = detail::scope_exit([&] {
  15103. svr.stop();
  15104. t.join();
  15105. });
  15106. svr.wait_until_ready();
  15107. bool verify_callback_called = false;
  15108. bool verify_result_wrong = false;
  15109. SSLClient cli(HOST, PORT);
  15110. cli.enable_server_certificate_verification(true);
  15111. cli.set_ca_cert_path(CA_CERT_FILE);
  15112. cli.set_connection_timeout(5);
  15113. // Note: Test certificate has CN="Common Name", not "localhost"
  15114. bool verify_result_cn = false;
  15115. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15116. verify_callback_called = true;
  15117. if (!ctx.cert) return false;
  15118. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  15119. verify_result_cn = ctx.check_hostname("Common Name");
  15120. // Test 2: wrong hostname should not match
  15121. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  15122. return true; // Accept for the purpose of this test
  15123. });
  15124. auto res = cli.Get("/test");
  15125. // The request may succeed or fail depending on cert configuration
  15126. // but the callback should have been called
  15127. ASSERT_TRUE(verify_callback_called)
  15128. << "Verify callback should have been called";
  15129. EXPECT_FALSE(verify_result_cn)
  15130. << "verify_hostname must not match the certificate CN (no SAN)";
  15131. // Wrong hostname should not match
  15132. EXPECT_FALSE(verify_result_wrong)
  15133. << "verify_hostname should not match 'wronghost.example.com'";
  15134. }
  15135. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  15136. // backend verifies it.
  15137. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  15138. // Certificate CN is "localhost" and it carries no SAN.
  15139. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15140. ASSERT_TRUE(svr.is_valid());
  15141. svr.Get("/test", [](const Request &, Response &res) {
  15142. res.set_content("ok", "text/plain");
  15143. });
  15144. auto port = svr.bind_to_any_port(HOST);
  15145. thread t([&]() { svr.listen_after_bind(); });
  15146. auto se = detail::scope_exit([&] {
  15147. svr.stop();
  15148. t.join();
  15149. });
  15150. svr.wait_until_ready();
  15151. SSLClient cli("localhost", port);
  15152. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15153. cli.enable_server_certificate_verification(true);
  15154. cli.set_connection_timeout(5);
  15155. auto res = cli.Get("/test");
  15156. ASSERT_FALSE(res);
  15157. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15158. // The same certificate is accepted once host name verification is off, so the
  15159. // failure above is the host name and not the chain.
  15160. cli.enable_server_hostname_verification(false);
  15161. res = cli.Get("/test");
  15162. ASSERT_TRUE(res) << to_string(res.error());
  15163. EXPECT_EQ(StatusCode::OK_200, res->status);
  15164. }
  15165. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15166. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15167. // X509_check_ip behavior and must hold for every backend.
  15168. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15169. using namespace httplib::tls;
  15170. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15171. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15172. ASSERT_TRUE(svr.is_valid());
  15173. svr.Get("/test", [](const Request &, Response &res) {
  15174. res.set_content("ok", "text/plain");
  15175. });
  15176. thread t([&]() { svr.listen(HOST, PORT); });
  15177. auto se = detail::scope_exit([&] {
  15178. svr.stop();
  15179. t.join();
  15180. });
  15181. svr.wait_until_ready();
  15182. bool verify_callback_called = false;
  15183. bool ip_matched_via_cn = true;
  15184. SSLClient cli(HOST, PORT);
  15185. cli.enable_server_certificate_verification(true);
  15186. cli.set_ca_cert_path(CA_CERT_FILE);
  15187. cli.set_connection_timeout(5);
  15188. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15189. verify_callback_called = true;
  15190. if (!ctx.cert) return false;
  15191. // The IP appears only in the CN, so it must NOT be accepted.
  15192. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15193. return true; // Accept for the purpose of this test
  15194. });
  15195. cli.Get("/test");
  15196. ASSERT_TRUE(verify_callback_called)
  15197. << "Verify callback should have been called";
  15198. EXPECT_FALSE(ip_matched_via_cn)
  15199. << "An IP host must not be authenticated via the certificate CN";
  15200. }
  15201. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15202. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15203. using namespace httplib::tls;
  15204. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15205. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15206. ASSERT_TRUE(svr.is_valid());
  15207. svr.Get("/test", [](const Request &, Response &res) {
  15208. res.set_content("ok", "text/plain");
  15209. });
  15210. thread t([&]() { svr.listen(HOST, PORT); });
  15211. auto se = detail::scope_exit([&] {
  15212. svr.stop();
  15213. t.join();
  15214. });
  15215. svr.wait_until_ready();
  15216. bool verify_callback_called = false;
  15217. bool san_matched = false;
  15218. bool wrong_ipv6_matched = true;
  15219. bool cn_ipv6_matched = true;
  15220. SSLClient cli(HOST, PORT);
  15221. cli.enable_server_certificate_verification(true);
  15222. cli.set_ca_cert_path(CA_CERT_FILE);
  15223. cli.set_connection_timeout(5);
  15224. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15225. verify_callback_called = true;
  15226. if (!ctx.cert) return false;
  15227. // Matches the IPv6 iPAddress SAN.
  15228. san_matched = ctx.check_hostname("2001:db8::1");
  15229. // A different IPv6 address must not match.
  15230. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15231. // "::1" lives only in the CN, so it must not be accepted.
  15232. cn_ipv6_matched = ctx.check_hostname("::1");
  15233. return true; // Accept for the purpose of this test
  15234. });
  15235. cli.Get("/test");
  15236. ASSERT_TRUE(verify_callback_called)
  15237. << "Verify callback should have been called";
  15238. EXPECT_TRUE(san_matched)
  15239. << "verify_hostname should match an IPv6 iPAddress SAN";
  15240. EXPECT_FALSE(wrong_ipv6_matched)
  15241. << "verify_hostname should not match a non-matching IPv6 address";
  15242. EXPECT_FALSE(cn_ipv6_matched)
  15243. << "An IPv6 host must not be authenticated via the certificate CN";
  15244. }
  15245. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15246. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15247. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15248. using namespace httplib::tls;
  15249. // SANs: DNS:a.zz, IP:42.46.122.122
  15250. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15251. ASSERT_TRUE(svr.is_valid());
  15252. svr.Get("/test", [](const Request &, Response &res) {
  15253. res.set_content("ok", "text/plain");
  15254. });
  15255. auto port = svr.bind_to_any_port(HOST);
  15256. thread t([&]() { svr.listen_after_bind(); });
  15257. auto se = detail::scope_exit([&] {
  15258. svr.stop();
  15259. t.join();
  15260. });
  15261. svr.wait_until_ready();
  15262. bool verify_callback_called = false;
  15263. bool dns_san_matched = false;
  15264. bool ip_san_matched = false;
  15265. bool ip_matched_via_dns_san = true;
  15266. bool dns_matched_via_ip_san = true;
  15267. bool cn_matched_next_to_dns_san = true;
  15268. SSLClient cli(HOST, port);
  15269. cli.enable_server_certificate_verification(true);
  15270. cli.set_ca_cert_path(CA_CERT_FILE);
  15271. cli.set_connection_timeout(5);
  15272. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15273. verify_callback_called = true;
  15274. if (!ctx.cert) return false;
  15275. dns_san_matched = ctx.check_hostname("a.zz");
  15276. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15277. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15278. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15279. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15280. return true; // Accept for the purpose of this test
  15281. });
  15282. cli.Get("/test");
  15283. ASSERT_TRUE(verify_callback_called)
  15284. << "Verify callback should have been called";
  15285. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15286. EXPECT_TRUE(ip_san_matched)
  15287. << "verify_hostname should match an iPAddress SAN";
  15288. EXPECT_FALSE(ip_matched_via_dns_san)
  15289. << "An IP host must not be authenticated via a dNSName SAN";
  15290. EXPECT_FALSE(dns_matched_via_ip_san)
  15291. << "A DNS host must not be authenticated via an iPAddress SAN";
  15292. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15293. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15294. }
  15295. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15296. // "www.*.example.test" names one host and not every host under example.test.
  15297. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15298. using namespace httplib::tls;
  15299. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15300. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15301. ASSERT_TRUE(svr.is_valid());
  15302. svr.Get("/test", [](const Request &, Response &res) {
  15303. res.set_content("ok", "text/plain");
  15304. });
  15305. auto port = svr.bind_to_any_port(HOST);
  15306. thread t([&]() { svr.listen_after_bind(); });
  15307. auto se = detail::scope_exit([&] {
  15308. svr.stop();
  15309. t.join();
  15310. });
  15311. svr.wait_until_ready();
  15312. bool verify_callback_called = false;
  15313. bool leftmost_wildcard_matched = false;
  15314. bool wildcard_spanned_labels = true;
  15315. bool inner_wildcard_matched = true;
  15316. SSLClient cli(HOST, port);
  15317. cli.enable_server_certificate_verification(true);
  15318. cli.set_ca_cert_path(CA_CERT_FILE);
  15319. cli.set_connection_timeout(5);
  15320. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15321. verify_callback_called = true;
  15322. if (!ctx.cert) return false;
  15323. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15324. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15325. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15326. return true; // Accept for the purpose of this test
  15327. });
  15328. cli.Get("/test");
  15329. ASSERT_TRUE(verify_callback_called)
  15330. << "Verify callback should have been called";
  15331. EXPECT_TRUE(leftmost_wildcard_matched)
  15332. << "A leftmost wildcard should match a single label";
  15333. EXPECT_FALSE(wildcard_spanned_labels)
  15334. << "A wildcard label must not match more than one label";
  15335. EXPECT_FALSE(inner_wildcard_matched)
  15336. << "A wildcard outside the leftmost label must not be honoured";
  15337. }
  15338. // sans() must report each SAN entry under its own type.
  15339. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15340. using namespace httplib::tls;
  15341. // SANs: DNS:a.zz, IP:42.46.122.122
  15342. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15343. ASSERT_TRUE(svr.is_valid());
  15344. svr.Get("/test", [](const Request &, Response &res) {
  15345. res.set_content("ok", "text/plain");
  15346. });
  15347. auto port = svr.bind_to_any_port(HOST);
  15348. thread t([&]() { svr.listen_after_bind(); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. });
  15353. svr.wait_until_ready();
  15354. bool verify_callback_called = false;
  15355. std::vector<SanEntry> sans;
  15356. SSLClient cli(HOST, port);
  15357. cli.enable_server_certificate_verification(true);
  15358. cli.set_ca_cert_path(CA_CERT_FILE);
  15359. cli.set_connection_timeout(5);
  15360. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15361. verify_callback_called = true;
  15362. if (!ctx.cert) return false;
  15363. sans = ctx.sans();
  15364. return true; // Accept for the purpose of this test
  15365. });
  15366. cli.Get("/test");
  15367. ASSERT_TRUE(verify_callback_called)
  15368. << "Verify callback should have been called";
  15369. auto has_san = [&](SanType type, const std::string &value) {
  15370. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15371. return san.type == type && san.value == value;
  15372. });
  15373. };
  15374. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15375. << "sans() should report the dNSName SAN";
  15376. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15377. << "sans() should report the iPAddress SAN";
  15378. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15379. << "sans() must not report the dNSName SAN as an address";
  15380. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15381. << "sans() must not report the iPAddress SAN as a DNS name";
  15382. }
  15383. #endif
  15384. // mbedTLS-specific callback constructor test
  15385. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15386. #ifdef CPPHTTPLIB_SSL_ENABLED
  15387. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15389. ASSERT_TRUE(svr.is_valid());
  15390. // Set up a handler to verify client certificate is present
  15391. bool client_cert_verified = false;
  15392. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15393. // Verify that client certificate was provided
  15394. client_cert_verified = true;
  15395. res.set_content("success", "text/plain");
  15396. });
  15397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15398. auto se = detail::scope_exit([&] {
  15399. svr.stop();
  15400. t.join();
  15401. ASSERT_FALSE(svr.is_running());
  15402. });
  15403. svr.wait_until_ready();
  15404. // Client with certificate
  15405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15406. cli.enable_server_certificate_verification(false);
  15407. cli.set_connection_timeout(30);
  15408. auto res = cli.Get("/test");
  15409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15410. ASSERT_EQ(StatusCode::OK_200, res->status);
  15411. ASSERT_TRUE(client_cert_verified);
  15412. EXPECT_EQ("success", res->body);
  15413. }
  15414. #endif
  15415. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15416. // backends
  15417. #ifdef CPPHTTPLIB_SSL_ENABLED
  15418. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15419. using namespace httplib::tls;
  15420. // Test that when client CA cert file is provided,
  15421. // the server properly requests and validates client certificates
  15422. // Create a server with client authentication
  15423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15424. ASSERT_TRUE(svr.is_valid());
  15425. bool handler_called = false;
  15426. svr.Get("/test", [&](const Request &req, Response &res) {
  15427. handler_called = true;
  15428. // Verify that a client certificate was provided
  15429. auto cert = req.peer_cert();
  15430. ASSERT_TRUE(static_cast<bool>(cert));
  15431. // Get the issuer name
  15432. std::string issuer_str = cert.issuer_name();
  15433. ASSERT_FALSE(issuer_str.empty());
  15434. // The client certificate should be issued by our test CA
  15435. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15436. res.set_content("authenticated", "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. ASSERT_FALSE(svr.is_running());
  15443. });
  15444. svr.wait_until_ready();
  15445. // Connect with a client certificate issued by the CA
  15446. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15447. cli.enable_server_certificate_verification(false);
  15448. cli.set_connection_timeout(30);
  15449. auto res = cli.Get("/test");
  15450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15451. ASSERT_EQ(StatusCode::OK_200, res->status);
  15452. ASSERT_TRUE(handler_called);
  15453. EXPECT_EQ("authenticated", res->body);
  15454. }
  15455. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15456. using namespace httplib::tls;
  15457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15458. ASSERT_TRUE(svr.is_valid());
  15459. svr.Get("/test", [](const Request &, Response &res) {
  15460. res.set_content("ok", "text/plain");
  15461. });
  15462. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15463. auto se = detail::scope_exit([&] {
  15464. svr.stop();
  15465. t.join();
  15466. });
  15467. svr.wait_until_ready();
  15468. SSLClient cli(HOST, PORT);
  15469. cli.enable_server_certificate_verification(false);
  15470. cli.set_connection_timeout(30);
  15471. bool cert_checked = false;
  15472. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15473. if (ctx.cert) {
  15474. auto sans = ctx.sans();
  15475. // Test certificate may or may not have SANs - just verify the API
  15476. // works If SANs exist, verify the types are valid
  15477. for (const auto &san : sans) {
  15478. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15479. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15480. san.type == SanType::OTHER);
  15481. EXPECT_FALSE(san.value.empty());
  15482. }
  15483. cert_checked = true;
  15484. }
  15485. return true;
  15486. });
  15487. auto res = cli.Get("/test");
  15488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15489. EXPECT_TRUE(cert_checked);
  15490. }
  15491. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15492. using namespace httplib::tls;
  15493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15494. ASSERT_TRUE(svr.is_valid());
  15495. svr.Get("/test", [](const Request &, Response &res) {
  15496. res.set_content("ok", "text/plain");
  15497. });
  15498. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15499. auto se = detail::scope_exit([&] {
  15500. svr.stop();
  15501. t.join();
  15502. });
  15503. svr.wait_until_ready();
  15504. SSLClient cli(HOST, PORT);
  15505. cli.enable_server_certificate_verification(false);
  15506. cli.set_connection_timeout(30);
  15507. bool validity_checked = false;
  15508. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15509. if (ctx.cert) {
  15510. time_t not_before = 0, not_after = 0;
  15511. bool result = ctx.validity(not_before, not_after);
  15512. EXPECT_TRUE(result);
  15513. // Verify that not_before < now < not_after for a valid cert
  15514. time_t now = time(nullptr);
  15515. EXPECT_LT(not_before, now);
  15516. EXPECT_GT(not_after, now);
  15517. validity_checked = true;
  15518. }
  15519. return true;
  15520. });
  15521. auto res = cli.Get("/test");
  15522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15523. EXPECT_TRUE(validity_checked);
  15524. }
  15525. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15526. using namespace httplib::tls;
  15527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15528. ASSERT_TRUE(svr.is_valid());
  15529. svr.Get("/test", [](const Request &, Response &res) {
  15530. res.set_content("ok", "text/plain");
  15531. });
  15532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15533. auto se = detail::scope_exit([&] {
  15534. svr.stop();
  15535. t.join();
  15536. });
  15537. svr.wait_until_ready();
  15538. SSLClient cli(HOST, PORT);
  15539. cli.enable_server_certificate_verification(false);
  15540. cli.set_connection_timeout(30);
  15541. bool serial_checked = false;
  15542. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15543. if (ctx.cert) {
  15544. std::string serial = ctx.serial();
  15545. EXPECT_FALSE(serial.empty());
  15546. // Serial should be a hex string
  15547. for (char c : serial) {
  15548. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15549. (c >= 'a' && c <= 'f'));
  15550. }
  15551. serial_checked = true;
  15552. }
  15553. return true;
  15554. });
  15555. auto res = cli.Get("/test");
  15556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15557. EXPECT_TRUE(serial_checked);
  15558. }
  15559. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15560. // Test 1: Valid CA file - no error should be recorded
  15561. {
  15562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15563. CLIENT_CA_CERT_FILE);
  15564. ASSERT_TRUE(svr.is_valid());
  15565. // With valid setup, last_ssl_error should be 0
  15566. EXPECT_EQ(0, svr.ssl_last_error());
  15567. }
  15568. // Test 2: Invalid CA file content
  15569. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15570. {
  15571. // Create a temporary file with completely invalid content
  15572. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15573. {
  15574. std::ofstream ofs(temp_invalid_ca);
  15575. ofs << "This is not a certificate file at all\n";
  15576. ofs << "Just plain text content\n";
  15577. }
  15578. // Create server with invalid CA file
  15579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15580. // Clean up temporary file
  15581. std::remove(temp_invalid_ca);
  15582. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15583. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15584. // Note: SSL_CTX_load_verify_locations typically fails first,
  15585. // but our error handling code path is still exercised
  15586. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15587. }
  15588. }
  15589. TEST(VerifyCallbackTest, VerifyContextFields) {
  15590. using namespace httplib::tls;
  15591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15592. ASSERT_TRUE(svr.is_valid());
  15593. svr.Get("/test", [](const Request &, Response &res) {
  15594. res.set_content("ok", "text/plain");
  15595. });
  15596. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15597. auto se = detail::scope_exit([&] {
  15598. svr.stop();
  15599. t.join();
  15600. });
  15601. svr.wait_until_ready();
  15602. SSLClient cli(HOST, PORT);
  15603. cli.enable_server_certificate_verification(false);
  15604. cli.set_connection_timeout(30);
  15605. int callback_count = 0;
  15606. bool saw_leaf_cert = false;
  15607. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15608. if (ctx.cert) {
  15609. callback_count++;
  15610. // We should see at least one certificate (the leaf)
  15611. std::string cn = ctx.subject_cn();
  15612. if (!cn.empty()) { saw_leaf_cert = true; }
  15613. // Verify context fields are populated
  15614. EXPECT_NE(ctx.session, nullptr);
  15615. EXPECT_GE(ctx.depth, 0);
  15616. }
  15617. return true;
  15618. });
  15619. auto res = cli.Get("/test");
  15620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15621. EXPECT_GT(callback_count, 0);
  15622. EXPECT_TRUE(saw_leaf_cert);
  15623. }
  15624. // A verifier that accepts runs alongside the built-in verification, and is the
  15625. // only check once that is turned off.
  15626. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15627. using namespace httplib::tls;
  15628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15629. ASSERT_TRUE(svr.is_valid());
  15630. svr.Get("/test", [](const Request &, Response &res) {
  15631. res.set_content("ok", "text/plain");
  15632. });
  15633. auto port = svr.bind_to_any_port(HOST);
  15634. thread t([&]() { svr.listen_after_bind(); });
  15635. auto se = detail::scope_exit([&] {
  15636. svr.stop();
  15637. t.join();
  15638. });
  15639. svr.wait_until_ready();
  15640. SSLClient cli(HOST, port);
  15641. cli.enable_server_hostname_verification(false);
  15642. auto calls = 0;
  15643. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15644. calls++;
  15645. return true;
  15646. });
  15647. // cert.pem is not trusted
  15648. auto res = cli.Get("/test");
  15649. ASSERT_FALSE(res);
  15650. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15651. EXPECT_GT(calls, 0);
  15652. cli.enable_server_certificate_verification(false);
  15653. res = cli.Get("/test");
  15654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15655. EXPECT_EQ("ok", res->body);
  15656. }
  15657. // A verifier belongs to the client that set it, not to the thread that set it.
  15658. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15659. using namespace httplib::tls;
  15660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15661. ASSERT_TRUE(svr.is_valid());
  15662. svr.Get("/test", [](const Request &, Response &res) {
  15663. res.set_content("ok", "text/plain");
  15664. });
  15665. auto port = svr.bind_to_any_port(HOST);
  15666. thread t([&]() { svr.listen_after_bind(); });
  15667. auto se = detail::scope_exit([&] {
  15668. svr.stop();
  15669. t.join();
  15670. });
  15671. svr.wait_until_ready();
  15672. auto rejecting_calls = 0;
  15673. SSLClient rejecting(HOST, port);
  15674. rejecting.enable_server_certificate_verification(false);
  15675. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15676. rejecting_calls++;
  15677. return false;
  15678. });
  15679. auto accepting_calls = 0;
  15680. SSLClient accepting(HOST, port);
  15681. accepting.enable_server_certificate_verification(false);
  15682. // Set on another thread than the requests below.
  15683. thread([&]() {
  15684. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15685. accepting_calls++;
  15686. return true;
  15687. });
  15688. }).join();
  15689. // Requested on another thread than the verifier was set on.
  15690. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15691. EXPECT_GT(rejecting_calls, 0);
  15692. auto res = accepting.Get("/test");
  15693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15694. EXPECT_GT(accepting_calls, 0);
  15695. }
  15696. // A verifier replaced while a handshake runs it lives until it returns.
  15697. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15698. using namespace httplib::tls;
  15699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15700. ASSERT_TRUE(svr.is_valid());
  15701. svr.Get("/test", [](const Request &, Response &res) {
  15702. res.set_content("ok", "text/plain");
  15703. });
  15704. auto port = svr.bind_to_any_port(HOST);
  15705. thread t([&]() { svr.listen_after_bind(); });
  15706. auto se = detail::scope_exit([&] {
  15707. svr.stop();
  15708. t.join();
  15709. });
  15710. svr.wait_until_ready();
  15711. SSLClient cli(HOST, port);
  15712. cli.enable_server_certificate_verification(false);
  15713. std::promise<void> entered;
  15714. std::promise<void> replaced;
  15715. auto replaced_future = replaced.get_future();
  15716. auto first_call = true;
  15717. // Long enough to live on the heap
  15718. std::string expected(64, 'v');
  15719. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15720. if (first_call) {
  15721. first_call = false;
  15722. entered.set_value();
  15723. replaced_future.wait();
  15724. }
  15725. return expected == std::string(64, 'v');
  15726. });
  15727. thread request([&]() {
  15728. auto res = cli.Get("/test");
  15729. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15730. });
  15731. entered.get_future().wait();
  15732. cli.set_server_certificate_verifier(
  15733. [](const VerifyContext &) { return true; });
  15734. replaced.set_value();
  15735. request.join();
  15736. }
  15737. // VerifyContext::session is the same handle the other tls:: functions take.
  15738. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15739. using namespace httplib::tls;
  15740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15741. ASSERT_TRUE(svr.is_valid());
  15742. svr.Get("/test", [](const Request &, Response &res) {
  15743. res.set_content("ok", "text/plain");
  15744. });
  15745. auto port = svr.bind_to_any_port(HOST);
  15746. thread t([&]() { svr.listen_after_bind(); });
  15747. auto se = detail::scope_exit([&] {
  15748. svr.stop();
  15749. t.join();
  15750. });
  15751. svr.wait_until_ready();
  15752. SSLClient cli(HOST, port);
  15753. cli.enable_server_certificate_verification(false);
  15754. session_t verifier_session = nullptr;
  15755. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15756. verifier_session = ctx.session;
  15757. return true;
  15758. });
  15759. session_t session_verifier_session = nullptr;
  15760. cli.set_session_verifier([&](session_t session) {
  15761. session_verifier_session = session;
  15762. return SSLVerifierResponse::NoDecisionMade;
  15763. });
  15764. auto res = cli.Get("/test");
  15765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15766. EXPECT_NE(nullptr, verifier_session);
  15767. EXPECT_EQ(session_verifier_session, verifier_session);
  15768. }
  15769. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15770. using httplib::tls::TlsError;
  15771. // Test that verify_error_to_string returns empty for success
  15772. std::string success_str = TlsError::verify_error_to_string(0);
  15773. EXPECT_TRUE(success_str.empty());
  15774. // Test that verify_error_to_string returns non-empty for error codes
  15775. // Using a common error code (certificate expired)
  15776. std::string error_str =
  15777. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15778. EXPECT_FALSE(error_str.empty());
  15779. }
  15780. TEST(SessionVerifierTest, CertificateAccepted) {
  15781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15782. ASSERT_TRUE(svr.is_valid());
  15783. svr.Get("/test", [](const Request &, Response &res) {
  15784. res.set_content("ok", "text/plain");
  15785. });
  15786. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15787. auto se = detail::scope_exit([&] {
  15788. svr.stop();
  15789. t.join();
  15790. });
  15791. svr.wait_until_ready();
  15792. SSLClient cli(HOST, PORT);
  15793. cli.enable_server_certificate_verification(false);
  15794. cli.set_connection_timeout(30);
  15795. bool callback_called = false;
  15796. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15797. EXPECT_NE(session, nullptr);
  15798. callback_called = true;
  15799. return SSLVerifierResponse::CertificateAccepted;
  15800. });
  15801. auto res = cli.Get("/test");
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. EXPECT_EQ(200, res->status);
  15804. EXPECT_TRUE(callback_called);
  15805. }
  15806. TEST(SessionVerifierTest, CertificateRejected) {
  15807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15808. ASSERT_TRUE(svr.is_valid());
  15809. svr.Get("/test", [](const Request &, Response &res) {
  15810. res.set_content("ok", "text/plain");
  15811. });
  15812. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15813. auto se = detail::scope_exit([&] {
  15814. svr.stop();
  15815. t.join();
  15816. });
  15817. svr.wait_until_ready();
  15818. SSLClient cli(HOST, PORT);
  15819. cli.enable_server_certificate_verification(false);
  15820. cli.set_connection_timeout(30);
  15821. bool callback_called = false;
  15822. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15823. EXPECT_NE(session, nullptr);
  15824. callback_called = true;
  15825. return SSLVerifierResponse::CertificateRejected;
  15826. });
  15827. auto res = cli.Get("/test");
  15828. EXPECT_FALSE(res);
  15829. EXPECT_TRUE(callback_called);
  15830. }
  15831. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15833. ASSERT_TRUE(svr.is_valid());
  15834. svr.Get("/test", [](const Request &, Response &res) {
  15835. res.set_content("ok", "text/plain");
  15836. });
  15837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15838. auto se = detail::scope_exit([&] {
  15839. svr.stop();
  15840. t.join();
  15841. });
  15842. svr.wait_until_ready();
  15843. // NoDecisionMade with verification disabled should succeed (no default check)
  15844. SSLClient cli(HOST, PORT);
  15845. cli.enable_server_certificate_verification(false);
  15846. cli.set_connection_timeout(30);
  15847. bool callback_called = false;
  15848. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15849. EXPECT_NE(session, nullptr);
  15850. callback_called = true;
  15851. return SSLVerifierResponse::NoDecisionMade;
  15852. });
  15853. auto res = cli.Get("/test");
  15854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15855. EXPECT_EQ(200, res->status);
  15856. EXPECT_TRUE(callback_called);
  15857. }
  15858. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15860. ASSERT_TRUE(svr.is_valid());
  15861. svr.Get("/test", [](const Request &, Response &res) {
  15862. res.set_content("ok", "text/plain");
  15863. });
  15864. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15865. auto se = detail::scope_exit([&] {
  15866. svr.stop();
  15867. t.join();
  15868. });
  15869. svr.wait_until_ready();
  15870. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15871. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15872. // so we only check that the request fails, not whether the callback was
  15873. // called.
  15874. SSLClient cli(HOST, PORT);
  15875. cli.enable_server_certificate_verification(true);
  15876. cli.set_connection_timeout(30);
  15877. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15878. EXPECT_NE(session, nullptr);
  15879. return SSLVerifierResponse::NoDecisionMade;
  15880. });
  15881. auto res = cli.Get("/test");
  15882. EXPECT_FALSE(res);
  15883. }
  15884. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15885. // Test SSL server using PemMemory constructor with client CA certificates
  15886. // Read PEM files
  15887. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15888. read_file(SERVER_CERT_FILE, server_cert_pem);
  15889. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15890. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15891. // Create SSLServer with PemMemory constructor including client CA
  15892. SSLServer::PemMemory server_pem = {
  15893. server_cert_pem.c_str(),
  15894. server_cert_pem.size(),
  15895. server_key_pem.c_str(),
  15896. server_key_pem.size(),
  15897. client_ca_pem.c_str(),
  15898. client_ca_pem.size(),
  15899. nullptr // no password for server key
  15900. };
  15901. SSLServer svr(server_pem);
  15902. ASSERT_TRUE(svr.is_valid());
  15903. // No SSL error should be recorded for valid setup
  15904. EXPECT_EQ(0, svr.ssl_last_error());
  15905. // Set up server endpoints
  15906. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15907. res.set_content("ok", "text/plain");
  15908. });
  15909. // Start server in a thread
  15910. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15911. svr.wait_until_ready();
  15912. // Connect with client certificate (using constructor with paths)
  15913. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15914. cli.enable_server_certificate_verification(false);
  15915. auto res = cli.Get("/test-pem-ca");
  15916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15917. EXPECT_EQ(200, res->status);
  15918. EXPECT_EQ("ok", res->body);
  15919. svr.stop();
  15920. server_thread.join();
  15921. }
  15922. #endif
  15923. #ifdef _WIN32
  15924. TEST(CleanupTest, WSACleanup) {
  15925. int ret = WSACleanup();
  15926. ASSERT_EQ(0, ret);
  15927. }
  15928. #endif
  15929. #ifndef CPPHTTPLIB_SSL_ENABLED
  15930. TEST(NoSSLSupport, SimpleInterface) {
  15931. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15932. }
  15933. #endif
  15934. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15935. TEST(InvalidScheme, SimpleInterface) {
  15936. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15937. }
  15938. #endif
  15939. TEST(NoScheme, SimpleInterface) {
  15940. Client cli("yahoo.com:80");
  15941. ASSERT_TRUE(cli.is_valid());
  15942. }
  15943. TEST(SendAPI, SimpleInterface_Online) {
  15944. Client cli("http://yahoo.com");
  15945. Request req;
  15946. req.method = "GET";
  15947. req.path = "/";
  15948. auto res = cli.send(req);
  15949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15950. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15951. }
  15952. TEST(SendAPI, WithParamsInRequest) {
  15953. Server svr;
  15954. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15955. EXPECT_TRUE(req.has_param("test"));
  15956. EXPECT_EQ("test_value", req.get_param_value("test"));
  15957. });
  15958. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15959. auto se = detail::scope_exit([&] {
  15960. svr.stop();
  15961. t.join();
  15962. ASSERT_FALSE(svr.is_running());
  15963. });
  15964. svr.wait_until_ready();
  15965. Client cli(HOST, PORT);
  15966. {
  15967. Request req;
  15968. req.method = "GET";
  15969. req.path = "/";
  15970. req.params.emplace("test", "test_value");
  15971. auto res = cli.send(req);
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. }
  15974. {
  15975. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15977. }
  15978. }
  15979. TEST(ClientImplMethods, GetSocketTest) {
  15980. httplib::Server svr;
  15981. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15982. res.status = StatusCode::OK_200;
  15983. });
  15984. auto port = svr.bind_to_any_port("127.0.0.1");
  15985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15986. auto se = detail::scope_exit([&] {
  15987. svr.stop();
  15988. thread.join();
  15989. ASSERT_FALSE(svr.is_running());
  15990. });
  15991. svr.wait_until_ready();
  15992. {
  15993. httplib::Client cli("127.0.0.1", port);
  15994. cli.set_keep_alive(true);
  15995. // Use the behavior of cpp-httplib of opening the connection
  15996. // only when the first request happens. If that changes,
  15997. // this test would be obsolete.
  15998. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15999. // This also implicitly tests the server. But other tests would fail much
  16000. // earlier than this one to be considered.
  16001. auto res = cli.Get("/");
  16002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16003. EXPECT_EQ(StatusCode::OK_200, res->status);
  16004. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  16005. }
  16006. }
  16007. #ifdef CPPHTTPLIB_SSL_ENABLED
  16008. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  16009. Client cli("http://yahoo.com");
  16010. auto res = cli.Get("/");
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16013. cli.set_follow_location(true);
  16014. res = cli.Get("/");
  16015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16016. EXPECT_EQ(StatusCode::OK_200, res->status);
  16017. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16018. }
  16019. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  16020. Client cli("https://yahoo.com");
  16021. auto res = cli.Get("/");
  16022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16024. cli.set_follow_location(true);
  16025. res = cli.Get("/");
  16026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16027. EXPECT_EQ(StatusCode::OK_200, res->status);
  16028. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16029. }
  16030. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  16031. Client cli("https://yahoo.com");
  16032. auto res = cli.Get("/");
  16033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16034. ASSERT_FALSE(!res);
  16035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16036. ASSERT_FALSE(res == nullptr);
  16037. ASSERT_TRUE(res != nullptr);
  16038. EXPECT_EQ(Error::Success, res.error());
  16039. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  16040. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  16041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16042. cli.set_follow_location(true);
  16043. res = cli.Get("/");
  16044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16045. EXPECT_EQ(Error::Success, res.error());
  16046. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  16047. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  16048. EXPECT_EQ(StatusCode::OK_200, res->status);
  16049. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16050. }
  16051. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16052. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  16053. Client cli("https://cdnjs.cloudflare.com");
  16054. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  16055. Headers{{"Accept-Encoding", "br"}});
  16056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16057. EXPECT_EQ(StatusCode::OK_200, res->status);
  16058. EXPECT_EQ(287630U, res->body.size());
  16059. EXPECT_EQ("application/javascript; charset=utf-8",
  16060. res->get_header_value("Content-Type"));
  16061. }
  16062. #endif
  16063. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  16064. #undef REDIR_HOST // Silence compiler warning
  16065. #define REDIR_HOST "https://httpbingo.org"
  16066. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  16067. Client cli(REDIR_HOST);
  16068. cli.set_follow_location(true);
  16069. auto res = retry_service_failures([&] {
  16070. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  16071. });
  16072. SKIP_ON_SERVICE_FAILURE(res);
  16073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16074. EXPECT_EQ(StatusCode::OK_200, res->status);
  16075. }
  16076. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  16077. Client cli(REDIR_HOST);
  16078. cli.set_follow_location(true);
  16079. Params params;
  16080. params.emplace("url", "http://example.com");
  16081. params.emplace("status_code", "302");
  16082. auto res = retry_service_failures(
  16083. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  16084. SKIP_ON_SERVICE_FAILURE(res);
  16085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16086. EXPECT_EQ(StatusCode::OK_200, res->status);
  16087. }
  16088. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  16089. Client cli(REDIR_HOST);
  16090. cli.set_follow_location(true);
  16091. Params params;
  16092. params.emplace("url", "http://example.com");
  16093. auto res = retry_service_failures([&] {
  16094. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  16095. });
  16096. SKIP_ON_SERVICE_FAILURE(res);
  16097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16098. EXPECT_EQ(StatusCode::OK_200, res->status);
  16099. }
  16100. TEST(HttpToHttpsRedirectTest, CertFile) {
  16101. auto ssl_port = PORT + 1;
  16102. Server svr;
  16103. ASSERT_TRUE(svr.is_valid());
  16104. svr.Get("/index", [&](const Request &, Response &res) {
  16105. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16106. "/index");
  16107. svr.stop();
  16108. });
  16109. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16110. ASSERT_TRUE(ssl_svr.is_valid());
  16111. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  16112. res.set_content("test", "text/plain");
  16113. ssl_svr.stop();
  16114. });
  16115. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16116. thread t2 =
  16117. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  16118. auto se = detail::scope_exit([&] {
  16119. t2.join();
  16120. t.join();
  16121. ASSERT_FALSE(svr.is_running());
  16122. });
  16123. svr.wait_until_ready();
  16124. ssl_svr.wait_until_ready();
  16125. Client cli("127.0.0.1", PORT);
  16126. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16127. cli.enable_server_certificate_verification(true);
  16128. cli.set_follow_location(true);
  16129. cli.set_connection_timeout(30);
  16130. auto res = cli.Get("/index");
  16131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16132. ASSERT_EQ(StatusCode::OK_200, res->status);
  16133. }
  16134. TEST(UppercaseSchemeTest, UsesTLS) {
  16135. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16136. ASSERT_TRUE(ssl_svr.is_valid());
  16137. ssl_svr.Get("/index", [](const Request &, Response &res) {
  16138. res.set_content("test", "text/plain");
  16139. });
  16140. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  16141. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  16142. Server svr;
  16143. svr.Get("/index", [&](const Request &, Response &res) {
  16144. res.set_redirect(https_url + "/index");
  16145. });
  16146. auto port = svr.bind_to_any_port("127.0.0.1");
  16147. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  16148. auto t2 = thread([&] { svr.listen_after_bind(); });
  16149. auto se = detail::scope_exit([&] {
  16150. svr.stop();
  16151. ssl_svr.stop();
  16152. t2.join();
  16153. t.join();
  16154. });
  16155. ssl_svr.wait_until_ready();
  16156. svr.wait_until_ready();
  16157. {
  16158. Client cli(https_url);
  16159. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16160. auto res = cli.Get("/index");
  16161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16162. EXPECT_EQ("test", res->body);
  16163. }
  16164. {
  16165. Client cli("127.0.0.1", port);
  16166. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16167. cli.set_follow_location(true);
  16168. auto res = cli.Get("/index");
  16169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16170. EXPECT_EQ("test", res->body);
  16171. }
  16172. }
  16173. TEST(SSLClientRedirectTest, CertFile) {
  16174. auto ssl_port = PORT + 1;
  16175. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16176. ASSERT_TRUE(ssl_svr1.is_valid());
  16177. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16178. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16179. "/index");
  16180. ssl_svr1.stop();
  16181. });
  16182. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16183. ASSERT_TRUE(ssl_svr2.is_valid());
  16184. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16185. res.set_content("test", "text/plain");
  16186. ssl_svr2.stop();
  16187. });
  16188. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16189. thread t2 =
  16190. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16191. auto se = detail::scope_exit([&] {
  16192. t2.join();
  16193. t.join();
  16194. ASSERT_FALSE(ssl_svr1.is_running());
  16195. });
  16196. ssl_svr1.wait_until_ready();
  16197. ssl_svr2.wait_until_ready();
  16198. SSLClient cli("127.0.0.1", PORT);
  16199. std::string cert;
  16200. read_file(SERVER_CERT2_FILE, cert);
  16201. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16202. cli.enable_server_certificate_verification(true);
  16203. cli.set_follow_location(true);
  16204. cli.set_connection_timeout(30);
  16205. auto res = cli.Get("/index");
  16206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16207. ASSERT_EQ(StatusCode::OK_200, res->status);
  16208. }
  16209. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16210. // another port, so the client follows it with a new client.
  16211. static Result GetThroughTlsRedirectToDifferentPort(
  16212. const std::function<void(SSLClient &)> &setup,
  16213. const char *target_cert = SERVER_CERT2_FILE,
  16214. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16215. auto ssl_port = PORT + 1;
  16216. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16217. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16218. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16219. "/index");
  16220. });
  16221. SSLServer ssl_svr2(target_cert, target_key);
  16222. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16223. res.set_content("test", "text/plain");
  16224. });
  16225. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16226. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16227. auto se = detail::scope_exit([&] {
  16228. ssl_svr2.stop();
  16229. ssl_svr1.stop();
  16230. t2.join();
  16231. t.join();
  16232. });
  16233. ssl_svr1.wait_until_ready();
  16234. ssl_svr2.wait_until_ready();
  16235. SSLClient cli("127.0.0.1", PORT);
  16236. cli.set_follow_location(true);
  16237. cli.set_connection_timeout(30);
  16238. setup(cli);
  16239. return cli.Get("/index");
  16240. }
  16241. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16242. auto calls = 0;
  16243. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16244. cli.enable_server_certificate_verification(false);
  16245. // Accept the first server only.
  16246. cli.set_session_verifier([&](tls::session_t) {
  16247. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16248. : SSLVerifierResponse::CertificateRejected;
  16249. });
  16250. });
  16251. ASSERT_FALSE(res);
  16252. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16253. EXPECT_EQ(2, calls);
  16254. }
  16255. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16256. std::string pinned;
  16257. auto res = GetThroughTlsRedirectToDifferentPort(
  16258. [&](SSLClient &cli) {
  16259. cli.enable_server_certificate_verification(false);
  16260. // Pin the first certificate seen.
  16261. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16262. if (pinned.empty()) { pinned = ctx.serial(); }
  16263. return ctx.serial() == pinned;
  16264. });
  16265. },
  16266. // A certificate other than the first server's.
  16267. SERVER_CERT_FILE);
  16268. EXPECT_FALSE(res);
  16269. EXPECT_FALSE(pinned.empty());
  16270. }
  16271. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16272. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16273. std::string cert;
  16274. read_file(SERVER_CERT2_FILE, cert);
  16275. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16276. });
  16277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16278. EXPECT_EQ(StatusCode::OK_200, res->status);
  16279. }
  16280. // The target's certificate is signed by the root CA, which the first server's
  16281. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16282. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16283. auto res = GetThroughTlsRedirectToDifferentPort(
  16284. [](SSLClient &cli) {
  16285. std::string root_ca, cert;
  16286. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16287. read_file(SERVER_CERT2_FILE, cert);
  16288. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16289. cli.load_ca_cert_store(cert.data(), cert.size());
  16290. cli.enable_server_hostname_verification(false);
  16291. },
  16292. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16294. EXPECT_EQ(StatusCode::OK_200, res->status);
  16295. }
  16296. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16297. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16298. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16299. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16300. auto res = GetThroughTlsRedirectToDifferentPort(
  16301. [](SSLClient &cli) {
  16302. std::string root_ca, cert;
  16303. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16304. read_file(SERVER_CERT2_FILE, cert);
  16305. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16306. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16307. cli.enable_server_hostname_verification(false);
  16308. },
  16309. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16310. ASSERT_FALSE(res);
  16311. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16312. }
  16313. #endif
  16314. #endif
  16315. #ifdef CPPHTTPLIB_SSL_ENABLED
  16316. // Test that set_ca_cert_store() skips system certs (consistent with
  16317. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16318. // should be trusted - system certs should NOT be loaded.
  16319. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16320. // Load a specific cert that is NOT a system CA cert
  16321. std::string cert;
  16322. read_file(SERVER_CERT2_FILE, cert);
  16323. SSLClient cli("google.com");
  16324. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16325. cli.enable_server_certificate_verification(true);
  16326. // This should FAIL because:
  16327. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16328. // 2. System certs should NOT be loaded when custom store is set
  16329. // If system certs WERE loaded, this would succeed
  16330. auto res = cli.Get("/");
  16331. ASSERT_FALSE(res);
  16332. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16333. }
  16334. // Same as above, but through the native store handle path. Regression test:
  16335. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16336. // merged system certs into the user-provided store.
  16337. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16338. std::string cert;
  16339. read_file(SERVER_CERT2_FILE, cert);
  16340. SSLClient cli("google.com");
  16341. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16342. cli.enable_server_certificate_verification(true);
  16343. auto res = cli.Get("/");
  16344. ASSERT_FALSE(res);
  16345. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16346. }
  16347. // A custom store set via the native handle must still verify a server whose
  16348. // cert it does contain.
  16349. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16350. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16351. ASSERT_TRUE(svr.is_valid());
  16352. svr.Get("/test", [&](const Request &, Response &res) {
  16353. res.set_content("test", "text/plain");
  16354. });
  16355. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16356. auto se = detail::scope_exit([&] {
  16357. svr.stop();
  16358. t.join();
  16359. ASSERT_FALSE(svr.is_running());
  16360. });
  16361. svr.wait_until_ready();
  16362. SSLClient cli("127.0.0.1", PORT);
  16363. std::string cert;
  16364. read_file(SERVER_CERT2_FILE, cert);
  16365. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16366. cli.enable_server_certificate_verification(true);
  16367. cli.set_connection_timeout(30);
  16368. auto res = cli.Get("/test");
  16369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16370. ASSERT_EQ(StatusCode::OK_200, res->status);
  16371. }
  16372. // CA certs loaded through the universal Client must be transferred to the
  16373. // client created internally for following an HTTPS redirect. Regression test:
  16374. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16375. // the CA data for redirect transfer.
  16376. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16377. auto ssl_port = PORT + 1;
  16378. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16379. ASSERT_TRUE(ssl_svr1.is_valid());
  16380. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16381. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16382. "/index");
  16383. });
  16384. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16385. ASSERT_TRUE(ssl_svr2.is_valid());
  16386. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16387. res.set_content("test", "text/plain");
  16388. });
  16389. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16390. thread t2 =
  16391. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16392. auto se = detail::scope_exit([&] {
  16393. ssl_svr2.stop();
  16394. ssl_svr1.stop();
  16395. t2.join();
  16396. t.join();
  16397. ASSERT_FALSE(ssl_svr1.is_running());
  16398. });
  16399. ssl_svr1.wait_until_ready();
  16400. ssl_svr2.wait_until_ready();
  16401. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16402. std::string cert;
  16403. read_file(SERVER_CERT2_FILE, cert);
  16404. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16405. cli.enable_server_certificate_verification(true);
  16406. cli.set_follow_location(true);
  16407. cli.set_connection_timeout(30);
  16408. auto res = cli.Get("/index");
  16409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16410. ASSERT_EQ(StatusCode::OK_200, res->status);
  16411. }
  16412. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16413. // so a host signed by a system CA verifies even though a custom CA is set
  16414. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16415. std::string cert;
  16416. read_file(SERVER_CERT2_FILE, cert);
  16417. SSLClient cli("google.com");
  16418. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16419. cli.enable_system_ca(true);
  16420. cli.enable_server_certificate_verification(true);
  16421. auto res = cli.Get("/");
  16422. // Any status: Google may redirect or rate-limit CI runners.
  16423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16424. }
  16425. // The custom CA remains effective when combined with the system CA
  16426. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16427. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16428. ASSERT_TRUE(svr.is_valid());
  16429. svr.Get("/test", [&](const Request &, Response &res) {
  16430. res.set_content("test", "text/plain");
  16431. });
  16432. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16433. auto se = detail::scope_exit([&] {
  16434. svr.stop();
  16435. t.join();
  16436. ASSERT_FALSE(svr.is_running());
  16437. });
  16438. svr.wait_until_ready();
  16439. SSLClient cli("127.0.0.1", PORT);
  16440. std::string cert;
  16441. read_file(SERVER_CERT2_FILE, cert);
  16442. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16443. cli.enable_system_ca(true);
  16444. cli.enable_server_certificate_verification(true);
  16445. cli.set_connection_timeout(30);
  16446. auto res = cli.Get("/test");
  16447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16448. ASSERT_EQ(StatusCode::OK_200, res->status);
  16449. }
  16450. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16451. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16452. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16453. static CFDictionaryRef
  16454. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16455. const SecTrustSettingsResult *result) {
  16456. auto constraint =
  16457. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16458. &kCFTypeDictionaryValueCallBacks);
  16459. if (policy) {
  16460. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16461. }
  16462. if (policy_string) {
  16463. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16464. kCFStringEncodingUTF8);
  16465. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16466. CFRelease(str);
  16467. }
  16468. if (result) {
  16469. auto number_value = static_cast<SInt32>(*result);
  16470. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16471. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16472. CFRelease(number);
  16473. }
  16474. return constraint;
  16475. }
  16476. static SecTrustSettingsResult
  16477. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16478. auto trust_settings =
  16479. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16480. for (auto constraint : constraints) {
  16481. CFArrayAppendValue(trust_settings, constraint);
  16482. CFRelease(constraint);
  16483. }
  16484. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16485. CFRelease(trust_settings);
  16486. return result;
  16487. }
  16488. // The system CA loader takes a Keychain certificate as a trusted root only
  16489. // when its Trust Settings say so for SSL, not merely because it has some.
  16490. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16491. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16492. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16493. const auto deny = kSecTrustSettingsResultDeny;
  16494. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16495. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16496. auto x509_policy = SecPolicyCreateBasicX509();
  16497. // "Always Trust", which stores no constraint at all
  16498. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16499. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16500. ssl_trust_settings_result(
  16501. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16502. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16503. ssl_trust_settings_result(
  16504. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16505. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16506. ssl_trust_settings_result(
  16507. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16508. // "Never Trust", for everything or for SSL
  16509. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16510. ssl_trust_settings_result(
  16511. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16512. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16513. ssl_trust_settings_result(
  16514. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16515. // Trusted for another policy, for one host, or not at all
  16516. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16517. ssl_trust_settings_result(
  16518. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16519. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16520. ssl_trust_settings_result({make_usage_constraint(
  16521. ssl_policy, "www.example.com", &trust_root)}));
  16522. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16523. ssl_trust_settings_result(
  16524. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16525. // The first constraint that applies to SSL decides
  16526. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16527. ssl_trust_settings_result(
  16528. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16529. make_usage_constraint(nullptr, nullptr, &deny)}));
  16530. CFRelease(x509_policy);
  16531. CFRelease(ssl_policy);
  16532. }
  16533. #endif
  16534. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16535. // skip chain verification entirely (only the certificate identity was
  16536. // checked), so a server presenting an untrusted certificate with a matching
  16537. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16538. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16539. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16540. ASSERT_TRUE(svr.is_valid());
  16541. svr.Get("/test", [&](const Request &, Response &res) {
  16542. res.set_content("test", "text/plain");
  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. SSLClient cli("127.0.0.1", PORT);
  16552. std::string cert;
  16553. // A trusted CA that did not sign the server certificate. The server cert
  16554. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16555. // this connection.
  16556. read_file(CLIENT_CA_CERT_FILE, cert);
  16557. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16558. cli.enable_server_certificate_verification(true);
  16559. cli.set_connection_timeout(30);
  16560. auto res = cli.Get("/test");
  16561. ASSERT_FALSE(res);
  16562. }
  16563. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16564. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16565. // CA that failed to come through fails verification instead of trusting them.
  16566. // (wolfSSL does not list the system CAs it loaded.)
  16567. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16568. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16569. ASSERT_TRUE(svr.is_valid());
  16570. auto port = svr.bind_to_any_port("127.0.0.1");
  16571. ASSERT_LT(0, port);
  16572. thread t = thread([&] { svr.listen_after_bind(); });
  16573. auto se = detail::scope_exit([&] {
  16574. svr.stop();
  16575. t.join();
  16576. ASSERT_FALSE(svr.is_running());
  16577. });
  16578. svr.wait_until_ready();
  16579. // The CAs a client trusts once its first request has loaded them
  16580. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16581. Client cli("https://127.0.0.1:" + std::to_string(port));
  16582. setup(cli);
  16583. cli.Get("/");
  16584. return tls::get_ca_names(cli.tls_context()).size();
  16585. };
  16586. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16587. EXPECT_EQ(0u,
  16588. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16589. }
  16590. #endif
  16591. // A TLS setting changed between requests applies to the next one, not just to
  16592. // the next connection
  16593. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16594. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16595. ASSERT_TRUE(svr.is_valid());
  16596. svr.Get("/", [](const Request &req, Response &res) {
  16597. res.set_content(std::to_string(req.remote_port), "text/plain");
  16598. });
  16599. auto port = svr.bind_to_any_port("127.0.0.1");
  16600. ASSERT_LT(0, port);
  16601. thread t = thread([&] { svr.listen_after_bind(); });
  16602. auto se = detail::scope_exit([&] {
  16603. svr.stop();
  16604. t.join();
  16605. ASSERT_FALSE(svr.is_running());
  16606. });
  16607. svr.wait_until_ready();
  16608. SSLClient cli("127.0.0.1", port);
  16609. cli.set_keep_alive(true);
  16610. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16611. cli.enable_server_certificate_verification(false);
  16612. // The port the request went out from, so a new one means a new connection
  16613. auto client_port = [&] {
  16614. auto res = cli.Get("/");
  16615. return res ? res->body : std::string();
  16616. };
  16617. auto last = client_port();
  16618. ASSERT_FALSE(last.empty());
  16619. // Setting a value it already has keeps the connection
  16620. cli.enable_server_certificate_verification(false);
  16621. cli.enable_server_hostname_verification(true);
  16622. EXPECT_EQ(last, client_port());
  16623. cli.enable_server_certificate_verification(true);
  16624. auto res = cli.Get("/");
  16625. EXPECT_FALSE(res);
  16626. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16627. std::string ca;
  16628. read_file(SERVER_CERT2_FILE, ca);
  16629. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16630. last = client_port();
  16631. ASSERT_FALSE(last.empty());
  16632. std::vector<std::function<void()>> setters = {
  16633. [&] { cli.enable_server_hostname_verification(false); },
  16634. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16635. [&] {
  16636. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16637. },
  16638. [&] {
  16639. cli.set_server_certificate_verifier(
  16640. [](const tls::VerifyContext &) { return true; });
  16641. },
  16642. [&] {
  16643. cli.set_session_verifier(
  16644. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16645. },
  16646. };
  16647. for (const auto &setter : setters) {
  16648. setter();
  16649. auto next = client_port();
  16650. ASSERT_FALSE(next.empty());
  16651. EXPECT_NE(last, next);
  16652. last = next;
  16653. }
  16654. cli.set_session_verifier(
  16655. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16656. auto handle = cli.open_stream("GET", "/");
  16657. EXPECT_FALSE(handle.is_valid());
  16658. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16659. }
  16660. // A PEM given to create_ca_store() needs no NUL after it
  16661. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16662. std::string pem;
  16663. read_file(SERVER_CERT2_FILE, pem);
  16664. auto buf = pem + "X";
  16665. auto store = tls::create_ca_store(buf.data(), pem.size());
  16666. EXPECT_TRUE(store != nullptr);
  16667. SSLClient cli("localhost");
  16668. cli.set_ca_cert_store(store);
  16669. }
  16670. // enable_system_ca(false) prevents system CA loading entirely
  16671. TEST(SSLClientTest, DisableSystemCa_Online) {
  16672. SSLClient cli("google.com");
  16673. cli.enable_system_ca(false);
  16674. cli.enable_server_certificate_verification(true);
  16675. auto res = cli.Get("/");
  16676. ASSERT_FALSE(res);
  16677. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16678. // itself when the CA chain is empty
  16679. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16680. res.error() == Error::SSLConnection);
  16681. }
  16682. // The universal Client forwards enable_system_ca()
  16683. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16684. std::string cert;
  16685. read_file(SERVER_CERT2_FILE, cert);
  16686. Client cli("https://google.com");
  16687. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16688. cli.enable_system_ca(true);
  16689. cli.enable_server_certificate_verification(true);
  16690. auto res = cli.Get("/");
  16691. // Any status: Google may redirect or rate-limit CI runners.
  16692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16693. }
  16694. // The system CA policy must carry over to the client created internally for
  16695. // following a cross-host HTTPS redirect
  16696. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16697. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16698. ASSERT_TRUE(svr.is_valid());
  16699. svr.Get("/index", [&](const Request &, Response &res) {
  16700. res.set_redirect("https://www.google.com/");
  16701. });
  16702. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16703. auto se = detail::scope_exit([&] {
  16704. svr.stop();
  16705. t.join();
  16706. ASSERT_FALSE(svr.is_running());
  16707. });
  16708. svr.wait_until_ready();
  16709. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16710. std::string cert;
  16711. read_file(SERVER_CERT2_FILE, cert);
  16712. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16713. cli.enable_system_ca(true);
  16714. cli.enable_server_certificate_verification(true);
  16715. cli.set_follow_location(true);
  16716. cli.set_connection_timeout(30);
  16717. // Receiving any response proves the redirect client completed the TLS
  16718. // handshake with a system-CA-signed host
  16719. auto res = cli.Get("/index");
  16720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16721. }
  16722. TEST(MultipartFormDataTest, LargeData) {
  16723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16724. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16725. const ContentReader &content_reader) {
  16726. if (req.is_multipart_form_data()) {
  16727. std::vector<FormData> items;
  16728. content_reader(
  16729. [&](const FormData &file) {
  16730. items.push_back(file);
  16731. return true;
  16732. },
  16733. [&](const char *data, size_t data_length) {
  16734. items.back().content.append(data, data_length);
  16735. return true;
  16736. });
  16737. EXPECT_TRUE(std::string(items[0].name) == "document");
  16738. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16739. EXPECT_TRUE(items[0].filename == "2MB_data");
  16740. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16741. EXPECT_TRUE(items[1].name == "hello");
  16742. EXPECT_TRUE(items[1].content == "world");
  16743. EXPECT_TRUE(items[1].filename == "");
  16744. EXPECT_TRUE(items[1].content_type == "");
  16745. } else {
  16746. std::string body;
  16747. content_reader([&](const char *data, size_t data_length) {
  16748. body.append(data, data_length);
  16749. return true;
  16750. });
  16751. }
  16752. });
  16753. auto port = svr.bind_to_any_port(HOST);
  16754. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16755. auto se = detail::scope_exit([&] {
  16756. svr.stop();
  16757. t.join();
  16758. ASSERT_FALSE(svr.is_running());
  16759. });
  16760. svr.wait_until_ready();
  16761. {
  16762. std::string data(1024 * 1024 * 2, '.');
  16763. std::stringstream buffer;
  16764. buffer << data;
  16765. SSLClient cli(HOST, port);
  16766. cli.enable_server_certificate_verification(false);
  16767. UploadFormDataItems items{
  16768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16769. {"hello", "world", "", ""},
  16770. };
  16771. auto res = cli.Post("/post", items);
  16772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16773. ASSERT_EQ(StatusCode::OK_200, res->status);
  16774. }
  16775. }
  16776. TEST(MultipartFormDataTest, DataProviderItems) {
  16777. std::random_device seed_gen;
  16778. std::mt19937 random(seed_gen());
  16779. std::string rand1;
  16780. rand1.resize(1000);
  16781. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16782. std::string rand2;
  16783. rand2.resize(3000);
  16784. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16786. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16787. const ContentReader &content_reader) {
  16788. ASSERT_FALSE(req.is_multipart_form_data());
  16789. std::string body;
  16790. content_reader([&](const char *data, size_t data_length) {
  16791. body.append(data, data_length);
  16792. return true;
  16793. });
  16794. EXPECT_EQ(body, "");
  16795. });
  16796. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16797. const ContentReader &content_reader) {
  16798. ASSERT_TRUE(req.is_multipart_form_data());
  16799. std::vector<FormData> items;
  16800. content_reader(
  16801. [&](const FormData &file) {
  16802. items.push_back(file);
  16803. return true;
  16804. },
  16805. [&](const char *data, size_t data_length) {
  16806. items.back().content.append(data, data_length);
  16807. return true;
  16808. });
  16809. ASSERT_TRUE(items.size() == 2);
  16810. EXPECT_EQ(std::string(items[0].name), "name1");
  16811. EXPECT_EQ(items[0].content, "Testing123");
  16812. EXPECT_EQ(items[0].filename, "filename1");
  16813. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16814. EXPECT_EQ(items[1].name, "name2");
  16815. EXPECT_EQ(items[1].content, "Testing456");
  16816. EXPECT_EQ(items[1].filename, "");
  16817. EXPECT_EQ(items[1].content_type, "");
  16818. });
  16819. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16820. const ContentReader &content_reader) {
  16821. ASSERT_TRUE(req.is_multipart_form_data());
  16822. std::vector<FormData> items;
  16823. content_reader(
  16824. [&](const FormData &file) {
  16825. items.push_back(file);
  16826. return true;
  16827. },
  16828. [&](const char *data, size_t data_length) {
  16829. items.back().content.append(data, data_length);
  16830. return true;
  16831. });
  16832. ASSERT_TRUE(items.size() == 2);
  16833. EXPECT_EQ(items[0].name, "name3");
  16834. EXPECT_EQ(items[0].content, rand1);
  16835. EXPECT_EQ(items[0].filename, "filename3");
  16836. EXPECT_EQ(items[0].content_type, "");
  16837. EXPECT_EQ(items[1].name, "name4");
  16838. EXPECT_EQ(items[1].content, rand2);
  16839. EXPECT_EQ(items[1].filename, "filename4");
  16840. EXPECT_EQ(items[1].content_type, "");
  16841. });
  16842. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16843. const ContentReader &content_reader) {
  16844. ASSERT_TRUE(req.is_multipart_form_data());
  16845. std::vector<FormData> items;
  16846. content_reader(
  16847. [&](const FormData &file) {
  16848. items.push_back(file);
  16849. return true;
  16850. },
  16851. [&](const char *data, size_t data_length) {
  16852. items.back().content.append(data, data_length);
  16853. return true;
  16854. });
  16855. ASSERT_TRUE(items.size() == 4);
  16856. EXPECT_EQ(std::string(items[0].name), "name1");
  16857. EXPECT_EQ(items[0].content, "Testing123");
  16858. EXPECT_EQ(items[0].filename, "filename1");
  16859. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16860. EXPECT_EQ(items[1].name, "name2");
  16861. EXPECT_EQ(items[1].content, "Testing456");
  16862. EXPECT_EQ(items[1].filename, "");
  16863. EXPECT_EQ(items[1].content_type, "");
  16864. EXPECT_EQ(items[2].name, "name3");
  16865. EXPECT_EQ(items[2].content, rand1);
  16866. EXPECT_EQ(items[2].filename, "filename3");
  16867. EXPECT_EQ(items[2].content_type, "");
  16868. EXPECT_EQ(items[3].name, "name4");
  16869. EXPECT_EQ(items[3].content, rand2);
  16870. EXPECT_EQ(items[3].filename, "filename4");
  16871. EXPECT_EQ(items[3].content_type, "");
  16872. });
  16873. auto port = svr.bind_to_any_port("localhost");
  16874. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16875. auto se = detail::scope_exit([&] {
  16876. svr.stop();
  16877. t.join();
  16878. ASSERT_FALSE(svr.is_running());
  16879. });
  16880. svr.wait_until_ready();
  16881. {
  16882. SSLClient cli("localhost", port);
  16883. cli.enable_server_certificate_verification(false);
  16884. UploadFormDataItems items{
  16885. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16886. {"name2", "Testing456", "", ""}, // not a file
  16887. };
  16888. {
  16889. auto res = cli.Post("/post-none", {}, {}, {});
  16890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16891. ASSERT_EQ(StatusCode::OK_200, res->status);
  16892. }
  16893. FormDataProviderItems providers;
  16894. {
  16895. auto res =
  16896. cli.Post("/post-items", {}, items, providers); // empty providers
  16897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16898. ASSERT_EQ(StatusCode::OK_200, res->status);
  16899. }
  16900. providers.push_back({"name3",
  16901. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16902. // test the offset is given correctly at each step
  16903. if (!offset)
  16904. sink.os.write(rand1.data(), 30);
  16905. else if (offset == 30)
  16906. sink.os.write(rand1.data() + 30, 300);
  16907. else if (offset == 330)
  16908. sink.os.write(rand1.data() + 330, 670);
  16909. else if (offset == rand1.size())
  16910. sink.done();
  16911. return true;
  16912. },
  16913. "filename3",
  16914. {}});
  16915. providers.push_back({"name4",
  16916. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16917. // test the offset is given correctly at each step
  16918. if (!offset)
  16919. sink.os.write(rand2.data(), 2000);
  16920. else if (offset == 2000)
  16921. sink.os.write(rand2.data() + 2000, 1);
  16922. else if (offset == 2001)
  16923. sink.os.write(rand2.data() + 2001, 999);
  16924. else if (offset == rand2.size())
  16925. sink.done();
  16926. return true;
  16927. },
  16928. "filename4",
  16929. {}});
  16930. {
  16931. auto res = cli.Post("/post-providers", {}, {}, providers);
  16932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16933. ASSERT_EQ(StatusCode::OK_200, res->status);
  16934. }
  16935. {
  16936. auto res = cli.Post("/post-both", {}, items, providers);
  16937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16938. ASSERT_EQ(StatusCode::OK_200, res->status);
  16939. }
  16940. }
  16941. }
  16942. TEST(MultipartFormDataTest, BadHeader) {
  16943. Server svr;
  16944. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16945. res.set_content("ok", "text/plain");
  16946. });
  16947. thread t = thread([&] { svr.listen(HOST, PORT); });
  16948. auto se = detail::scope_exit([&] {
  16949. svr.stop();
  16950. t.join();
  16951. ASSERT_FALSE(svr.is_running());
  16952. });
  16953. svr.wait_until_ready();
  16954. const std::string body =
  16955. "This is the preamble. It is to be ignored, though it\r\n"
  16956. "is a handy place for composition agents to include an\r\n"
  16957. "explanatory note to non-MIME conformant readers.\r\n"
  16958. "\r\n"
  16959. "\r\n"
  16960. "--simple boundary\r\n"
  16961. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16962. ": BAD...\r\n"
  16963. "\r\n"
  16964. "value1\r\n"
  16965. "--simple boundary\r\n"
  16966. "Content-Disposition: form-data; name=\"field2\"; "
  16967. "filename=\"example.txt\"\r\n"
  16968. "\r\n"
  16969. "value2\r\n"
  16970. "--simple boundary--\r\n"
  16971. "This is the epilogue. It is also to be ignored.\r\n";
  16972. std::string content_type =
  16973. R"(multipart/form-data; boundary="simple boundary")";
  16974. Client cli(HOST, PORT);
  16975. auto res = cli.Post("/post", body, content_type.c_str());
  16976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16977. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16978. }
  16979. TEST(MultipartFormDataTest, WithPreamble) {
  16980. Server svr;
  16981. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16982. res.set_content("ok", "text/plain");
  16983. });
  16984. thread t = thread([&] { svr.listen(HOST, PORT); });
  16985. auto se = detail::scope_exit([&] {
  16986. svr.stop();
  16987. t.join();
  16988. ASSERT_FALSE(svr.is_running());
  16989. });
  16990. svr.wait_until_ready();
  16991. const std::string body =
  16992. "This is the preamble. It is to be ignored, though it\r\n"
  16993. "is a handy place for composition agents to include an\r\n"
  16994. "explanatory note to non-MIME conformant readers.\r\n"
  16995. "\r\n"
  16996. "\r\n"
  16997. "--simple boundary\r\n"
  16998. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16999. "\r\n"
  17000. "value1\r\n"
  17001. "--simple boundary\r\n"
  17002. "Content-Disposition: form-data; name=\"field2\"; "
  17003. "filename=\"example.txt\"\r\n"
  17004. "\r\n"
  17005. "value2\r\n"
  17006. "--simple boundary--\r\n"
  17007. "This is the epilogue. It is also to be ignored.\r\n";
  17008. std::string content_type =
  17009. R"(multipart/form-data; boundary="simple boundary")";
  17010. Client cli(HOST, PORT);
  17011. auto res = cli.Post("/post", body, content_type.c_str());
  17012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17013. EXPECT_EQ(StatusCode::OK_200, res->status);
  17014. }
  17015. TEST(MultipartFormDataTest, PostCustomBoundary) {
  17016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17017. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  17018. const ContentReader &content_reader) {
  17019. if (req.is_multipart_form_data()) {
  17020. std::vector<FormData> items;
  17021. content_reader(
  17022. [&](const FormData &file) {
  17023. items.push_back(file);
  17024. return true;
  17025. },
  17026. [&](const char *data, size_t data_length) {
  17027. items.back().content.append(data, data_length);
  17028. return true;
  17029. });
  17030. EXPECT_TRUE(std::string(items[0].name) == "document");
  17031. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17032. EXPECT_TRUE(items[0].filename == "2MB_data");
  17033. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17034. EXPECT_TRUE(items[1].name == "hello");
  17035. EXPECT_TRUE(items[1].content == "world");
  17036. EXPECT_TRUE(items[1].filename == "");
  17037. EXPECT_TRUE(items[1].content_type == "");
  17038. } else {
  17039. std::string body;
  17040. content_reader([&](const char *data, size_t data_length) {
  17041. body.append(data, data_length);
  17042. return true;
  17043. });
  17044. }
  17045. });
  17046. auto port = svr.bind_to_any_port("localhost");
  17047. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17048. auto se = detail::scope_exit([&] {
  17049. svr.stop();
  17050. t.join();
  17051. ASSERT_FALSE(svr.is_running());
  17052. });
  17053. svr.wait_until_ready();
  17054. {
  17055. std::string data(1024 * 1024 * 2, '.');
  17056. std::stringstream buffer;
  17057. buffer << data;
  17058. SSLClient cli("localhost", port);
  17059. cli.enable_server_certificate_verification(false);
  17060. UploadFormDataItems items{
  17061. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17062. {"hello", "world", "", ""},
  17063. };
  17064. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  17065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17066. ASSERT_EQ(StatusCode::OK_200, res->status);
  17067. }
  17068. }
  17069. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  17070. std::string data(1024 * 1024 * 2, '&');
  17071. std::stringstream buffer;
  17072. buffer << data;
  17073. Client cli("https://localhost:8080");
  17074. UploadFormDataItems items{
  17075. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17076. {"hello", "world", "", ""},
  17077. };
  17078. for (const char &c : " \t\r\n") {
  17079. auto res =
  17080. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  17081. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17082. ASSERT_FALSE(res);
  17083. }
  17084. }
  17085. TEST(MultipartFormDataTest, PutFormData) {
  17086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17087. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  17088. const ContentReader &content_reader) {
  17089. if (req.is_multipart_form_data()) {
  17090. std::vector<FormData> items;
  17091. content_reader(
  17092. [&](const FormData &file) {
  17093. items.push_back(file);
  17094. return true;
  17095. },
  17096. [&](const char *data, size_t data_length) {
  17097. items.back().content.append(data, data_length);
  17098. return true;
  17099. });
  17100. EXPECT_TRUE(std::string(items[0].name) == "document");
  17101. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17102. EXPECT_TRUE(items[0].filename == "2MB_data");
  17103. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17104. EXPECT_TRUE(items[1].name == "hello");
  17105. EXPECT_TRUE(items[1].content == "world");
  17106. EXPECT_TRUE(items[1].filename == "");
  17107. EXPECT_TRUE(items[1].content_type == "");
  17108. } else {
  17109. std::string body;
  17110. content_reader([&](const char *data, size_t data_length) {
  17111. body.append(data, data_length);
  17112. return true;
  17113. });
  17114. }
  17115. });
  17116. auto port = svr.bind_to_any_port("localhost");
  17117. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17118. auto se = detail::scope_exit([&] {
  17119. svr.stop();
  17120. t.join();
  17121. ASSERT_FALSE(svr.is_running());
  17122. });
  17123. svr.wait_until_ready();
  17124. {
  17125. std::string data(1024 * 1024 * 2, '&');
  17126. std::stringstream buffer;
  17127. buffer << data;
  17128. SSLClient cli("localhost", port);
  17129. cli.enable_server_certificate_verification(false);
  17130. UploadFormDataItems items{
  17131. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17132. {"hello", "world", "", ""},
  17133. };
  17134. auto res = cli.Put("/put", items);
  17135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17136. ASSERT_EQ(StatusCode::OK_200, res->status);
  17137. }
  17138. }
  17139. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  17140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17141. svr.Put("/put_customboundary",
  17142. [&](const Request &req, const Response & /*res*/,
  17143. const ContentReader &content_reader) {
  17144. if (req.is_multipart_form_data()) {
  17145. std::vector<FormData> items;
  17146. content_reader(
  17147. [&](const FormData &file) {
  17148. items.push_back(file);
  17149. return true;
  17150. },
  17151. [&](const char *data, size_t data_length) {
  17152. items.back().content.append(data, data_length);
  17153. return true;
  17154. });
  17155. EXPECT_TRUE(std::string(items[0].name) == "document");
  17156. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17157. EXPECT_TRUE(items[0].filename == "2MB_data");
  17158. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17159. EXPECT_TRUE(items[1].name == "hello");
  17160. EXPECT_TRUE(items[1].content == "world");
  17161. EXPECT_TRUE(items[1].filename == "");
  17162. EXPECT_TRUE(items[1].content_type == "");
  17163. } else {
  17164. std::string body;
  17165. content_reader([&](const char *data, size_t data_length) {
  17166. body.append(data, data_length);
  17167. return true;
  17168. });
  17169. }
  17170. });
  17171. auto port = svr.bind_to_any_port("localhost");
  17172. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17173. auto se = detail::scope_exit([&] {
  17174. svr.stop();
  17175. t.join();
  17176. ASSERT_FALSE(svr.is_running());
  17177. });
  17178. svr.wait_until_ready();
  17179. {
  17180. std::string data(1024 * 1024 * 2, '&');
  17181. std::stringstream buffer;
  17182. buffer << data;
  17183. SSLClient cli("localhost", port);
  17184. cli.enable_server_certificate_verification(false);
  17185. UploadFormDataItems items{
  17186. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17187. {"hello", "world", "", ""},
  17188. };
  17189. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17191. ASSERT_EQ(StatusCode::OK_200, res->status);
  17192. }
  17193. }
  17194. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17195. std::string data(1024 * 1024 * 2, '&');
  17196. std::stringstream buffer;
  17197. buffer << data;
  17198. Client cli("https://localhost:8080");
  17199. cli.enable_server_certificate_verification(false);
  17200. UploadFormDataItems items{
  17201. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17202. {"hello", "world", "", ""},
  17203. };
  17204. for (const char &c : " \t\r\n") {
  17205. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17206. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17207. ASSERT_FALSE(res);
  17208. }
  17209. }
  17210. TEST(MultipartFormDataTest, AlternateFilename) {
  17211. auto handled = false;
  17212. Server svr;
  17213. svr.Post("/test", [&](const Request &req, Response &res) {
  17214. ASSERT_EQ(2u, req.form.files.size());
  17215. ASSERT_EQ(1u, req.form.fields.size());
  17216. // Test files
  17217. const auto &file1 = req.form.get_file("file1");
  17218. ASSERT_EQ("file1", file1.name);
  17219. ASSERT_EQ("A.txt", file1.filename);
  17220. ASSERT_EQ("text/plain", file1.content_type);
  17221. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17222. const auto &file2 = req.form.get_file("file2");
  17223. ASSERT_EQ("file2", file2.name);
  17224. ASSERT_EQ("a.html", file2.filename);
  17225. ASSERT_EQ("text/html", file2.content_type);
  17226. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17227. file2.content);
  17228. // Test text field
  17229. const auto &text = req.form.get_field("text");
  17230. ASSERT_EQ("text default", text);
  17231. res.set_content("ok", "text/plain");
  17232. handled = true;
  17233. });
  17234. thread t = thread([&] { svr.listen(HOST, PORT); });
  17235. auto se = detail::scope_exit([&] {
  17236. svr.stop();
  17237. t.join();
  17238. ASSERT_FALSE(svr.is_running());
  17239. ASSERT_TRUE(handled);
  17240. });
  17241. svr.wait_until_ready();
  17242. auto req = "POST /test HTTP/1.1\r\n"
  17243. "Host: localhost\r\n"
  17244. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17245. "Content-Length: 399\r\n"
  17246. "\r\n"
  17247. "----------\r\n"
  17248. "Content-Disposition: form-data; name=\"text\"\r\n"
  17249. "\r\n"
  17250. "text default\r\n"
  17251. "----------\r\n"
  17252. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17253. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17254. "Content-Type: text/plain\r\n"
  17255. "\r\n"
  17256. "Content of a.txt.\r\n"
  17257. "\r\n"
  17258. "----------\r\n"
  17259. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17260. "\"a.html\"\r\n"
  17261. "Content-Type: text/html\r\n"
  17262. "\r\n"
  17263. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17264. "\r\n"
  17265. "------------\r\n";
  17266. ASSERT_TRUE(send_request(1, req));
  17267. }
  17268. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17269. auto handled = false;
  17270. Server svr;
  17271. svr.Post("/test", [&](const Request &req, Response &res) {
  17272. // Case-insensitive "utf-8''" prefix with a long value
  17273. const auto &file = req.form.get_file("file1");
  17274. ASSERT_EQ("file1", file.name);
  17275. // 8000 chars exercises both the Content-Disposition parser and the
  17276. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17277. // Prior to the fix, std::regex_match on this header would cause O(N)
  17278. // stack recursion in libstdc++, leading to SIGSEGV.
  17279. std::string expected_filename(8000, 'A');
  17280. ASSERT_EQ(expected_filename, file.filename);
  17281. res.set_content("ok", "text/plain");
  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. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17293. // Regression test for GHSA-qq6v-r583-3h69
  17294. std::string long_filename(8000, 'A');
  17295. std::string body = "----------\r\n"
  17296. "Content-Disposition: form-data; name=\"file1\"; "
  17297. "filename*=\"Utf-8''" +
  17298. long_filename +
  17299. "\"\r\n"
  17300. "\r\n"
  17301. "hello\r\n"
  17302. "------------\r\n";
  17303. auto req = "POST /test HTTP/1.1\r\n"
  17304. "Host: localhost\r\n"
  17305. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17306. "Content-Length: " +
  17307. std::to_string(body.size()) + "\r\n\r\n" + body;
  17308. ASSERT_TRUE(send_request(1, req));
  17309. }
  17310. TEST(MultipartFormDataTest, AlternateFilenameWithLanguageTag) {
  17311. auto handled = false;
  17312. Server svr;
  17313. svr.Post("/test", [&](const Request &req, Response &res) {
  17314. ASSERT_EQ("A.txt", req.form.get_file("file1").filename);
  17315. ASSERT_EQ("na\xC3\xAFve.txt", req.form.get_file("file2").filename);
  17316. res.set_content("ok", "text/plain");
  17317. handled = true;
  17318. });
  17319. thread t = thread([&] { svr.listen(HOST, PORT); });
  17320. auto se = detail::scope_exit([&] {
  17321. svr.stop();
  17322. t.join();
  17323. ASSERT_FALSE(svr.is_running());
  17324. ASSERT_TRUE(handled);
  17325. });
  17326. svr.wait_until_ready();
  17327. std::string body = "----------\r\n"
  17328. "Content-Disposition: form-data; name=\"file1\"; "
  17329. "filename*=UTF-8'en'%41.txt\r\n"
  17330. "\r\n"
  17331. "hello\r\n"
  17332. "----------\r\n"
  17333. "Content-Disposition: form-data; name=\"file2\"; "
  17334. "filename*=utf-8'fr-CA'na%C3%AFve.txt\r\n"
  17335. "\r\n"
  17336. "bonjour\r\n"
  17337. "------------\r\n";
  17338. auto req = "POST /test HTTP/1.1\r\n"
  17339. "Host: localhost\r\n"
  17340. "Connection: close\r\n"
  17341. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17342. "Content-Length: " +
  17343. std::to_string(body.size()) + "\r\n\r\n" + body;
  17344. ASSERT_TRUE(send_request(1, req));
  17345. }
  17346. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17347. auto handled = false;
  17348. Server svr;
  17349. svr.Post("/test", [&](const Request &req, Response &) {
  17350. ASSERT_EQ(2u, req.form.fields.size());
  17351. const auto &text1 = req.form.get_field("text1");
  17352. ASSERT_EQ("text1", text1);
  17353. const auto &text2 = req.form.get_field("text2");
  17354. ASSERT_EQ("text2", text2);
  17355. handled = true;
  17356. });
  17357. thread t = thread([&] { svr.listen(HOST, PORT); });
  17358. auto se = detail::scope_exit([&] {
  17359. svr.stop();
  17360. t.join();
  17361. ASSERT_FALSE(svr.is_running());
  17362. ASSERT_TRUE(handled);
  17363. });
  17364. svr.wait_until_ready();
  17365. auto req = "POST /test HTTP/1.1\r\n"
  17366. "Host: localhost\r\n"
  17367. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17368. "Content-Length: 146\r\n"
  17369. "\r\n----------\r\n"
  17370. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17371. "\r\n"
  17372. "text1"
  17373. "\r\n----------\r\n"
  17374. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17375. "\r\n"
  17376. "text2"
  17377. "\r\n------------";
  17378. std::string response;
  17379. ASSERT_TRUE(send_request(1, req, &response));
  17380. ASSERT_EQ("200", response.substr(9, 3));
  17381. }
  17382. TEST(MultipartFormDataTest, ContentLength) {
  17383. auto handled = false;
  17384. Server svr;
  17385. svr.Post("/test", [&](const Request &req, Response &) {
  17386. ASSERT_EQ(2u, req.form.fields.size());
  17387. const auto &text1 = req.form.get_field("text1");
  17388. ASSERT_EQ("text1", text1);
  17389. const auto &text2 = req.form.get_field("text2");
  17390. ASSERT_EQ("text2", text2);
  17391. handled = true;
  17392. });
  17393. thread t = thread([&] { svr.listen(HOST, PORT); });
  17394. auto se = detail::scope_exit([&] {
  17395. svr.stop();
  17396. t.join();
  17397. ASSERT_FALSE(svr.is_running());
  17398. ASSERT_TRUE(handled);
  17399. });
  17400. svr.wait_until_ready();
  17401. auto req = "POST /test HTTP/1.1\r\n"
  17402. "Host: localhost\r\n"
  17403. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17404. "Content-Length: 167\r\n"
  17405. "\r\n----------\r\n"
  17406. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17407. "Content-Length: 5\r\n"
  17408. "\r\n"
  17409. "text1"
  17410. "\r\n----------\r\n"
  17411. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17412. "\r\n"
  17413. "text2"
  17414. "\r\n------------\r\n";
  17415. std::string response;
  17416. ASSERT_TRUE(send_request(1, req, &response));
  17417. ASSERT_EQ("200", response.substr(9, 3));
  17418. }
  17419. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17420. auto handled = false;
  17421. Server svr;
  17422. svr.Post("/test", [&](const Request &req, Response &) {
  17423. ASSERT_EQ(2u, req.form.fields.size());
  17424. const auto &text1 = req.form.get_field("text1");
  17425. ASSERT_EQ("text1", text1);
  17426. // TODO: Add header access for text fields if needed
  17427. const auto &text2 = req.form.get_field("text2");
  17428. ASSERT_EQ("text2", text2);
  17429. // TODO: Header access for text fields needs to be implemented
  17430. // auto &headers = it->second.headers;
  17431. // ASSERT_EQ(3U, headers.size());
  17432. // auto custom_header = headers.find("x-whatever");
  17433. // ASSERT_TRUE(custom_header != headers.end());
  17434. // ASSERT_NE("customvalue", custom_header->second);
  17435. // ASSERT_EQ("CustomValue", custom_header->second);
  17436. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17437. handled = true;
  17438. });
  17439. thread t = thread([&] { svr.listen(HOST, PORT); });
  17440. auto se = detail::scope_exit([&] {
  17441. svr.stop();
  17442. t.join();
  17443. ASSERT_FALSE(svr.is_running());
  17444. ASSERT_TRUE(handled);
  17445. });
  17446. svr.wait_until_ready();
  17447. auto req = "POST /test HTTP/1.1\r\n"
  17448. "Host: localhost\r\n"
  17449. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17450. "Content-Length: 232\r\n"
  17451. "\r\n----------\r\n"
  17452. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17453. "Content-Length: 5\r\n"
  17454. "X-Test: 1\r\n"
  17455. "\r\n"
  17456. "text1"
  17457. "\r\n----------\r\n"
  17458. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17459. "Content-Type: text/plain\r\n"
  17460. "X-Whatever: CustomValue\r\n"
  17461. "\r\n"
  17462. "text2"
  17463. "\r\n------------\r\n"
  17464. "That should be disregarded. Not even read";
  17465. std::string response;
  17466. ASSERT_TRUE(send_request(1, req, &response));
  17467. ASSERT_EQ("200", response.substr(9, 3));
  17468. }
  17469. TEST(MultipartFormDataTest, LargeHeader) {
  17470. auto handled = false;
  17471. Server svr;
  17472. svr.Post("/test", [&](const Request &req, Response &) {
  17473. ASSERT_EQ(1u, req.form.fields.size());
  17474. const auto &text = req.form.get_field("name1");
  17475. ASSERT_EQ("text1", text);
  17476. handled = true;
  17477. });
  17478. thread t = thread([&] { svr.listen(HOST, PORT); });
  17479. auto se = detail::scope_exit([&] {
  17480. svr.stop();
  17481. t.join();
  17482. ASSERT_FALSE(svr.is_running());
  17483. ASSERT_TRUE(handled);
  17484. });
  17485. svr.wait_until_ready();
  17486. auto boundary = std::string("cpp-httplib-multipart-data");
  17487. std::string content = "--" + boundary +
  17488. "\r\n"
  17489. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17490. "\r\n"
  17491. "text1\r\n"
  17492. "--" +
  17493. boundary + "--\r\n";
  17494. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17495. "Host: localhost\r\n"
  17496. "Content-Type: multipart/form-data;boundary=" +
  17497. boundary +
  17498. "\r\n"
  17499. "Content-Length: " +
  17500. std::to_string(content.size()) +
  17501. "\r\n"
  17502. "Dummy-Header: ";
  17503. std::string header_suffix = "\r\n"
  17504. "\r\n";
  17505. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17506. size_t header_dummy_size =
  17507. read_buff_size -
  17508. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17509. auto header_dummy = std::string(header_dummy_size, '@');
  17510. auto req = header_prefix + header_dummy + header_suffix + content;
  17511. std::string response;
  17512. ASSERT_TRUE(send_request(1, req, &response));
  17513. ASSERT_EQ("200", response.substr(9, 3));
  17514. }
  17515. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17516. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17517. // (not chunked Transfer-Encoding) after the streaming refactor.
  17518. auto handled = false;
  17519. Server svr;
  17520. svr.Post("/upload", [&](const Request &req, Response &res) {
  17521. auto cl_it = req.headers.find("Content-Length");
  17522. EXPECT_TRUE(cl_it != req.headers.end());
  17523. auto te_it = req.headers.find("Transfer-Encoding");
  17524. EXPECT_TRUE(te_it == req.headers.end());
  17525. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17526. res.set_content("ok", "text/plain");
  17527. handled = true;
  17528. });
  17529. auto port = svr.bind_to_any_port(HOST);
  17530. auto t = thread([&] { svr.listen_after_bind(); });
  17531. auto se = detail::scope_exit([&] {
  17532. svr.stop();
  17533. t.join();
  17534. ASSERT_FALSE(svr.is_running());
  17535. ASSERT_TRUE(handled);
  17536. });
  17537. svr.wait_until_ready();
  17538. UploadFormDataItems items = {
  17539. {"field1", "hello", "", "text/plain"},
  17540. {"file1", "world", "test.txt", "application/octet-stream"},
  17541. };
  17542. Client cli(HOST, port);
  17543. auto res = cli.Post("/upload", {}, items);
  17544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17545. EXPECT_EQ(StatusCode::OK_200, res->status);
  17546. }
  17547. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17548. // Verify that make_multipart_content_provider coalesces many small segments
  17549. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17550. constexpr size_t kItemCount = 1000;
  17551. UploadFormDataItems items;
  17552. items.reserve(kItemCount);
  17553. for (size_t i = 0; i < kItemCount; i++) {
  17554. items.push_back(
  17555. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17556. }
  17557. const std::string boundary = "----test-boundary";
  17558. auto content_length = detail::get_multipart_content_length(items, boundary);
  17559. auto provider = detail::make_multipart_content_provider(items, boundary);
  17560. // Drive the provider the same way write_content_with_progress does
  17561. size_t write_count = 0;
  17562. size_t total_bytes = 0;
  17563. DataSink sink;
  17564. size_t offset = 0;
  17565. sink.write = [&](const char *d, size_t l) -> bool {
  17566. (void)d;
  17567. write_count++;
  17568. total_bytes += l;
  17569. offset += l;
  17570. return true;
  17571. };
  17572. sink.is_writable = []() -> bool { return true; };
  17573. while (offset < content_length) {
  17574. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17575. }
  17576. EXPECT_EQ(content_length, total_bytes);
  17577. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17578. // With buffering into 64KB blocks, write_count should be much smaller.
  17579. auto segment_count = 3 * kItemCount + 1;
  17580. EXPECT_LT(write_count, segment_count / 10);
  17581. }
  17582. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17583. // Integration test: send many UploadFormDataItems and verify the server
  17584. // receives all of them correctly (#2410).
  17585. constexpr size_t kItemCount = 500;
  17586. auto handled = false;
  17587. Server svr;
  17588. svr.Post("/upload", [&](const Request &req, Response &res) {
  17589. EXPECT_EQ(kItemCount, req.form.fields.size());
  17590. for (size_t i = 0; i < kItemCount; i++) {
  17591. auto key = "field" + std::to_string(i);
  17592. auto val = "value" + std::to_string(i);
  17593. auto it = req.form.fields.find(key);
  17594. if (it != req.form.fields.end()) {
  17595. EXPECT_EQ(val, it->second.content);
  17596. } else {
  17597. ADD_FAILURE() << "Missing field: " << key;
  17598. }
  17599. }
  17600. res.set_content("ok", "text/plain");
  17601. handled = true;
  17602. });
  17603. auto port = svr.bind_to_any_port(HOST);
  17604. auto t = thread([&] { svr.listen_after_bind(); });
  17605. auto se = detail::scope_exit([&] {
  17606. svr.stop();
  17607. t.join();
  17608. ASSERT_FALSE(svr.is_running());
  17609. ASSERT_TRUE(handled);
  17610. });
  17611. svr.wait_until_ready();
  17612. UploadFormDataItems items;
  17613. items.reserve(kItemCount);
  17614. for (size_t i = 0; i < kItemCount; i++) {
  17615. items.push_back(
  17616. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17617. }
  17618. Client cli(HOST, port);
  17619. auto res = cli.Post("/upload", items);
  17620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17621. EXPECT_EQ(StatusCode::OK_200, res->status);
  17622. }
  17623. TEST(MultipartFormDataTest, MakeFileProvider) {
  17624. // Verify make_file_provider sends a file's contents correctly.
  17625. const std::string file_content(4096, 'Z');
  17626. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17627. {
  17628. std::ofstream ofs(tmp_path, std::ios::binary);
  17629. ofs.write(file_content.data(),
  17630. static_cast<std::streamsize>(file_content.size()));
  17631. }
  17632. auto handled = false;
  17633. Server svr;
  17634. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17635. const ContentReader &content_reader) {
  17636. ASSERT_TRUE(req.is_multipart_form_data());
  17637. std::vector<FormData> items;
  17638. content_reader(
  17639. [&](const FormData &file) {
  17640. items.push_back(file);
  17641. return true;
  17642. },
  17643. [&](const char *data, size_t data_length) {
  17644. items.back().content.append(data, data_length);
  17645. return true;
  17646. });
  17647. ASSERT_EQ(1u, items.size());
  17648. EXPECT_EQ("myfile", items[0].name);
  17649. EXPECT_EQ("data.bin", items[0].filename);
  17650. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17651. EXPECT_EQ(file_content, items[0].content);
  17652. handled = true;
  17653. });
  17654. auto port = svr.bind_to_any_port(HOST);
  17655. auto t = thread([&] { svr.listen_after_bind(); });
  17656. auto se = detail::scope_exit([&] {
  17657. svr.stop();
  17658. t.join();
  17659. ASSERT_FALSE(svr.is_running());
  17660. ASSERT_TRUE(handled);
  17661. std::remove(tmp_path.c_str());
  17662. });
  17663. svr.wait_until_ready();
  17664. FormDataProviderItems providers;
  17665. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17666. "application/octet-stream"));
  17667. Client cli(HOST, port);
  17668. auto res = cli.Post("/upload", {}, {}, providers);
  17669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17670. EXPECT_EQ(StatusCode::OK_200, res->status);
  17671. }
  17672. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17673. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17674. // (100) headers is rejected with a 400 Bad Request response.
  17675. Server svr;
  17676. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17677. res.set_content("ok", "text/plain");
  17678. });
  17679. thread t = thread([&] { svr.listen(HOST, PORT); });
  17680. auto se = detail::scope_exit([&] {
  17681. svr.stop();
  17682. t.join();
  17683. ASSERT_FALSE(svr.is_running());
  17684. });
  17685. svr.wait_until_ready();
  17686. // Build a multipart part with 101 custom headers (exceeding
  17687. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17688. std::stringstream body;
  17689. body << "--simpleboundary\r\n"
  17690. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17691. for (int i = 0; i < 101; i++) {
  17692. body << "X-Custom-Header-" << i << ": value\r\n";
  17693. }
  17694. body << "\r\n"
  17695. << "value1\r\n"
  17696. << "--simpleboundary--\r\n";
  17697. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17698. Client cli(HOST, PORT);
  17699. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17701. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17702. }
  17703. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17704. // A body that never contains the declared boundary must not be accumulated
  17705. // while the parser waits for it. Buffering it would also make every read
  17706. // rescan everything seen so far, which is quadratic in the body size.
  17707. Server svr;
  17708. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17709. res.set_content("ok", "text/plain");
  17710. });
  17711. auto port = svr.bind_to_any_port(HOST);
  17712. thread t = thread([&] { svr.listen_after_bind(); });
  17713. auto se = detail::scope_exit([&] {
  17714. svr.stop();
  17715. t.join();
  17716. ASSERT_FALSE(svr.is_running());
  17717. });
  17718. svr.wait_until_ready();
  17719. Client cli(HOST, port);
  17720. cli.set_read_timeout(60, 0);
  17721. cli.set_write_timeout(60, 0);
  17722. // '-' is the worst case: it matches the first character of the boundary, so
  17723. // every position has to be checked against it.
  17724. auto post_dashes = [&](size_t size) {
  17725. const std::string body(size, '-');
  17726. auto start = std::chrono::steady_clock::now();
  17727. auto res =
  17728. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17729. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17730. std::chrono::steady_clock::now() - start)
  17731. .count();
  17732. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17733. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17734. return ms;
  17735. };
  17736. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17737. // Windows.
  17738. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17739. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17740. // Comparing the two sizes rather than checking an absolute duration keeps
  17741. // this meaningful across build types and CI load, both of which move the
  17742. // absolute numbers by more than an order of magnitude. Four times the bytes
  17743. // costs about four times the time when parsing is linear, and about sixteen
  17744. // times when the body is buffered and rescanned.
  17745. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17746. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17747. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17748. << "ms, which suggests the body is being buffered and rescanned";
  17749. }
  17750. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17751. // A boundary can only be followed by CRLF or by "--", so anything else is
  17752. // malformed no matter what comes next. The parser must say so right away
  17753. // instead of buffering the rest of the declared body.
  17754. Server svr;
  17755. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17756. res.set_content("ok", "text/plain");
  17757. });
  17758. auto port = svr.bind_to_any_port(HOST);
  17759. thread t = thread([&] { svr.listen_after_bind(); });
  17760. auto se = detail::scope_exit([&] {
  17761. svr.stop();
  17762. t.join();
  17763. ASSERT_FALSE(svr.is_running());
  17764. });
  17765. svr.wait_until_ready();
  17766. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17767. // buffers instead of failing would still be waiting for the remaining bytes.
  17768. const std::string body = "--zzzz\r\n"
  17769. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17770. "\r\n"
  17771. "text1"
  17772. "\r\n--zzzzXX";
  17773. const std::string req = "POST /post HTTP/1.1\r\n"
  17774. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17775. "Content-Length: 1048576\r\n"
  17776. "\r\n" +
  17777. body;
  17778. std::string response;
  17779. ASSERT_TRUE(send_request(3, req, &response, port));
  17780. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17781. EXPECT_EQ("400", response.substr(9, 3));
  17782. }
  17783. // Posts a multipart body split into two writes, so that the server sees the
  17784. // split at whatever offset the caller chose, and expects the single "text1"
  17785. // field to come through.
  17786. static void expect_split_multipart_ok(const std::string &body1,
  17787. const std::string &body2) {
  17788. auto handled = false;
  17789. Server svr;
  17790. svr.Post("/post", [&](const Request &req, Response &) {
  17791. EXPECT_EQ(1u, req.form.fields.size());
  17792. EXPECT_EQ("text1", req.form.get_field("text1"));
  17793. handled = true;
  17794. });
  17795. auto port = svr.bind_to_any_port(HOST);
  17796. thread t = thread([&] { svr.listen_after_bind(); });
  17797. auto se = detail::scope_exit([&] {
  17798. svr.stop();
  17799. t.join();
  17800. ASSERT_FALSE(svr.is_running());
  17801. ASSERT_TRUE(handled);
  17802. });
  17803. svr.wait_until_ready();
  17804. // "Connection: close" makes the server close once it has answered, so the
  17805. // response drain ends immediately instead of idling until the read timeout.
  17806. const std::string head =
  17807. "POST /post HTTP/1.1\r\n"
  17808. "Host: localhost\r\n"
  17809. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17810. "Connection: close\r\n"
  17811. "Content-Length: " +
  17812. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17813. std::string response;
  17814. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17815. ASSERT_GE(response.size(), 12u) << "no response";
  17816. EXPECT_EQ("200", response.substr(9, 3));
  17817. }
  17818. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17819. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17820. // ignored, including when it does not arrive in the same read as the
  17821. // close-delimiter itself.
  17822. expect_split_multipart_ok("--zzzz\r\n"
  17823. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17824. "\r\n"
  17825. "text1"
  17826. "\r\n--zzzz--",
  17827. "\r\nthis epilogue must be ignored\r\n");
  17828. }
  17829. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17830. // The initial boundary may be preceded by a preamble of any length and may
  17831. // straddle a read boundary. Discarding data while waiting for it must not
  17832. // throw away a partial boundary sitting at the end of the buffer.
  17833. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17834. "zz\r\n"
  17835. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17836. "\r\n"
  17837. "text1"
  17838. "\r\n--zzzz--\r\n");
  17839. }
  17840. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17841. // The received boundary was only checked for being non-empty, so it could be
  17842. // as long as a header is allowed to be. The parser scans the body for
  17843. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17844. // costs a nearly full comparison at nearly every position, making the
  17845. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17846. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17847. Server svr;
  17848. svr.Post("/post", [](const Request &req, Response &res) {
  17849. EXPECT_EQ(1u, req.form.fields.size());
  17850. EXPECT_EQ("text1", req.form.get_field("text1"));
  17851. res.set_content("ok", "text/plain");
  17852. });
  17853. auto port = svr.bind_to_any_port(HOST);
  17854. thread t = thread([&] { svr.listen_after_bind(); });
  17855. auto se = detail::scope_exit([&] {
  17856. svr.stop();
  17857. t.join();
  17858. ASSERT_FALSE(svr.is_running());
  17859. });
  17860. svr.wait_until_ready();
  17861. Client cli(HOST, port);
  17862. auto post_with_boundary_of_length = [&](size_t len) {
  17863. const std::string boundary(len, 'a');
  17864. const std::string body =
  17865. "--" + boundary +
  17866. "\r\n"
  17867. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17868. "\r\n"
  17869. "text1"
  17870. "\r\n--" +
  17871. boundary + "--\r\n";
  17872. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17873. };
  17874. auto res = post_with_boundary_of_length(70);
  17875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17876. EXPECT_EQ(StatusCode::OK_200, res->status);
  17877. res = post_with_boundary_of_length(71);
  17878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17880. }
  17881. TEST(MakeFileBodyTest, Basic) {
  17882. const std::string file_content(4096, 'Z');
  17883. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17884. {
  17885. std::ofstream ofs(tmp_path, std::ios::binary);
  17886. ofs.write(file_content.data(),
  17887. static_cast<std::streamsize>(file_content.size()));
  17888. }
  17889. auto handled = false;
  17890. Server svr;
  17891. svr.Post("/upload", [&](const Request &req, Response &res) {
  17892. EXPECT_EQ(file_content, req.body);
  17893. handled = true;
  17894. res.status = StatusCode::OK_200;
  17895. });
  17896. auto port = svr.bind_to_any_port(HOST);
  17897. auto t = thread([&] { svr.listen_after_bind(); });
  17898. auto se = detail::scope_exit([&] {
  17899. svr.stop();
  17900. t.join();
  17901. ASSERT_FALSE(svr.is_running());
  17902. ASSERT_TRUE(handled);
  17903. std::remove(tmp_path.c_str());
  17904. });
  17905. svr.wait_until_ready();
  17906. auto fb = make_file_body(tmp_path);
  17907. ASSERT_GT(fb.first, 0u);
  17908. Client cli(HOST, port);
  17909. auto res =
  17910. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17912. EXPECT_EQ(StatusCode::OK_200, res->status);
  17913. }
  17914. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17915. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17916. {
  17917. std::ofstream ofs(path, std::ios::binary);
  17918. const std::string content(100, 'A');
  17919. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17920. }
  17921. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17922. auto body = make_file_body(path);
  17923. ASSERT_EQ(100u, body.first);
  17924. ASSERT_TRUE(static_cast<bool>(body.second));
  17925. // Rewritten shorter after its length was measured - and, on a server, after
  17926. // that length has already gone out as Content-Length.
  17927. {
  17928. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17929. const std::string content(10, 'A');
  17930. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17931. }
  17932. std::string written;
  17933. DataSink sink;
  17934. sink.write = [&](const char *d, size_t l) {
  17935. written.append(d, l);
  17936. return true;
  17937. };
  17938. // The provider has to report failure. write_content_with_progress() advances
  17939. // its offset only by what was written, so a provider that returns true
  17940. // without completing the length it promised is called again straight away,
  17941. // and again.
  17942. EXPECT_FALSE(body.second(0, body.first, sink));
  17943. EXPECT_EQ(std::string(10, 'A'), written);
  17944. }
  17945. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17946. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17947. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17948. {
  17949. std::ofstream ofs(path, std::ios::binary);
  17950. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17951. }
  17952. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17953. auto body = make_file_body(path);
  17954. ASSERT_EQ(content.size(), body.first);
  17955. ASSERT_TRUE(static_cast<bool>(body.second));
  17956. std::string written;
  17957. DataSink sink;
  17958. sink.write = [&](const char *d, size_t l) {
  17959. written.append(d, l);
  17960. return true;
  17961. };
  17962. EXPECT_TRUE(body.second(0, body.first, sink));
  17963. EXPECT_EQ(content, written);
  17964. }
  17965. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17966. static constexpr unsigned int number_of_tasks{1000000};
  17967. std::atomic_uint count{0};
  17968. std::unique_ptr<TaskQueue> task_queue{
  17969. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17970. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17971. auto queued = task_queue->enqueue(
  17972. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17973. EXPECT_TRUE(queued);
  17974. }
  17975. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17976. task_queue->shutdown();
  17977. #else
  17978. EXPECT_NO_THROW(task_queue->shutdown());
  17979. #endif
  17980. EXPECT_EQ(number_of_tasks, count.load());
  17981. }
  17982. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17983. static constexpr unsigned int number_of_tasks{1000000};
  17984. static constexpr unsigned int qlimit{2};
  17985. unsigned int queued_count{0};
  17986. std::atomic_uint count{0};
  17987. std::unique_ptr<TaskQueue> task_queue{
  17988. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17989. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17990. if (task_queue->enqueue(
  17991. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17992. queued_count++;
  17993. }
  17994. }
  17995. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17996. task_queue->shutdown();
  17997. #else
  17998. EXPECT_NO_THROW(task_queue->shutdown());
  17999. #endif
  18000. EXPECT_EQ(queued_count, count.load());
  18001. EXPECT_TRUE(queued_count <= number_of_tasks);
  18002. EXPECT_TRUE(queued_count >= qlimit);
  18003. }
  18004. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  18005. // Use a short idle timeout so a dynamic thread spawns, times out and
  18006. // exits during the test, and the pool keeps working afterwards.
  18007. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  18008. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  18009. /*idle_timeout_sec=*/1}};
  18010. std::atomic_uint count{0};
  18011. std::condition_variable cv;
  18012. std::mutex mtx;
  18013. bool release = false;
  18014. // Block the base thread so the second task spawns a dynamic thread.
  18015. EXPECT_TRUE(task_queue->enqueue([&] {
  18016. std::unique_lock<std::mutex> lock(mtx);
  18017. while (!release) {
  18018. cv.wait(lock);
  18019. }
  18020. count++;
  18021. }));
  18022. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  18023. // Let the dynamic thread finish its task and exceed the idle timeout.
  18024. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  18025. {
  18026. std::unique_lock<std::mutex> lock(mtx);
  18027. release = true;
  18028. }
  18029. cv.notify_all();
  18030. // The pool must still accept and run tasks after the dynamic thread exited.
  18031. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  18032. task_queue->shutdown();
  18033. EXPECT_EQ(3u, count.load());
  18034. }
  18035. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  18036. static constexpr size_t number_of_tasks{32};
  18037. std::unique_ptr<TaskQueue> task_queue{
  18038. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  18039. // Let the base threads go idle so the burst below finds them waiting.
  18040. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18041. std::mutex mtx;
  18042. std::condition_variable cv;
  18043. size_t running = 0;
  18044. bool release = false;
  18045. for (size_t i = 0; i < number_of_tasks; i++) {
  18046. EXPECT_TRUE(task_queue->enqueue([&] {
  18047. std::unique_lock<std::mutex> lock(mtx);
  18048. running++;
  18049. cv.notify_all();
  18050. cv.wait(lock, [&] { return release; });
  18051. }));
  18052. }
  18053. {
  18054. std::unique_lock<std::mutex> lock(mtx);
  18055. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  18056. [&] { return running == number_of_tasks; }));
  18057. release = true;
  18058. }
  18059. cv.notify_all();
  18060. task_queue->shutdown();
  18061. }
  18062. TEST(TaskQueueTest, MaxQueuedRequests) {
  18063. static constexpr unsigned int qlimit{3};
  18064. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  18065. std::condition_variable sem_cv;
  18066. std::mutex sem_mtx;
  18067. int credits = 0;
  18068. bool queued;
  18069. /* Fill up the queue with tasks that will block until we give them credits to
  18070. * complete. */
  18071. for (unsigned int n = 0; n <= qlimit;) {
  18072. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  18073. std::unique_lock<std::mutex> lock(sem_mtx);
  18074. while (credits <= 0) {
  18075. sem_cv.wait(lock);
  18076. }
  18077. /* Consume the credit and signal the test code if they are all gone. */
  18078. if (--credits == 0) { sem_cv.notify_one(); }
  18079. });
  18080. if (n < qlimit) {
  18081. /* The first qlimit enqueues must succeed. */
  18082. EXPECT_TRUE(queued);
  18083. } else {
  18084. /* The last one will succeed only when the worker thread
  18085. * starts and dequeues the first blocking task. Although
  18086. * not necessary for the correctness of this test, we sleep for
  18087. * a short while to avoid busy waiting. */
  18088. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18089. }
  18090. if (queued) { n++; }
  18091. }
  18092. /* Further enqueues must fail since the queue is full. */
  18093. for (auto i = 0; i < 4; i++) {
  18094. queued = task_queue->enqueue([] {});
  18095. EXPECT_FALSE(queued);
  18096. }
  18097. /* Give the credits to allow the previous tasks to complete. */
  18098. {
  18099. std::unique_lock<std::mutex> lock(sem_mtx);
  18100. credits += qlimit + 1;
  18101. }
  18102. sem_cv.notify_all();
  18103. /* Wait for all the credits to be consumed. */
  18104. {
  18105. std::unique_lock<std::mutex> lock(sem_mtx);
  18106. while (credits > 0) {
  18107. sem_cv.wait(lock);
  18108. }
  18109. }
  18110. /* Check that we are able again to enqueue at least qlimit tasks. */
  18111. for (unsigned int i = 0; i < qlimit; i++) {
  18112. queued = task_queue->enqueue([] {});
  18113. EXPECT_TRUE(queued);
  18114. }
  18115. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18116. task_queue->shutdown();
  18117. #else
  18118. EXPECT_NO_THROW(task_queue->shutdown());
  18119. #endif
  18120. }
  18121. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  18122. Server svr;
  18123. std::string method;
  18124. std::string body;
  18125. auto has_content_length = false;
  18126. auto has_transfer_encoding = false;
  18127. std::atomic<int> bad_requests{0};
  18128. // Leftover body bytes get parsed as a malformed request and answered with
  18129. // 400
  18130. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  18131. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  18132. });
  18133. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  18134. res.set_redirect("/down", StatusCode::SeeOther_303);
  18135. });
  18136. svr.Get("/down", [&](const Request &req, Response &res) {
  18137. method = req.method;
  18138. body = req.body;
  18139. has_content_length = req.has_header("Content-Length");
  18140. has_transfer_encoding = req.has_header("Transfer-Encoding");
  18141. res.set_content("ok", "text/plain");
  18142. });
  18143. auto port = svr.bind_to_any_port(HOST);
  18144. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18145. auto se = detail::scope_exit([&] {
  18146. svr.stop();
  18147. thread.join();
  18148. ASSERT_FALSE(svr.is_running());
  18149. });
  18150. svr.wait_until_ready();
  18151. const std::string payload = "SECRET-BODY";
  18152. auto check = [&](Client &cli, const Result &res) {
  18153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18154. EXPECT_EQ(StatusCode::OK_200, res->status);
  18155. EXPECT_EQ("ok", res->body);
  18156. EXPECT_EQ("GET", method);
  18157. EXPECT_TRUE(body.empty());
  18158. EXPECT_FALSE(has_content_length);
  18159. EXPECT_FALSE(has_transfer_encoding);
  18160. // Nothing of the original body may be left on the connection
  18161. auto res2 = cli.Get("/down");
  18162. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18163. EXPECT_EQ(StatusCode::OK_200, res2->status);
  18164. EXPECT_EQ("ok", res2->body);
  18165. EXPECT_EQ(0, bad_requests);
  18166. };
  18167. // With content length
  18168. {
  18169. Client cli(HOST, port);
  18170. cli.set_keep_alive(true);
  18171. cli.set_follow_location(true);
  18172. auto res = cli.Post(
  18173. "/up", payload.size(),
  18174. [&](size_t offset, size_t length, DataSink &sink) {
  18175. return sink.write(payload.data() + offset, length);
  18176. },
  18177. "text/plain");
  18178. check(cli, res);
  18179. }
  18180. // Without content length (chunked)
  18181. {
  18182. Client cli(HOST, port);
  18183. cli.set_keep_alive(true);
  18184. cli.set_follow_location(true);
  18185. auto res = cli.Post(
  18186. "/up",
  18187. [&](size_t /*offset*/, DataSink &sink) {
  18188. sink.write(payload.data(), payload.size());
  18189. sink.done();
  18190. return true;
  18191. },
  18192. "text/plain");
  18193. check(cli, res);
  18194. }
  18195. }
  18196. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18197. Server svr;
  18198. std::string target;
  18199. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18200. // Echo the still-encoded name back in the Location
  18201. const std::string prefix = "/start/";
  18202. res.status = StatusCode::Found_302;
  18203. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18204. });
  18205. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18206. target = req.target;
  18207. res.set_content("ok", "text/plain");
  18208. });
  18209. auto port = svr.bind_to_any_port(HOST);
  18210. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18211. auto se = detail::scope_exit([&] {
  18212. svr.stop();
  18213. thread.join();
  18214. ASSERT_FALSE(svr.is_running());
  18215. });
  18216. svr.wait_until_ready();
  18217. // Decoding the Location path would turn the first four into a path
  18218. // separator, a query delimiter, a fragment delimiter and a different
  18219. // percent-encoded octet. The rest must keep reaching the server as they are.
  18220. const std::vector<std::string> names = {
  18221. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18222. };
  18223. for (auto path_encode : {true, false}) {
  18224. Client cli(HOST, port);
  18225. cli.set_follow_location(true);
  18226. cli.set_path_encode(path_encode);
  18227. for (const auto &name : names) {
  18228. target.clear();
  18229. auto res = cli.Get("/start/" + name);
  18230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18231. EXPECT_EQ(StatusCode::OK_200, res->status);
  18232. EXPECT_EQ("/dest/" + name, target);
  18233. }
  18234. }
  18235. }
  18236. TEST(RedirectTest, NotModifiedIsReturned) {
  18237. Server svr;
  18238. svr.Get("/cached", [](const Request &, Response &res) {
  18239. res.status = StatusCode::NotModified_304;
  18240. });
  18241. auto port = svr.bind_to_any_port(HOST);
  18242. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18243. auto se = detail::scope_exit([&] {
  18244. svr.stop();
  18245. thread.join();
  18246. ASSERT_FALSE(svr.is_running());
  18247. });
  18248. svr.wait_until_ready();
  18249. Client cli(HOST, port);
  18250. cli.set_follow_location(true);
  18251. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18253. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18254. }
  18255. TEST(RedirectTest, NoLocationIsReturned) {
  18256. Server svr;
  18257. svr.Get("/no-location", [](const Request &, Response &res) {
  18258. res.status = StatusCode::Found_302;
  18259. res.set_content("no location", "text/plain");
  18260. });
  18261. auto port = svr.bind_to_any_port(HOST);
  18262. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18263. auto se = detail::scope_exit([&] {
  18264. svr.stop();
  18265. thread.join();
  18266. ASSERT_FALSE(svr.is_running());
  18267. });
  18268. svr.wait_until_ready();
  18269. Client cli(HOST, port);
  18270. cli.set_follow_location(true);
  18271. auto res = cli.Get("/no-location");
  18272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18273. EXPECT_EQ(StatusCode::Found_302, res->status);
  18274. EXPECT_EQ("no location", res->body);
  18275. // The callbacks see the body of the response that is returned
  18276. auto handler_called = false;
  18277. auto progress_called = false;
  18278. std::string body;
  18279. auto res2 = cli.Get(
  18280. "/no-location",
  18281. [&](const Response &) {
  18282. handler_called = true;
  18283. return true;
  18284. },
  18285. [&](const char *data, size_t data_length) {
  18286. body.append(data, data_length);
  18287. return true;
  18288. },
  18289. [&](size_t, size_t) {
  18290. progress_called = true;
  18291. return true;
  18292. });
  18293. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18294. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18295. EXPECT_TRUE(handler_called);
  18296. EXPECT_TRUE(progress_called);
  18297. EXPECT_EQ("no location", body);
  18298. }
  18299. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18300. Server svr;
  18301. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18302. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18303. });
  18304. svr.Get("/hello", [](const Request &req, Response &res) {
  18305. res.set_content(req.get_param_value("key"), "text/plain");
  18306. });
  18307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18308. auto se = detail::scope_exit([&] {
  18309. svr.stop();
  18310. thread.join();
  18311. ASSERT_FALSE(svr.is_running());
  18312. });
  18313. svr.wait_until_ready();
  18314. {
  18315. Client cli(HOST, PORT);
  18316. cli.set_follow_location(true);
  18317. auto res = cli.Get("/");
  18318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18319. EXPECT_EQ(StatusCode::OK_200, res->status);
  18320. EXPECT_EQ("val&key2=val2", res->body);
  18321. }
  18322. }
  18323. #endif
  18324. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18325. Server svr;
  18326. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18327. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18328. });
  18329. svr.Get("/hello", [](const Request &req, Response &res) {
  18330. res.set_content(req.get_param_value("key"), "text/plain");
  18331. });
  18332. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18333. auto se = detail::scope_exit([&] {
  18334. svr.stop();
  18335. thread.join();
  18336. ASSERT_FALSE(svr.is_running());
  18337. });
  18338. svr.wait_until_ready();
  18339. {
  18340. Client cli(HOST, PORT);
  18341. cli.set_follow_location(true);
  18342. auto res = cli.Get("/");
  18343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18344. EXPECT_EQ(StatusCode::OK_200, res->status);
  18345. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18346. }
  18347. }
  18348. TEST(RedirectTest, RedirectWithPlusInPath) {
  18349. Server svr;
  18350. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18351. res.set_redirect("/a+b");
  18352. });
  18353. // Route pattern uses regex; escape + as \\+
  18354. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18355. res.set_content(req.path, "text/plain");
  18356. });
  18357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18358. auto se = detail::scope_exit([&] {
  18359. svr.stop();
  18360. thread.join();
  18361. ASSERT_FALSE(svr.is_running());
  18362. });
  18363. svr.wait_until_ready();
  18364. {
  18365. Client cli(HOST, PORT);
  18366. cli.set_follow_location(true);
  18367. auto res = cli.Get("/");
  18368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18369. EXPECT_EQ(StatusCode::OK_200, res->status);
  18370. EXPECT_EQ("/a+b", res->body);
  18371. }
  18372. }
  18373. TEST(RedirectTest, ResolveRelativeLocation) {
  18374. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18375. const std::vector<std::pair<std::string, std::string>> cases = {
  18376. {"g", "/b/c/g"},
  18377. {"./g", "/b/c/g"},
  18378. {"g/", "/b/c/g/"},
  18379. {"?y", "/b/c/d;p?y"},
  18380. {"g?y", "/b/c/g?y"},
  18381. {"#s", "/b/c/d;p?q#s"},
  18382. {"g#s", "/b/c/g#s"},
  18383. {"g?y#s", "/b/c/g?y#s"},
  18384. {";x", "/b/c/;x"},
  18385. {"g;x", "/b/c/g;x"},
  18386. {".", "/b/c/"},
  18387. {"./", "/b/c/"},
  18388. {"..", "/b/"},
  18389. {"../", "/b/"},
  18390. {"../g", "/b/g"},
  18391. {"../..", "/"},
  18392. {"../../", "/"},
  18393. {"../../g", "/g"},
  18394. {"../../../g", "/g"},
  18395. {"g.", "/b/c/g."},
  18396. {".g", "/b/c/.g"},
  18397. {"g..", "/b/c/g.."},
  18398. {"..g", "/b/c/..g"},
  18399. {"./../g", "/b/g"},
  18400. {"./g/.", "/b/c/g/"},
  18401. {"g/./h", "/b/c/g/h"},
  18402. {"g/../h", "/b/c/h"},
  18403. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18404. {"g;x=1/../y", "/b/c/y"},
  18405. {"g?y/./x", "/b/c/g?y/./x"},
  18406. {"g#s/../x", "/b/c/g#s/../x"},
  18407. // Not relative-path references, so left for parse_url.
  18408. {"/g", "/g"},
  18409. {"//g", "//g"},
  18410. {"http://g/x", "http://g/x"},
  18411. {"g:h", "g:h"},
  18412. };
  18413. for (const auto &c : cases) {
  18414. EXPECT_EQ(c.second,
  18415. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18416. << c.first;
  18417. }
  18418. // A result starting with "//" is still a path, not a network-path reference
  18419. EXPECT_EQ("/.//g",
  18420. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18421. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18422. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18423. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18424. }
  18425. TEST(RedirectTest, RemoveDotSegments) {
  18426. // RFC 3986 section 5.2.4
  18427. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18428. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18429. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18430. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18431. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18432. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18433. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18434. }
  18435. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18436. Server svr;
  18437. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18438. res.set_redirect("/dir/../target?x=1");
  18439. });
  18440. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18441. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18442. "/dir/./../target");
  18443. });
  18444. svr.Get("/target", [](const Request &req, Response &res) {
  18445. res.set_content(req.path, "text/plain");
  18446. });
  18447. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18448. auto se = detail::scope_exit([&] {
  18449. svr.stop();
  18450. th.join();
  18451. ASSERT_FALSE(svr.is_running());
  18452. });
  18453. svr.wait_until_ready();
  18454. Client cli("localhost", PORT);
  18455. cli.set_follow_location(true);
  18456. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18457. auto res = cli.Get(path);
  18458. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18459. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18460. EXPECT_EQ("/target", res->body) << path;
  18461. }
  18462. }
  18463. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18464. Server svr;
  18465. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18466. res.set_redirect(req.get_param_value("to"));
  18467. });
  18468. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18469. res.set_content(req.target, "text/plain");
  18470. });
  18471. svr.Get("/other", [](const Request &req, Response &res) {
  18472. res.set_content(req.target, "text/plain");
  18473. });
  18474. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18475. auto se = detail::scope_exit([&] {
  18476. svr.stop();
  18477. thread.join();
  18478. ASSERT_FALSE(svr.is_running());
  18479. });
  18480. svr.wait_until_ready();
  18481. const std::vector<std::pair<std::string, std::string>> cases = {
  18482. {"next", "/dir/next"},
  18483. {"./next?x=1", "/dir/next?x=1"},
  18484. {"next?source=https://example.com/catalog",
  18485. "/dir/next?source=https://example.com/catalog"},
  18486. {"../other", "/other"},
  18487. };
  18488. for (const auto &c : cases) {
  18489. Client cli(HOST, PORT);
  18490. cli.set_follow_location(true);
  18491. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18492. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18493. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18494. EXPECT_EQ(c.second, res->body) << c.first;
  18495. }
  18496. }
  18497. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18498. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18499. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18500. Server other;
  18501. std::atomic<int> other_hits{0};
  18502. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18503. other_hits++;
  18504. res.set_content("other", "text/plain");
  18505. });
  18506. auto other_port = other.bind_to_any_port("127.0.0.1");
  18507. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18508. Server svr;
  18509. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18510. res.set_redirect(req.get_param_value("to"));
  18511. });
  18512. svr.Get(".*", [](const Request &req, Response &res) {
  18513. res.set_content(req.path, "text/plain");
  18514. });
  18515. auto port = svr.bind_to_any_port(HOST);
  18516. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18517. auto se = detail::scope_exit([&] {
  18518. svr.stop();
  18519. thread.join();
  18520. other.stop();
  18521. other_thread.join();
  18522. ASSERT_FALSE(svr.is_running());
  18523. ASSERT_FALSE(other.is_running());
  18524. });
  18525. svr.wait_until_ready();
  18526. other.wait_until_ready();
  18527. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18528. for (const auto &to :
  18529. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18530. Client cli(HOST, port);
  18531. cli.set_follow_location(true);
  18532. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18533. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18534. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18535. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18536. }
  18537. EXPECT_EQ(0, other_hits.load());
  18538. }
  18539. #ifdef CPPHTTPLIB_SSL_ENABLED
  18540. TEST(RedirectTest, Issue2185_Online) {
  18541. SSLClient client("github.com");
  18542. client.set_follow_location(true);
  18543. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18544. "Coollab-Windows.zip");
  18545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18546. EXPECT_EQ(StatusCode::OK_200, res->status);
  18547. EXPECT_EQ(9920427U, res->body.size());
  18548. }
  18549. #endif
  18550. TEST(VulnerabilityTest, CRLFInjection) {
  18551. Server svr;
  18552. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18553. res.set_content("Hello 1", "text/plain");
  18554. });
  18555. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18556. res.set_content("Hello 2", "text/plain");
  18557. });
  18558. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18559. res.set_content("Hello 3", "text/plain");
  18560. });
  18561. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18562. res.set_content("Hello 4", "text/plain");
  18563. });
  18564. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18565. for (const auto &x : req.headers) {
  18566. auto key = x.first;
  18567. EXPECT_STRNE("evil", key.c_str());
  18568. }
  18569. });
  18570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18571. auto se = detail::scope_exit([&] {
  18572. svr.stop();
  18573. thread.join();
  18574. ASSERT_FALSE(svr.is_running());
  18575. });
  18576. svr.wait_until_ready();
  18577. {
  18578. Client cli(HOST, PORT);
  18579. cli.Post("/test1", "A=B",
  18580. "application/x-www-form-urlencoded\r\nevil: hello1");
  18581. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18582. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18583. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18584. }
  18585. }
  18586. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18587. auto server_thread = std::thread([] {
  18588. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18589. default_socket_options(srv);
  18590. sockaddr_in addr{};
  18591. addr.sin_family = AF_INET;
  18592. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18593. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18594. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18595. ::listen(srv, 1);
  18596. sockaddr_in cli_addr{};
  18597. socklen_t cli_len = sizeof(cli_addr);
  18598. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18599. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18600. std::string buf_all;
  18601. char buf[2048];
  18602. ssize_t n;
  18603. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18604. buf_all.append(buf, static_cast<size_t>(n));
  18605. size_t pos;
  18606. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18607. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18608. auto e = request_block.find("\r\n");
  18609. if (e != std::string::npos) {
  18610. auto request_line = request_block.substr(0, e);
  18611. std::string msg =
  18612. "CRLF injection detected in request line: '" + request_line + "'";
  18613. EXPECT_FALSE(true) << msg;
  18614. }
  18615. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18616. ::send(cli,
  18617. #ifdef _WIN32
  18618. static_cast<const char *>(resp.c_str()),
  18619. static_cast<int>(resp.size()),
  18620. #else
  18621. resp.c_str(), resp.size(),
  18622. #endif
  18623. 0);
  18624. buf_all.erase(0, pos + 4);
  18625. }
  18626. }
  18627. detail::close_socket(cli);
  18628. detail::close_socket(srv);
  18629. });
  18630. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18631. auto cli = Client("127.0.0.1", PORT + 1);
  18632. auto headers = Headers{
  18633. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18634. {"Connection", "keep-alive"}};
  18635. auto res = cli.Get("/hi", headers);
  18636. EXPECT_FALSE(res);
  18637. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18638. server_thread.join();
  18639. }
  18640. // A request rejected before any byte reaches the socket must fail right away
  18641. // instead of waiting for a response the server will never send.
  18642. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18643. // The kernel completes the TCP handshake from the listen backlog, so the
  18644. // client connects, but nothing ever reads, responds or closes.
  18645. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18646. default_socket_options(srv);
  18647. sockaddr_in addr{};
  18648. addr.sin_family = AF_INET;
  18649. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18650. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18651. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18652. ASSERT_EQ(0, ::listen(srv, 8));
  18653. auto cli = Client("127.0.0.1", PORT + 1);
  18654. cli.set_read_timeout(10, 0);
  18655. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18656. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18657. std::chrono::steady_clock::now() - start)
  18658. .count();
  18659. };
  18660. {
  18661. Request req;
  18662. req.method = "GE T";
  18663. req.path = "/";
  18664. auto start = std::chrono::steady_clock::now();
  18665. auto res = cli.send(req);
  18666. EXPECT_FALSE(res);
  18667. EXPECT_EQ(Error::Write, res.error());
  18668. EXPECT_LT(elapsed_ms(start), 1000);
  18669. }
  18670. {
  18671. auto start = std::chrono::steady_clock::now();
  18672. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18673. EXPECT_FALSE(res);
  18674. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18675. EXPECT_LT(elapsed_ms(start), 1000);
  18676. }
  18677. EXPECT_FALSE(cli.is_socket_open());
  18678. detail::close_socket(srv);
  18679. }
  18680. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18681. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18682. default_socket_options(srv);
  18683. sockaddr_in addr{};
  18684. addr.sin_family = AF_INET;
  18685. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18686. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18687. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18688. ASSERT_EQ(0, ::listen(srv, 1));
  18689. std::string received;
  18690. auto server_thread = std::thread([&] {
  18691. auto sock = ::accept(srv, nullptr, nullptr);
  18692. if (sock == INVALID_SOCKET) { return; }
  18693. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18694. char buf[2048];
  18695. ssize_t n;
  18696. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18697. received.append(buf, static_cast<size_t>(n));
  18698. }
  18699. detail::close_socket(sock);
  18700. });
  18701. {
  18702. auto cli = Client("127.0.0.1", PORT + 1);
  18703. // "Z" sorts after the default headers, so writing straight to the socket
  18704. // would have sent the request line and those headers before the rejection.
  18705. auto handle =
  18706. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18707. EXPECT_FALSE(handle.is_valid());
  18708. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18709. }
  18710. server_thread.join();
  18711. detail::close_socket(srv);
  18712. EXPECT_TRUE(received.empty()) << received;
  18713. }
  18714. TEST(PathParamsTest, StaticMatch) {
  18715. const auto pattern = "/users/all";
  18716. detail::PathParamsMatcher matcher(pattern);
  18717. Request request;
  18718. request.path = "/users/all";
  18719. ASSERT_TRUE(matcher.match(request));
  18720. std::unordered_map<std::string, std::string> expected_params = {};
  18721. EXPECT_EQ(request.path_params, expected_params);
  18722. }
  18723. TEST(PathParamsTest, StaticMismatch) {
  18724. const auto pattern = "/users/all";
  18725. detail::PathParamsMatcher matcher(pattern);
  18726. Request request;
  18727. request.path = "/users/1";
  18728. ASSERT_FALSE(matcher.match(request));
  18729. }
  18730. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18731. const auto pattern = "/users/:id/subscriptions";
  18732. detail::PathParamsMatcher matcher(pattern);
  18733. Request request;
  18734. request.path = "/users/42/subscriptions";
  18735. ASSERT_TRUE(matcher.match(request));
  18736. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18737. EXPECT_EQ(request.path_params, expected_params);
  18738. }
  18739. TEST(PathParamsTest, SingleParamInTheEnd) {
  18740. const auto pattern = "/users/:id";
  18741. detail::PathParamsMatcher matcher(pattern);
  18742. Request request;
  18743. request.path = "/users/24";
  18744. ASSERT_TRUE(matcher.match(request));
  18745. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18746. EXPECT_EQ(request.path_params, expected_params);
  18747. }
  18748. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18749. const auto pattern = "/users/:id/";
  18750. detail::PathParamsMatcher matcher(pattern);
  18751. Request request;
  18752. request.path = "/users/42/";
  18753. ASSERT_TRUE(matcher.match(request));
  18754. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18755. EXPECT_EQ(request.path_params, expected_params);
  18756. }
  18757. TEST(PathParamsTest, EmptyParam) {
  18758. const auto pattern = "/users/:id/";
  18759. detail::PathParamsMatcher matcher(pattern);
  18760. Request request;
  18761. request.path = "/users//";
  18762. ASSERT_TRUE(matcher.match(request));
  18763. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18764. EXPECT_EQ(request.path_params, expected_params);
  18765. }
  18766. TEST(PathParamsTest, FragmentMismatch) {
  18767. const auto pattern = "/users/:id/";
  18768. detail::PathParamsMatcher matcher(pattern);
  18769. Request request;
  18770. request.path = "/admins/24/";
  18771. ASSERT_FALSE(matcher.match(request));
  18772. }
  18773. TEST(PathParamsTest, ExtraFragments) {
  18774. const auto pattern = "/users/:id";
  18775. detail::PathParamsMatcher matcher(pattern);
  18776. Request request;
  18777. request.path = "/users/42/subscriptions";
  18778. ASSERT_FALSE(matcher.match(request));
  18779. }
  18780. TEST(PathParamsTest, MissingTrailingParam) {
  18781. const auto pattern = "/users/:id";
  18782. detail::PathParamsMatcher matcher(pattern);
  18783. Request request;
  18784. request.path = "/users";
  18785. ASSERT_FALSE(matcher.match(request));
  18786. }
  18787. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18788. const auto pattern = "/users/:id/subscriptions";
  18789. detail::PathParamsMatcher matcher(pattern);
  18790. Request request;
  18791. request.path = "/users/subscriptions";
  18792. ASSERT_FALSE(matcher.match(request));
  18793. }
  18794. TEST(PathParamsTest, MultipleParams) {
  18795. const auto pattern = "/users/:userid/subscriptions/:subid";
  18796. detail::PathParamsMatcher matcher(pattern);
  18797. Request request;
  18798. request.path = "/users/42/subscriptions/2";
  18799. ASSERT_TRUE(matcher.match(request));
  18800. std::unordered_map<std::string, std::string> expected_params = {
  18801. {"userid", "42"}, {"subid", "2"}};
  18802. EXPECT_EQ(request.path_params, expected_params);
  18803. }
  18804. TEST(PathParamsTest, SequenceOfParams) {
  18805. const auto pattern = "/values/:x/:y/:z";
  18806. detail::PathParamsMatcher matcher(pattern);
  18807. Request request;
  18808. request.path = "/values/1/2/3";
  18809. ASSERT_TRUE(matcher.match(request));
  18810. std::unordered_map<std::string, std::string> expected_params = {
  18811. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18812. EXPECT_EQ(request.path_params, expected_params);
  18813. }
  18814. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18815. const auto pattern = "/prefix:suffix";
  18816. detail::PathParamsMatcher matcher(pattern);
  18817. Request request;
  18818. request.path = "/prefix:suffix";
  18819. ASSERT_TRUE(matcher.match(request));
  18820. const std::unordered_map<std::string, std::string> expected_params = {};
  18821. EXPECT_EQ(request.path_params, expected_params);
  18822. }
  18823. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18824. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18825. // calling thread's stack on a long enough path for a quantified pattern;
  18826. // RegexMatcher must refuse to run regex matching on paths beyond
  18827. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18828. detail::RegexMatcher matcher("/files/(.*)");
  18829. Request within_limit;
  18830. within_limit.path = "/files/" + std::string(10, 'A');
  18831. EXPECT_TRUE(matcher.match(within_limit));
  18832. Request over_limit;
  18833. over_limit.path =
  18834. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18835. EXPECT_FALSE(matcher.match(over_limit));
  18836. }
  18837. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18838. Server svr;
  18839. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18840. res.set_content("ok", "text/plain");
  18841. });
  18842. auto port = svr.bind_to_any_port(HOST);
  18843. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18844. auto se = detail::scope_exit([&] {
  18845. svr.stop();
  18846. thread.join();
  18847. ASSERT_FALSE(svr.is_running());
  18848. });
  18849. svr.wait_until_ready();
  18850. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18851. // request URI limit; this used to be able to crash the process.
  18852. std::string path =
  18853. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18854. std::string req = "GET " + path +
  18855. " HTTP/1.1\r\n"
  18856. "Host: " +
  18857. std::string(HOST) + ":" + std::to_string(port) +
  18858. "\r\n"
  18859. "Connection: close\r\n"
  18860. "\r\n";
  18861. std::string response;
  18862. ASSERT_TRUE(send_request(5, req, &response, port));
  18863. EXPECT_NE(std::string::npos, response.find("404"));
  18864. }
  18865. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18866. Server svr;
  18867. auto handler = [](const Request & /*req*/, Response &res) {
  18868. res.set_content("hit", "text/plain");
  18869. };
  18870. // No regex metacharacter, so this one is compared literally
  18871. svr.Get("/literal/route", handler);
  18872. // '.' is a regex metacharacter, so this one must keep regex semantics
  18873. svr.Get("/a.c", handler);
  18874. auto port = svr.bind_to_any_port(HOST);
  18875. std::thread t([&]() { svr.listen_after_bind(); });
  18876. auto se = detail::scope_exit([&] {
  18877. svr.stop();
  18878. t.join();
  18879. ASSERT_FALSE(svr.is_running());
  18880. });
  18881. svr.wait_until_ready();
  18882. Client cli(HOST, port);
  18883. struct {
  18884. const char *path;
  18885. int status;
  18886. } cases[] = {
  18887. {"/literal/route", StatusCode::OK_200},
  18888. {"/literal/routes", StatusCode::NotFound_404},
  18889. {"/literal/rout", StatusCode::NotFound_404},
  18890. {"/abc", StatusCode::OK_200},
  18891. {"/a.c", StatusCode::OK_200},
  18892. };
  18893. for (const auto &x : cases) {
  18894. auto res = cli.Get(x.path);
  18895. ASSERT_TRUE(res) << x.path;
  18896. EXPECT_EQ(x.status, res->status) << x.path;
  18897. }
  18898. }
  18899. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18900. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18901. // from exhausting the stack, so it must only constrain routes that actually
  18902. // run a regular expression. A literal route is matched by comparison and
  18903. // stays usable at any length.
  18904. Server svr;
  18905. const std::string pattern =
  18906. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18907. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18908. res.set_content("hit", "text/plain");
  18909. });
  18910. auto port = svr.bind_to_any_port(HOST);
  18911. std::thread t([&]() { svr.listen_after_bind(); });
  18912. auto se = detail::scope_exit([&] {
  18913. svr.stop();
  18914. t.join();
  18915. ASSERT_FALSE(svr.is_running());
  18916. });
  18917. svr.wait_until_ready();
  18918. Client cli(HOST, port);
  18919. auto res = cli.Get(pattern);
  18920. ASSERT_TRUE(res);
  18921. EXPECT_EQ(StatusCode::OK_200, res->status);
  18922. }
  18923. TEST(ParseUrlTest, VariousPatterns) {
  18924. {
  18925. detail::UrlComponents uc;
  18926. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18927. EXPECT_EQ("http", uc.scheme);
  18928. EXPECT_EQ("example.com", uc.host);
  18929. EXPECT_EQ("8080", uc.port);
  18930. EXPECT_EQ("/path", uc.path);
  18931. EXPECT_EQ("?q=1", uc.query);
  18932. }
  18933. {
  18934. detail::UrlComponents uc;
  18935. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18936. EXPECT_EQ("https", uc.scheme);
  18937. EXPECT_EQ("example.com", uc.host);
  18938. EXPECT_TRUE(uc.port.empty());
  18939. EXPECT_EQ("/path", uc.path);
  18940. }
  18941. {
  18942. detail::UrlComponents uc;
  18943. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18944. EXPECT_EQ("::1", uc.host);
  18945. EXPECT_EQ("8080", uc.port);
  18946. EXPECT_EQ("/path", uc.path);
  18947. }
  18948. {
  18949. detail::UrlComponents uc;
  18950. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18951. }
  18952. {
  18953. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18954. // the path while the connection still targets the bracketed host.
  18955. detail::UrlComponents uc;
  18956. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18957. }
  18958. {
  18959. detail::UrlComponents uc;
  18960. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18961. }
  18962. {
  18963. detail::UrlComponents uc;
  18964. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18965. EXPECT_EQ("::1", uc.host);
  18966. EXPECT_TRUE(uc.port.empty());
  18967. EXPECT_EQ("/path", uc.path);
  18968. }
  18969. {
  18970. detail::UrlComponents uc;
  18971. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18972. EXPECT_TRUE(uc.scheme.empty());
  18973. EXPECT_EQ("example.com", uc.host);
  18974. EXPECT_EQ("/path", uc.path);
  18975. EXPECT_EQ("?q=1", uc.query);
  18976. }
  18977. {
  18978. detail::UrlComponents uc;
  18979. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18980. EXPECT_TRUE(uc.host.empty());
  18981. EXPECT_EQ("/path", uc.path);
  18982. EXPECT_EQ("?q=1", uc.query);
  18983. }
  18984. {
  18985. detail::UrlComponents uc;
  18986. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18987. EXPECT_EQ("example.com", uc.host);
  18988. EXPECT_EQ("8080", uc.port);
  18989. }
  18990. {
  18991. // Unix socket path — must not be parsed as host
  18992. detail::UrlComponents uc;
  18993. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18994. EXPECT_TRUE(uc.host.empty());
  18995. }
  18996. {
  18997. detail::UrlComponents uc;
  18998. ASSERT_TRUE(detail::parse_url("", uc));
  18999. EXPECT_TRUE(uc.host.empty());
  19000. EXPECT_TRUE(uc.path.empty());
  19001. }
  19002. {
  19003. detail::UrlComponents uc;
  19004. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  19005. EXPECT_EQ("http", uc.scheme);
  19006. }
  19007. {
  19008. detail::UrlComponents uc;
  19009. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  19010. }
  19011. {
  19012. // Accepted by parse_url; callers restrict to http/https
  19013. detail::UrlComponents uc;
  19014. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  19015. EXPECT_EQ("ftp", uc.scheme);
  19016. }
  19017. {
  19018. detail::UrlComponents uc;
  19019. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  19020. }
  19021. {
  19022. detail::UrlComponents uc;
  19023. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  19024. }
  19025. }
  19026. TEST(ParseUrlTest, FragmentHandling) {
  19027. {
  19028. detail::UrlComponents uc;
  19029. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  19030. EXPECT_EQ("/path", uc.path);
  19031. EXPECT_TRUE(uc.query.empty());
  19032. }
  19033. {
  19034. detail::UrlComponents uc;
  19035. ASSERT_TRUE(detail::parse_url("#frag", uc));
  19036. EXPECT_TRUE(uc.path.empty());
  19037. EXPECT_TRUE(uc.query.empty());
  19038. }
  19039. }
  19040. TEST(ParseUrlTest, UserinfoHandling) {
  19041. // userinfo, and a backslash some parsers take for '/', are rejected: such
  19042. // parsers would see evil.com as the host.
  19043. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  19044. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  19045. for (auto url : urls) {
  19046. detail::UrlComponents uc;
  19047. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  19048. }
  19049. }
  19050. TEST(ParseUrlTest, IPv6EdgeCases) {
  19051. {
  19052. detail::UrlComponents uc;
  19053. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  19054. EXPECT_TRUE(uc.scheme.empty());
  19055. EXPECT_EQ("::1", uc.host);
  19056. EXPECT_EQ("8080", uc.port);
  19057. }
  19058. {
  19059. // Zone ID '%25' is not in [a-fA-F0-9:]
  19060. detail::UrlComponents uc;
  19061. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  19062. }
  19063. }
  19064. TEST(ParseUrlTest, SchemeEdgeCases) {
  19065. {
  19066. detail::UrlComponents uc;
  19067. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  19068. }
  19069. {
  19070. detail::UrlComponents uc;
  19071. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  19072. }
  19073. {
  19074. detail::UrlComponents uc;
  19075. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  19076. }
  19077. {
  19078. detail::UrlComponents uc;
  19079. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  19080. EXPECT_EQ("https", uc.scheme);
  19081. }
  19082. {
  19083. detail::UrlComponents uc;
  19084. ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
  19085. EXPECT_TRUE(uc.scheme.empty());
  19086. EXPECT_TRUE(uc.host.empty());
  19087. EXPECT_EQ("/path", uc.path);
  19088. EXPECT_EQ("?next=https://example.com/", uc.query);
  19089. }
  19090. }
  19091. TEST(ParseUrlTest, PortEdgeCases) {
  19092. {
  19093. detail::UrlComponents uc;
  19094. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  19095. EXPECT_TRUE(uc.port.empty());
  19096. EXPECT_EQ("/path", uc.path);
  19097. }
  19098. {
  19099. // parse_url accepts any port string; validation is done by parse_port
  19100. detail::UrlComponents uc;
  19101. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  19102. EXPECT_EQ("abc", uc.port);
  19103. }
  19104. }
  19105. TEST(ParseUrlTest, WebSocketPatterns) {
  19106. {
  19107. detail::UrlComponents uc;
  19108. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  19109. EXPECT_EQ("ws", uc.scheme);
  19110. EXPECT_EQ("echo.example.com", uc.host);
  19111. EXPECT_EQ("8080", uc.port);
  19112. EXPECT_EQ("/ws", uc.path);
  19113. }
  19114. {
  19115. detail::UrlComponents uc;
  19116. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  19117. EXPECT_EQ("wss", uc.scheme);
  19118. EXPECT_EQ("echo.example.com", uc.host);
  19119. EXPECT_TRUE(uc.port.empty());
  19120. EXPECT_EQ("/ws", uc.path);
  19121. }
  19122. }
  19123. TEST(ParseUrlTest, QueryOnly) {
  19124. detail::UrlComponents uc;
  19125. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  19126. EXPECT_TRUE(uc.host.empty());
  19127. EXPECT_TRUE(uc.path.empty());
  19128. EXPECT_EQ("?q=1&r=2", uc.query);
  19129. }
  19130. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  19131. detail::UrlComponents uc;
  19132. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  19133. EXPECT_TRUE(uc.scheme.empty());
  19134. EXPECT_EQ("example.com", uc.host);
  19135. EXPECT_EQ("443", uc.port);
  19136. EXPECT_EQ("/path", uc.path);
  19137. }
  19138. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  19139. // If ipv6 regex working, regex match codepath is taken.
  19140. // else port will default to 80 in Client impl
  19141. int clientImplMagicPort = 80;
  19142. int port = 4321;
  19143. // above ports must be different to avoid false negative
  19144. EXPECT_NE(clientImplMagicPort, port);
  19145. std::string ipV6TestURL = "http://[ff06::c3]";
  19146. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  19147. CLIENT_PRIVATE_KEY_FILE);
  19148. EXPECT_EQ(cli.port(), port);
  19149. }
  19150. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  19151. auto file_path = "./www/dir/index.html";
  19152. auto dir_path = "./www/dir";
  19153. detail::FileStat stat_file(file_path);
  19154. EXPECT_TRUE(stat_file.is_file());
  19155. EXPECT_FALSE(stat_file.is_dir());
  19156. detail::FileStat stat_dir(dir_path);
  19157. EXPECT_FALSE(stat_dir.is_file());
  19158. EXPECT_TRUE(stat_dir.is_dir());
  19159. }
  19160. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  19161. // IPv4 with default HTTP port (80)
  19162. EXPECT_EQ("example.com",
  19163. detail::make_host_and_port_string("example.com", 80, false));
  19164. // IPv4 with default HTTPS port (443)
  19165. EXPECT_EQ("example.com",
  19166. detail::make_host_and_port_string("example.com", 443, true));
  19167. // IPv4 with non-default HTTP port
  19168. EXPECT_EQ("example.com:8080",
  19169. detail::make_host_and_port_string("example.com", 8080, false));
  19170. // IPv4 with non-default HTTPS port
  19171. EXPECT_EQ("example.com:8443",
  19172. detail::make_host_and_port_string("example.com", 8443, true));
  19173. // IPv6 with default HTTP port (80)
  19174. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  19175. // IPv6 with default HTTPS port (443)
  19176. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  19177. // IPv6 with non-default HTTP port
  19178. EXPECT_EQ("[::1]:8080",
  19179. detail::make_host_and_port_string("::1", 8080, false));
  19180. // IPv6 with non-default HTTPS port
  19181. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  19182. // IPv6 full address with default port
  19183. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  19184. detail::make_host_and_port_string(
  19185. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  19186. // IPv6 full address with non-default port
  19187. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  19188. detail::make_host_and_port_string(
  19189. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  19190. // IPv6 localhost with non-default port
  19191. EXPECT_EQ("[::1]:3000",
  19192. detail::make_host_and_port_string("::1", 3000, false));
  19193. // IPv6 with zone ID (link-local address) with default port
  19194. EXPECT_EQ("[fe80::1%eth0]",
  19195. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19196. // IPv6 with zone ID (link-local address) with non-default port
  19197. EXPECT_EQ("[fe80::1%eth0]:8080",
  19198. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19199. // Edge case: Port 443 with is_ssl=false (should add port)
  19200. EXPECT_EQ("example.com:443",
  19201. detail::make_host_and_port_string("example.com", 443, false));
  19202. // Edge case: Port 80 with is_ssl=true (should add port)
  19203. EXPECT_EQ("example.com:80",
  19204. detail::make_host_and_port_string("example.com", 80, true));
  19205. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19206. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19207. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19208. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19209. // Security fix: Already bracketed IPv6 should not get double brackets
  19210. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19211. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19212. EXPECT_EQ("[::1]:8080",
  19213. detail::make_host_and_port_string("[::1]", 8080, false));
  19214. EXPECT_EQ("[2001:db8::1]:8080",
  19215. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19216. EXPECT_EQ("[fe80::1%eth0]",
  19217. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19218. EXPECT_EQ("[fe80::1%eth0]:8080",
  19219. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19220. // Edge case: Empty host (should return as-is)
  19221. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19222. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19223. // This is a known limitation but shouldn't crash
  19224. EXPECT_EQ("[host:name]",
  19225. detail::make_host_and_port_string("host:name", 80, false));
  19226. // Port number edge cases (no validation, but should not crash)
  19227. EXPECT_EQ("example.com:0",
  19228. detail::make_host_and_port_string("example.com", 0, false));
  19229. EXPECT_EQ("example.com:-1",
  19230. detail::make_host_and_port_string("example.com", -1, false));
  19231. EXPECT_EQ("example.com:65535",
  19232. detail::make_host_and_port_string("example.com", 65535, false));
  19233. EXPECT_EQ("example.com:65536",
  19234. detail::make_host_and_port_string("example.com", 65536, false));
  19235. }
  19236. namespace httplib {
  19237. namespace detail {
  19238. std::string
  19239. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19240. const std::string &host, int port);
  19241. } // namespace detail
  19242. } // namespace httplib
  19243. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19244. std::map<std::string, std::string> addr_map = {
  19245. {"ipv4.example", "192.0.2.10"},
  19246. {"ipv6.example", "2001:db8::1"},
  19247. {"name.example", "internal.example.lan"},
  19248. {"empty.example", ""}};
  19249. EXPECT_EQ("192.0.2.10:443",
  19250. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19251. EXPECT_EQ("[2001:db8::1]:443",
  19252. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19253. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19254. addr_map, "name.example", 8443));
  19255. // An empty or absent mapping keeps the hostname as the target
  19256. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19257. addr_map, "empty.example", 443));
  19258. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19259. addr_map, "other.example", 443));
  19260. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19261. }
  19262. #ifdef CPPHTTPLIB_SSL_ENABLED
  19263. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19264. httplib::SSLClient cli("roblox.com", 443);
  19265. cli.set_follow_location(true);
  19266. auto res = cli.Get("/");
  19267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19268. EXPECT_EQ(StatusCode::OK_200, res->status);
  19269. }
  19270. #endif
  19271. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19272. Server svr;
  19273. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19274. EXPECT_EQ(res.status, 400);
  19275. });
  19276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19277. auto se = detail::scope_exit([&] {
  19278. svr.stop();
  19279. thread.join();
  19280. ASSERT_FALSE(svr.is_running());
  19281. });
  19282. svr.wait_until_ready();
  19283. Client cli(HOST, PORT);
  19284. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19285. }
  19286. TEST(InvalidHeaderCharsTest, is_field_name) {
  19287. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19288. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19289. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19290. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19291. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19292. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19293. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19294. EXPECT_FALSE(detail::fields::is_field_name(""));
  19295. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19296. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19297. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19298. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19299. }
  19300. TEST(InvalidHeaderCharsTest, is_field_value) {
  19301. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19302. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19303. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19304. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19305. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19306. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19307. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19308. EXPECT_TRUE(detail::fields::is_field_value(""));
  19309. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19310. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19311. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19312. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19313. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19314. }
  19315. TEST(InvalidHeaderCharsTest, OnServer) {
  19316. Server svr;
  19317. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19318. std::string header = "Not Set";
  19319. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19320. res.set_header(header, "value");
  19321. res.set_content("Page Content Page Content", "text/plain");
  19322. });
  19323. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19324. std::string header = "Not Set";
  19325. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19326. res.set_header("X-Test", header);
  19327. res.set_content("Page Content Page Content", "text/plain");
  19328. });
  19329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19330. auto se = detail::scope_exit([&] {
  19331. svr.stop();
  19332. thread.join();
  19333. ASSERT_FALSE(svr.is_running());
  19334. });
  19335. svr.wait_until_ready();
  19336. Client cli(HOST, PORT);
  19337. {
  19338. auto res = cli.Get(
  19339. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19341. EXPECT_EQ("Page Content Page Content", res->body);
  19342. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19343. }
  19344. {
  19345. auto res = cli.Get(
  19346. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19348. EXPECT_EQ("Page Content Page Content", res->body);
  19349. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19350. }
  19351. }
  19352. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19353. auto handled = false;
  19354. Server svr;
  19355. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19356. thread t = thread([&] { svr.listen(HOST, PORT); });
  19357. auto se = detail::scope_exit([&] {
  19358. svr.stop();
  19359. t.join();
  19360. ASSERT_FALSE(svr.is_running());
  19361. ASSERT_FALSE(handled);
  19362. });
  19363. svr.wait_until_ready();
  19364. auto req = "POST /test HTTP/1.1\r\n"
  19365. "Content-Length: x\r\n"
  19366. "\r\n";
  19367. std::string response;
  19368. ASSERT_TRUE(send_request(1, req, &response));
  19369. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19370. response.substr(0, response.find("\r\n")));
  19371. }
  19372. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19373. // case-insensitive, and a server that receives a 100-continue expectation in
  19374. // an HTTP/1.0 request MUST ignore it.
  19375. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19376. std::string response;
  19377. ASSERT_TRUE(send_request(1, req, &response, port));
  19378. *got_100 = response.find("100 Continue") != std::string::npos;
  19379. }
  19380. class ExpectTokenTest : public ::testing::Test {
  19381. protected:
  19382. void SetUp() override {
  19383. svr_.Post("/p", [](const Request &, Response &res) {
  19384. res.set_content("ok", "text/plain");
  19385. });
  19386. port_ = svr_.bind_to_any_port(HOST);
  19387. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19388. svr_.wait_until_ready();
  19389. }
  19390. void TearDown() override {
  19391. svr_.stop();
  19392. if (thread_.joinable()) { thread_.join(); }
  19393. }
  19394. std::string request(const char *version, const char *expect_value) const {
  19395. return std::string("POST /p ") + version +
  19396. "\r\n"
  19397. "Host: localhost\r\n"
  19398. "Content-Length: 2\r\n"
  19399. "Connection: close\r\n"
  19400. "Expect: " +
  19401. expect_value +
  19402. "\r\n"
  19403. "\r\n"
  19404. "hi";
  19405. }
  19406. Server svr_;
  19407. int port_ = 0;
  19408. thread thread_;
  19409. };
  19410. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19411. bool got_100 = false;
  19412. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19413. EXPECT_TRUE(got_100);
  19414. }
  19415. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19416. bool got_100 = true;
  19417. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19418. EXPECT_FALSE(got_100);
  19419. }
  19420. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19421. bool got_100 = false;
  19422. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19423. EXPECT_TRUE(got_100);
  19424. }
  19425. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19426. bool got_100 = false;
  19427. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19428. EXPECT_TRUE(got_100);
  19429. }
  19430. // `100 Continue` is sent only when the server starts reading the body, so a
  19431. // request rejected before that never invites the client to send it. The
  19432. // requests below carry the expectation but withhold the body, as a client
  19433. // waiting for `100 Continue` would.
  19434. // A POST that expects `100 Continue` and withholds its two-byte body.
  19435. static std::string expect_headers_only(const std::string &path) {
  19436. return "POST " + path +
  19437. " HTTP/1.1\r\n"
  19438. "Host: localhost\r\n"
  19439. "Content-Length: 2\r\n"
  19440. "Expect: 100-continue\r\n"
  19441. "\r\n";
  19442. }
  19443. class ExpectLazyContinueTest : public ::testing::Test {
  19444. protected:
  19445. void SetUp() override {
  19446. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19447. if (req.path == "/pre-routing") {
  19448. res.status = StatusCode::Unauthorized_401;
  19449. return Server::HandlerResponse::Handled;
  19450. }
  19451. return Server::HandlerResponse::Unhandled;
  19452. });
  19453. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19454. if (req.matched_route == "/pre-request") {
  19455. res.status = StatusCode::Forbidden_403;
  19456. return Server::HandlerResponse::Handled;
  19457. }
  19458. return Server::HandlerResponse::Unhandled;
  19459. });
  19460. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19461. res.set_content("ok", "text/plain");
  19462. });
  19463. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19464. res.set_content("ok", "text/plain");
  19465. });
  19466. svr_.Post("/reader-used", [](const Request &, Response &res,
  19467. const ContentReader &content_reader) {
  19468. std::string body;
  19469. content_reader([&](const char *data, size_t len) {
  19470. body.append(data, len);
  19471. return true;
  19472. });
  19473. res.set_content(body, "text/plain");
  19474. });
  19475. svr_.Post("/reader-unused",
  19476. [](const Request &, Response &res, const ContentReader &) {
  19477. res.set_content("ignored", "text/plain");
  19478. });
  19479. port_ = svr_.bind_to_any_port(HOST);
  19480. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19481. svr_.wait_until_ready();
  19482. }
  19483. void TearDown() override {
  19484. svr_.stop();
  19485. if (thread_.joinable()) { thread_.join(); }
  19486. }
  19487. // Sends `req` and reads until the server closes the connection. Returns
  19488. // false if the read had to wait for the client-side timeout instead.
  19489. bool send_until_closed(const std::string &req, std::string *resp) const {
  19490. auto start = std::chrono::steady_clock::now();
  19491. if (!send_request(3, req, resp, port_)) { return false; }
  19492. auto elapsed = std::chrono::steady_clock::now() - start;
  19493. return elapsed < std::chrono::seconds(2);
  19494. }
  19495. // The final response comes without `100 Continue`, and the server closes
  19496. // the connection since the body may or may not follow.
  19497. void expect_final_without_interim(const std::string &path,
  19498. const char *status_line) const {
  19499. std::string resp;
  19500. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19501. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19502. EXPECT_EQ(0u, resp.find(status_line));
  19503. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19504. }
  19505. Server svr_;
  19506. int port_ = 0;
  19507. thread thread_;
  19508. };
  19509. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19510. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19511. }
  19512. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19513. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19514. }
  19515. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19516. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19517. }
  19518. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19519. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19520. }
  19521. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19522. // The body follows once `100 Continue` has had time to arrive.
  19523. auto req = expect_headers_only("/reader-used");
  19524. req.insert(req.size() - 2, "Connection: close\r\n");
  19525. std::string resp;
  19526. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19527. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19528. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19529. EXPECT_NE(std::string::npos, resp.find("hi"));
  19530. }
  19531. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19532. // Large enough for the client to add `Expect: 100-continue` itself.
  19533. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19534. std::atomic<bool> body_sent{false};
  19535. Client cli(HOST, port_);
  19536. auto res = cli.Post(
  19537. "/pre-request", length,
  19538. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19539. body_sent = true;
  19540. std::string chunk(len, 'x');
  19541. sink.write(chunk.data(), chunk.size());
  19542. return true;
  19543. },
  19544. "application/octet-stream");
  19545. ASSERT_TRUE(res);
  19546. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19547. EXPECT_FALSE(body_sent);
  19548. }
  19549. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19550. Server svr;
  19551. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19552. return StatusCode::ExpectationFailed_417;
  19553. });
  19554. svr.Post("/p", [](const Request &, Response &res) {
  19555. res.set_content("ok", "text/plain");
  19556. });
  19557. auto port = svr.bind_to_any_port(HOST);
  19558. thread t = thread([&] { svr.listen_after_bind(); });
  19559. auto se = detail::scope_exit([&] {
  19560. svr.stop();
  19561. t.join();
  19562. });
  19563. svr.wait_until_ready();
  19564. std::string resp;
  19565. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19566. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19567. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19568. // Exactly one response: the route handler must not run after the 417.
  19569. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19570. }
  19571. #ifndef _WIN32
  19572. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19573. static constexpr char reject[] = "Unauthorized";
  19574. static constexpr char accept[] = "Upload accepted";
  19575. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19576. Server svr;
  19577. svr.set_expect_100_continue_handler(
  19578. [](const Request & /*req*/, Response &res) {
  19579. res.status = StatusCode::Unauthorized_401;
  19580. res.set_content(reject, "text/plain");
  19581. return res.status;
  19582. });
  19583. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19584. res.set_content(accept, "text/plain");
  19585. });
  19586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19587. auto se = detail::scope_exit([&] {
  19588. svr.stop();
  19589. thread.join();
  19590. ASSERT_FALSE(svr.is_running());
  19591. });
  19592. svr.wait_until_ready();
  19593. {
  19594. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19595. curl_easy_init(), &curl_easy_cleanup};
  19596. ASSERT_NE(curl, nullptr);
  19597. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19598. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19599. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19600. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19601. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19602. &curl_slist_free_all};
  19603. ASSERT_NE(list, nullptr);
  19604. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19605. struct read_data {
  19606. uint64_t read_size;
  19607. uint64_t total_size;
  19608. } data = {0, total_size};
  19609. using read_callback_t =
  19610. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19611. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19612. void *userdata) -> size_t {
  19613. read_data *d = (read_data *)userdata;
  19614. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19615. std::fill_n(ptr, size * nmemb, 'A');
  19616. d->read_size += size * nmemb;
  19617. return size * nmemb;
  19618. };
  19619. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19620. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19621. std::vector<char> buffer;
  19622. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19623. using write_callback_t =
  19624. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19625. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19626. void *userdata) -> size_t {
  19627. std::vector<char> *buf = (std::vector<char> *)userdata;
  19628. buf->reserve(buf->size() + size * nmemb + 1);
  19629. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19630. return size * nmemb;
  19631. };
  19632. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19633. {
  19634. const auto res = curl_easy_perform(curl.get());
  19635. ASSERT_EQ(res, CURLE_OK);
  19636. }
  19637. {
  19638. auto response_code = long{};
  19639. const auto res =
  19640. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19641. ASSERT_EQ(res, CURLE_OK);
  19642. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19643. }
  19644. {
  19645. auto dl = curl_off_t{};
  19646. const auto res =
  19647. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19648. ASSERT_EQ(res, CURLE_OK);
  19649. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19650. }
  19651. {
  19652. buffer.push_back('\0');
  19653. ASSERT_STRCASEEQ(buffer.data(), reject);
  19654. }
  19655. }
  19656. }
  19657. #endif
  19658. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19659. // Regression test for #2458.
  19660. //
  19661. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19662. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19663. // ticket can make the client socket spuriously readable during the
  19664. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19665. // the client withholds the body and then blocks reading a response that never
  19666. // comes, failing with `Failed to read connection`.
  19667. //
  19668. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19669. // within the timeout. This raw OpenSSL server deliberately never sends
  19670. // `100 Continue`; the client must still deliver the body and receive 200.
  19671. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19672. signal(SIGPIPE, SIG_IGN);
  19673. const auto port = PORT + 4;
  19674. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19675. ASSERT_NE(srv, INVALID_SOCKET);
  19676. int opt = 1;
  19677. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19678. sockaddr_in addr{};
  19679. addr.sin_family = AF_INET;
  19680. addr.sin_port = htons(static_cast<uint16_t>(port));
  19681. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19682. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19683. ASSERT_EQ(0, ::listen(srv, 1));
  19684. std::atomic<size_t> server_body_bytes{0};
  19685. auto server_thread = std::thread([&] {
  19686. sockaddr_in cli_addr{};
  19687. socklen_t cli_len = sizeof(cli_addr);
  19688. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19689. if (cli == INVALID_SOCKET) { return; }
  19690. // Bound the lifetime of the server side so a buggy client (which never
  19691. // sends the body) cannot make this thread block forever on join.
  19692. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19693. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19694. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19695. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19696. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19697. SSL *ssl = SSL_new(ctx);
  19698. SSL_set_fd(ssl, static_cast<int>(cli));
  19699. if (SSL_accept(ssl) > 0) {
  19700. // Read the request headers. Reading here also flushes the TLS 1.3
  19701. // session tickets to the client. Deliberately do NOT send
  19702. // `100 Continue`.
  19703. std::string buf;
  19704. char tmp[1024];
  19705. while (buf.find("\r\n\r\n") == std::string::npos) {
  19706. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19707. if (n <= 0) { break; }
  19708. buf.append(tmp, static_cast<size_t>(n));
  19709. }
  19710. // A correct client sends the body now; count what arrives.
  19711. auto pos = buf.find("\r\n\r\n");
  19712. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19713. while (body < 4096) {
  19714. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19715. if (n <= 0) { break; }
  19716. body += static_cast<size_t>(n);
  19717. }
  19718. server_body_bytes = body;
  19719. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19720. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19721. SSL_shutdown(ssl);
  19722. }
  19723. SSL_free(ssl);
  19724. detail::close_socket(cli);
  19725. SSL_CTX_free(ctx);
  19726. });
  19727. auto se = detail::scope_exit([&] {
  19728. server_thread.join();
  19729. detail::close_socket(srv);
  19730. });
  19731. SSLClient cli("127.0.0.1", port);
  19732. cli.enable_server_certificate_verification(false);
  19733. cli.set_connection_timeout(5, 0);
  19734. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19735. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19736. std::string body(4096, 'A');
  19737. auto res = cli.Put("/api/test", body, "application/json");
  19738. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19739. EXPECT_EQ(StatusCode::OK_200, res->status);
  19740. EXPECT_EQ(body.size(), server_body_bytes.load());
  19741. }
  19742. #endif
  19743. template <typename S, typename C>
  19744. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19745. svr.Get("/stream", [&](const Request &, Response &res) {
  19746. auto data = new std::string("01234567890123456789");
  19747. res.set_content_provider(
  19748. data->size(), "text/plain",
  19749. [&, data](size_t offset, size_t length, DataSink &sink) {
  19750. const size_t DATA_CHUNK_SIZE = 4;
  19751. const auto &d = *data;
  19752. std::this_thread::sleep_for(std::chrono::seconds(1));
  19753. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19754. return true;
  19755. },
  19756. [data](bool success) {
  19757. EXPECT_FALSE(success);
  19758. delete data;
  19759. });
  19760. });
  19761. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19762. auto i = new size_t(0);
  19763. res.set_content_provider(
  19764. "text/plain",
  19765. [i](size_t, DataSink &sink) {
  19766. if (*i < 5) {
  19767. std::this_thread::sleep_for(std::chrono::seconds(1));
  19768. sink.write("abcd", 4);
  19769. (*i)++;
  19770. } else {
  19771. sink.done();
  19772. }
  19773. return true;
  19774. },
  19775. [i](bool success) {
  19776. EXPECT_FALSE(success);
  19777. delete i;
  19778. });
  19779. });
  19780. svr.Get("/chunked", [&](const Request &, Response &res) {
  19781. auto i = new size_t(0);
  19782. res.set_chunked_content_provider(
  19783. "text/plain",
  19784. [i](size_t, DataSink &sink) {
  19785. if (*i < 5) {
  19786. std::this_thread::sleep_for(std::chrono::seconds(1));
  19787. sink.os << "abcd";
  19788. (*i)++;
  19789. } else {
  19790. sink.done();
  19791. }
  19792. return true;
  19793. },
  19794. [i](bool success) {
  19795. EXPECT_FALSE(success);
  19796. delete i;
  19797. });
  19798. });
  19799. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19800. auto se = detail::scope_exit([&] {
  19801. svr.stop();
  19802. listen_thread.join();
  19803. ASSERT_FALSE(svr.is_running());
  19804. });
  19805. svr.wait_until_ready();
  19806. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19807. {
  19808. auto start = std::chrono::steady_clock::now();
  19809. auto res = cli.Get("/stream");
  19810. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19811. std::chrono::steady_clock::now() - start)
  19812. .count();
  19813. ASSERT_FALSE(res);
  19814. EXPECT_EQ(Error::Read, res.error());
  19815. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19816. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19817. }
  19818. {
  19819. auto start = std::chrono::steady_clock::now();
  19820. auto res = cli.Get("/stream_without_length");
  19821. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19822. std::chrono::steady_clock::now() - start)
  19823. .count();
  19824. ASSERT_FALSE(res);
  19825. EXPECT_EQ(Error::Read, res.error());
  19826. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19827. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19828. }
  19829. {
  19830. auto start = std::chrono::steady_clock::now();
  19831. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19832. EXPECT_EQ("abcd", string(data, data_length));
  19833. return true;
  19834. });
  19835. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19836. std::chrono::steady_clock::now() - start)
  19837. .count();
  19838. ASSERT_FALSE(res);
  19839. EXPECT_EQ(Error::Read, res.error());
  19840. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19841. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19842. }
  19843. }
  19844. TEST(MaxTimeoutTest, ContentStream) {
  19845. time_t timeout = 2000;
  19846. time_t threshold = 200;
  19847. Server svr;
  19848. Client cli("localhost", PORT);
  19849. max_timeout_test(svr, cli, timeout, threshold);
  19850. }
  19851. #ifdef CPPHTTPLIB_SSL_ENABLED
  19852. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19853. time_t timeout = 2000;
  19854. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19856. SSLClient cli("localhost", PORT);
  19857. cli.enable_server_certificate_verification(false);
  19858. max_timeout_test(svr, cli, timeout, threshold);
  19859. }
  19860. #endif
  19861. class EventDispatcher {
  19862. public:
  19863. EventDispatcher() {}
  19864. bool wait_event(DataSink *sink) {
  19865. unique_lock<mutex> lk(m_);
  19866. int id = id_;
  19867. // Wait with timeout to prevent hanging if client disconnects
  19868. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19869. [&] { return cid_ == id; })) {
  19870. return false; // Timeout occurred
  19871. }
  19872. sink->write(message_.data(), message_.size());
  19873. return true;
  19874. }
  19875. void send_event(const string &message) {
  19876. lock_guard<mutex> lk(m_);
  19877. cid_ = id_++;
  19878. message_ = message;
  19879. cv_.notify_all();
  19880. }
  19881. private:
  19882. mutex m_;
  19883. condition_variable cv_;
  19884. atomic_int id_{0};
  19885. atomic_int cid_{-1};
  19886. string message_;
  19887. };
  19888. TEST(ClientInThreadTest, Issue2068) {
  19889. EventDispatcher ed;
  19890. Server svr;
  19891. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19892. res.set_chunked_content_provider("text/event-stream",
  19893. [&](size_t /*offset*/, DataSink &sink) {
  19894. return ed.wait_event(&sink);
  19895. });
  19896. });
  19897. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19898. svr.wait_until_ready();
  19899. thread event_thread([&] {
  19900. int id = 0;
  19901. while (svr.is_running()) {
  19902. this_thread::sleep_for(chrono::milliseconds(500));
  19903. std::stringstream ss;
  19904. ss << "data: " << id << "\n\n";
  19905. ed.send_event(ss.str());
  19906. id++;
  19907. }
  19908. });
  19909. auto se = detail::scope_exit([&] {
  19910. svr.stop();
  19911. listen_thread.join();
  19912. event_thread.join();
  19913. ASSERT_FALSE(svr.is_running());
  19914. });
  19915. {
  19916. auto client = detail::make_unique<Client>(HOST, PORT);
  19917. client->set_read_timeout(std::chrono::minutes(10));
  19918. std::atomic<bool> stop{false};
  19919. std::thread t([&] {
  19920. client->Get("/event1",
  19921. [&](const char *, size_t) -> bool { return !stop; });
  19922. });
  19923. std::this_thread::sleep_for(std::chrono::seconds(2));
  19924. stop = true;
  19925. client->stop();
  19926. t.join();
  19927. // Reset client after thread has finished
  19928. client.reset();
  19929. }
  19930. }
  19931. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19932. auto handled = false;
  19933. Server svr;
  19934. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19935. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19936. auto se = detail::scope_exit([&] {
  19937. svr.stop();
  19938. t.join();
  19939. ASSERT_FALSE(svr.is_running());
  19940. ASSERT_FALSE(handled);
  19941. });
  19942. svr.wait_until_ready();
  19943. // Two Content-Length headers with different values — must be rejected
  19944. auto req = "POST /test HTTP/1.1\r\n"
  19945. "Content-Length: 5\r\n"
  19946. "Content-Length: 10\r\n"
  19947. "\r\n"
  19948. "hello";
  19949. std::string response;
  19950. ASSERT_TRUE(send_request(1, req, &response));
  19951. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19952. response.substr(0, response.find("\r\n")));
  19953. }
  19954. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19955. auto handled = false;
  19956. Server svr;
  19957. svr.Post("/test", [&](const Request &, Response &res) {
  19958. handled = true;
  19959. res.set_content("ok", "text/plain");
  19960. });
  19961. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19962. auto se = detail::scope_exit([&] {
  19963. svr.stop();
  19964. t.join();
  19965. ASSERT_FALSE(svr.is_running());
  19966. ASSERT_TRUE(handled);
  19967. });
  19968. svr.wait_until_ready();
  19969. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19970. auto req = "POST /test HTTP/1.1\r\n"
  19971. "Host: localhost\r\n"
  19972. "Content-Length: 5\r\n"
  19973. "Content-Length: 5\r\n"
  19974. "\r\n"
  19975. "hello";
  19976. std::string response;
  19977. ASSERT_TRUE(send_request(1, req, &response));
  19978. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19979. }
  19980. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19981. Server svr;
  19982. svr.Get("/test", [](const Request &, Response &res) {
  19983. res.set_content("ok", "text/plain");
  19984. });
  19985. auto port = svr.bind_to_any_port(HOST);
  19986. thread t = thread([&] { svr.listen_after_bind(); });
  19987. auto se = detail::scope_exit([&] {
  19988. svr.stop();
  19989. t.join();
  19990. ASSERT_FALSE(svr.is_running());
  19991. });
  19992. svr.wait_until_ready();
  19993. auto status_line = [&](const std::string &host_lines) {
  19994. std::string res;
  19995. send_request(
  19996. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19997. &res, port);
  19998. return res.substr(0, res.find("\r\n"));
  19999. };
  20000. const char *accepted[] = {
  20001. "Host: localhost\r\n",
  20002. "Host: a.example:8080\r\n",
  20003. "Host: my_service\r\n",
  20004. "Host: [::1]:8080\r\n",
  20005. "Host: [fe80::1%25eth0]\r\n",
  20006. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  20007. };
  20008. for (auto host_lines : accepted) {
  20009. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  20010. }
  20011. const char *rejected[] = {
  20012. "Host: a.example\r\nHost: b.example\r\n",
  20013. "Host: a.example\r\nHost: a.example\r\n",
  20014. "Host: a@b.example\r\n",
  20015. "Host: a.example/b\r\n",
  20016. "Host: a.example\\b\r\n",
  20017. "Host: a.example?b\r\n",
  20018. "Host: a.example#b\r\n",
  20019. "Host: a.example b.example\r\n",
  20020. };
  20021. for (auto host_lines : rejected) {
  20022. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  20023. << host_lines;
  20024. }
  20025. }
  20026. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  20027. Server svr;
  20028. svr.Get("/", [](const Request &req, Response &res) {
  20029. EXPECT_EQ(2U, req.trailers.size());
  20030. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  20031. // Denied
  20032. EXPECT_FALSE(req.has_trailer("Content-Length"));
  20033. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  20034. // Accepted
  20035. EXPECT_TRUE(req.has_trailer("X-Hello"));
  20036. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  20037. EXPECT_TRUE(req.has_trailer("X-World"));
  20038. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  20039. res.set_content("ok", "text/plain");
  20040. });
  20041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20042. auto se = detail::scope_exit([&] {
  20043. svr.stop();
  20044. t.join();
  20045. ASSERT_FALSE(svr.is_running());
  20046. });
  20047. svr.wait_until_ready();
  20048. const std::string req = "GET / HTTP/1.1\r\n"
  20049. "Transfer-Encoding: chunked\r\n"
  20050. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  20051. "\r\n"
  20052. "0\r\n"
  20053. "Content-Length: 10\r\n"
  20054. "Host: internal.local\r\n"
  20055. "Content-Type: malicious/content\r\n"
  20056. "Cookie: any\r\n"
  20057. "Set-Cookie: any\r\n"
  20058. "X-Forwarded-For: attacker.com\r\n"
  20059. "X-Real-Ip: 1.1.1.1\r\n"
  20060. "X-Hello: hello\r\n"
  20061. "X-World: world\r\n"
  20062. "\r\n";
  20063. std::string res;
  20064. ASSERT_TRUE(send_request(1, req, &res));
  20065. }
  20066. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  20067. // several field lines, and the combined value is what has to be parsed. A
  20068. // Trailer field split across lines therefore declares every name it lists;
  20069. // reading only the first line silently drops the trailers the later lines
  20070. // declare. The prohibited-trailer filter still applies to every line.
  20071. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  20072. Server svr;
  20073. size_t observed_trailer_count = 0;
  20074. std::string observed_hello;
  20075. std::string observed_world;
  20076. bool observed_content_length = true;
  20077. svr.Get("/", [&](const Request &req, Response &res) {
  20078. observed_trailer_count = req.trailers.size();
  20079. observed_hello = req.get_trailer_value("X-Hello");
  20080. observed_world = req.get_trailer_value("X-World");
  20081. observed_content_length = req.has_trailer("Content-Length");
  20082. res.set_content("ok", "text/plain");
  20083. });
  20084. auto port = svr.bind_to_any_port(HOST);
  20085. thread t = thread([&]() { svr.listen_after_bind(); });
  20086. auto se = detail::scope_exit([&] {
  20087. svr.stop();
  20088. t.join();
  20089. ASSERT_FALSE(svr.is_running());
  20090. });
  20091. svr.wait_until_ready();
  20092. const std::string req = "GET / HTTP/1.1\r\n"
  20093. "Host: localhost\r\n"
  20094. "Transfer-Encoding: chunked\r\n"
  20095. "Trailer: X-Hello\r\n"
  20096. "Trailer: X-World, Content-Length\r\n"
  20097. "\r\n"
  20098. "0\r\n"
  20099. "X-Hello: hello\r\n"
  20100. "X-World: world\r\n"
  20101. "Content-Length: 10\r\n"
  20102. "\r\n";
  20103. std::string res;
  20104. ASSERT_TRUE(send_request(1, req, &res, port));
  20105. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  20106. // Accepted: both field lines contribute to the declared set
  20107. EXPECT_EQ(2U, observed_trailer_count);
  20108. EXPECT_EQ(observed_hello, "hello");
  20109. EXPECT_EQ(observed_world, "world");
  20110. // Denied: a prohibited name stays prohibited on a later field line
  20111. EXPECT_FALSE(observed_content_length);
  20112. }
  20113. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  20114. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  20115. // unbounded run of fields that are never declared, because the counter would
  20116. // only advance for declared fields.
  20117. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  20118. Server svr;
  20119. bool handler_called = false;
  20120. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  20121. handler_called = true;
  20122. res.set_content("ok", "text/plain");
  20123. });
  20124. auto port = svr.bind_to_any_port(HOST);
  20125. thread t = thread([&]() { svr.listen_after_bind(); });
  20126. auto se = detail::scope_exit([&] {
  20127. svr.stop();
  20128. t.join();
  20129. ASSERT_FALSE(svr.is_running());
  20130. });
  20131. svr.wait_until_ready();
  20132. // Declare nothing, then send far more undeclared trailer fields than the
  20133. // header-count limit. Parsing must stop and reject the request rather than
  20134. // read every line.
  20135. std::string req = "GET / HTTP/1.1\r\n"
  20136. "Transfer-Encoding: chunked\r\n"
  20137. "\r\n"
  20138. "0\r\n";
  20139. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  20140. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  20141. }
  20142. req += "\r\n";
  20143. std::string res;
  20144. ASSERT_TRUE(send_request(1, req, &res, port));
  20145. // The request is rejected before the handler runs.
  20146. EXPECT_FALSE(handler_called);
  20147. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  20148. }
  20149. // The set of declared trailer names is capped so a peer cannot grow it without
  20150. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  20151. // declared past the cap is not honored, even if the field is actually sent.
  20152. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  20153. Server svr;
  20154. // One name inside the cap and one past it, so the test tracks the cap rather
  20155. // than a fixed count.
  20156. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  20157. const std::string within_cap_name = "X-T-0";
  20158. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  20159. bool observed_within_cap = false;
  20160. bool observed_past_cap = false;
  20161. svr.Get("/", [&](const Request &req, Response &res) {
  20162. observed_within_cap = req.has_trailer(within_cap_name);
  20163. observed_past_cap = req.has_trailer(past_cap_name);
  20164. res.set_content("ok", "text/plain");
  20165. });
  20166. auto port = svr.bind_to_any_port(HOST);
  20167. thread t = thread([&]() { svr.listen_after_bind(); });
  20168. auto se = detail::scope_exit([&] {
  20169. svr.stop();
  20170. t.join();
  20171. ASSERT_FALSE(svr.is_running());
  20172. });
  20173. svr.wait_until_ready();
  20174. // Declare more trailer names than the cap in a single Trailer field, then
  20175. // actually send the first (within the cap) and the last (past it).
  20176. std::string trailer_decl = "Trailer: ";
  20177. for (int i = 0; i < declared_count; i++) {
  20178. if (i != 0) { trailer_decl += ", "; }
  20179. trailer_decl += "X-T-" + std::to_string(i);
  20180. }
  20181. trailer_decl += "\r\n";
  20182. const std::string req = "GET / HTTP/1.1\r\n"
  20183. "Host: localhost\r\n"
  20184. "Transfer-Encoding: chunked\r\n" +
  20185. trailer_decl +
  20186. "\r\n"
  20187. "0\r\n" +
  20188. within_cap_name + ": a\r\n" + past_cap_name +
  20189. ": b\r\n"
  20190. "\r\n";
  20191. std::string res;
  20192. ASSERT_TRUE(send_request(1, req, &res, port));
  20193. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  20194. // A name within the cap is honored; one declared past the cap is dropped.
  20195. EXPECT_TRUE(observed_within_cap);
  20196. EXPECT_FALSE(observed_past_cap);
  20197. }
  20198. // A direct client that is not listed in trusted_proxies must not be able to
  20199. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20200. // the peer address on the actual TCP connection determines whether the
  20201. // header is honored.
  20202. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20203. Server svr;
  20204. // Deliberately does NOT include the loopback address the test client
  20205. // actually connects from, so the direct connection is not a trusted proxy.
  20206. svr.set_trusted_proxies({"203.0.113.66"});
  20207. std::string observed_remote_addr;
  20208. svr.Get("/ip", [&](const Request &req, Response &res) {
  20209. observed_remote_addr = req.remote_addr;
  20210. res.set_content("ok", "text/plain");
  20211. });
  20212. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20213. auto se = detail::scope_exit([&] {
  20214. svr.stop();
  20215. t.join();
  20216. ASSERT_FALSE(svr.is_running());
  20217. });
  20218. svr.wait_until_ready();
  20219. Client cli(HOST, PORT);
  20220. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20222. EXPECT_EQ(StatusCode::OK_200, res->status);
  20223. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20224. // ignored entirely and the real connection-level address retained.
  20225. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20226. observed_remote_addr == "127.0.0.1");
  20227. }
  20228. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20229. Server svr;
  20230. std::string observed_remote_addr;
  20231. std::string observed_xff;
  20232. svr.Get("/ip", [&](const Request &req, Response &res) {
  20233. observed_remote_addr = req.remote_addr;
  20234. observed_xff = req.get_header_value("X-Forwarded-For");
  20235. res.set_content("ok", "text/plain");
  20236. });
  20237. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20238. auto se = detail::scope_exit([&] {
  20239. svr.stop();
  20240. t.join();
  20241. ASSERT_FALSE(svr.is_running());
  20242. });
  20243. svr.wait_until_ready();
  20244. Client cli(HOST, PORT);
  20245. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20247. EXPECT_EQ(StatusCode::OK_200, res->status);
  20248. EXPECT_EQ(observed_xff, "203.0.113.66");
  20249. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20250. observed_remote_addr == "127.0.0.1");
  20251. }
  20252. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20253. Server svr;
  20254. svr.set_trusted_proxies({"203.0.113.66"});
  20255. std::string observed_remote_addr;
  20256. std::string observed_xff;
  20257. svr.Get("/ip", [&](const Request &req, Response &res) {
  20258. observed_remote_addr = req.remote_addr;
  20259. observed_xff = req.get_header_value("X-Forwarded-For");
  20260. res.set_content("ok", "text/plain");
  20261. });
  20262. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20263. auto se = detail::scope_exit([&] {
  20264. svr.stop();
  20265. t.join();
  20266. ASSERT_FALSE(svr.is_running());
  20267. });
  20268. svr.wait_until_ready();
  20269. Client cli(HOST, PORT);
  20270. auto res = cli.Get("/ip");
  20271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20272. EXPECT_EQ(StatusCode::OK_200, res->status);
  20273. EXPECT_EQ(observed_xff, "");
  20274. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20275. observed_remote_addr == "127.0.0.1");
  20276. }
  20277. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20278. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20279. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20280. Server svr;
  20281. svr.set_trusted_proxies({"127.0.0.1"});
  20282. svr.Get("/ip", [](const Request &req, Response &res) {
  20283. res.set_content(req.remote_addr, "text/plain");
  20284. });
  20285. auto port = svr.bind_to_any_port("::");
  20286. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20287. thread t = thread([&] { svr.listen_after_bind(); });
  20288. auto se = detail::scope_exit([&] {
  20289. svr.stop();
  20290. t.join();
  20291. ASSERT_FALSE(svr.is_running());
  20292. });
  20293. svr.wait_until_ready();
  20294. Client cli("127.0.0.1", port);
  20295. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20297. EXPECT_EQ("198.51.100.23", res->body);
  20298. }
  20299. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20300. Server svr;
  20301. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20302. svr.Get("/ip", [](const Request &req, Response &res) {
  20303. res.set_content(req.remote_addr, "text/plain");
  20304. });
  20305. auto port = svr.bind_to_any_port(HOST);
  20306. ASSERT_GT(port, 0);
  20307. thread t = thread([&] { svr.listen_after_bind(); });
  20308. auto se = detail::scope_exit([&] {
  20309. svr.stop();
  20310. t.join();
  20311. ASSERT_FALSE(svr.is_running());
  20312. });
  20313. svr.wait_until_ready();
  20314. Client cli(HOST, port);
  20315. auto res = cli.Get(
  20316. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20318. EXPECT_EQ("198.51.100.23", res->body);
  20319. }
  20320. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20321. Server svr;
  20322. // Include the loopback address the test client actually connects from, so
  20323. // the direct connection itself is recognized as the trusted proxy hop.
  20324. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20325. std::string observed_remote_addr;
  20326. std::string observed_xff;
  20327. svr.Get("/ip", [&](const Request &req, Response &res) {
  20328. observed_remote_addr = req.remote_addr;
  20329. observed_xff = req.get_header_value("X-Forwarded-For");
  20330. res.set_content("ok", "text/plain");
  20331. });
  20332. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20333. auto se = detail::scope_exit([&] {
  20334. svr.stop();
  20335. t.join();
  20336. ASSERT_FALSE(svr.is_running());
  20337. });
  20338. svr.wait_until_ready();
  20339. Client cli(HOST, PORT);
  20340. auto res = cli.Get(
  20341. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20343. EXPECT_EQ(StatusCode::OK_200, res->status);
  20344. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20345. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20346. }
  20347. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20348. Server svr;
  20349. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20350. std::string observed_remote_addr;
  20351. std::string observed_xff;
  20352. svr.Get("/ip", [&](const Request &req, Response &res) {
  20353. observed_remote_addr = req.remote_addr;
  20354. observed_xff = req.get_header_value("X-Forwarded-For");
  20355. res.set_content("ok", "text/plain");
  20356. });
  20357. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20358. auto se = detail::scope_exit([&] {
  20359. svr.stop();
  20360. t.join();
  20361. ASSERT_FALSE(svr.is_running());
  20362. });
  20363. svr.wait_until_ready();
  20364. Client cli(HOST, PORT);
  20365. auto res = cli.Get(
  20366. "/ip",
  20367. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20369. EXPECT_EQ(StatusCode::OK_200, res->status);
  20370. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20371. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20372. }
  20373. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20374. Server svr;
  20375. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20376. std::string observed_remote_addr;
  20377. std::string observed_xff;
  20378. svr.Get("/ip", [&](const Request &req, Response &res) {
  20379. observed_remote_addr = req.remote_addr;
  20380. observed_xff = req.get_header_value("X-Forwarded-For");
  20381. res.set_content("ok", "text/plain");
  20382. });
  20383. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20384. auto se = detail::scope_exit([&] {
  20385. svr.stop();
  20386. t.join();
  20387. ASSERT_FALSE(svr.is_running());
  20388. });
  20389. svr.wait_until_ready();
  20390. Client cli(HOST, PORT);
  20391. auto res = cli.Get(
  20392. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20394. EXPECT_EQ(StatusCode::OK_200, res->status);
  20395. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20396. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20397. // and must not be selected.
  20398. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20399. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20400. }
  20401. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20402. Server svr;
  20403. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20404. std::string observed_remote_addr;
  20405. svr.Get("/ip", [&](const Request &req, Response &res) {
  20406. observed_remote_addr = req.remote_addr;
  20407. res.set_content("ok", "text/plain");
  20408. });
  20409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20410. auto se = detail::scope_exit([&] {
  20411. svr.stop();
  20412. t.join();
  20413. ASSERT_FALSE(svr.is_running());
  20414. });
  20415. svr.wait_until_ready();
  20416. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20417. // a forged address and the trusted proxy's own address; the forged value must
  20418. // not win over the address the trusted proxy actually recorded.
  20419. Client cli(HOST, PORT);
  20420. auto res = cli.Get(
  20421. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20423. EXPECT_EQ(StatusCode::OK_200, res->status);
  20424. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20425. }
  20426. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20427. Server svr;
  20428. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20429. std::string observed_remote_addr;
  20430. std::string observed_xff;
  20431. svr.Get("/ip", [&](const Request &req, Response &res) {
  20432. observed_remote_addr = req.remote_addr;
  20433. observed_xff = req.get_header_value("X-Forwarded-For");
  20434. res.set_content("ok", "text/plain");
  20435. });
  20436. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20437. auto se = detail::scope_exit([&] {
  20438. svr.stop();
  20439. t.join();
  20440. ASSERT_FALSE(svr.is_running());
  20441. });
  20442. svr.wait_until_ready();
  20443. Client cli(HOST, PORT);
  20444. auto res = cli.Get(
  20445. "/ip",
  20446. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20448. EXPECT_EQ(StatusCode::OK_200, res->status);
  20449. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20450. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20451. }
  20452. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20453. Server svr;
  20454. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20455. std::string observed_remote_addr;
  20456. std::string observed_xff;
  20457. svr.Get("/ip", [&](const Request &req, Response &res) {
  20458. observed_remote_addr = req.remote_addr;
  20459. observed_xff = req.get_header_value("X-Forwarded-For");
  20460. res.set_content("ok", "text/plain");
  20461. });
  20462. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20463. auto se = detail::scope_exit([&] {
  20464. svr.stop();
  20465. t.join();
  20466. ASSERT_FALSE(svr.is_running());
  20467. });
  20468. svr.wait_until_ready();
  20469. std::string raw_req =
  20470. "GET /ip HTTP/1.1\r\n"
  20471. "Host: localhost\r\n"
  20472. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20473. "Connection: close\r\n"
  20474. "\r\n";
  20475. std::string out;
  20476. ASSERT_TRUE(send_request(5, raw_req, &out));
  20477. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20478. // Header parser trims surrounding whitespace of the header value
  20479. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20480. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20481. }
  20482. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20483. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20484. // their own X-Forwarded-For as a separate field line rather than extending the
  20485. // one the client sent, so every occurrence has to be taken into account.
  20486. // Reading only the first one hands back the address the client chose.
  20487. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20488. Server svr;
  20489. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20490. std::string observed_remote_addr;
  20491. size_t observed_xff_count = 0;
  20492. svr.Get("/ip", [&](const Request &req, Response &res) {
  20493. observed_remote_addr = req.remote_addr;
  20494. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20495. res.set_content("ok", "text/plain");
  20496. });
  20497. auto port = svr.bind_to_any_port(HOST);
  20498. thread t = thread([&]() { svr.listen_after_bind(); });
  20499. auto se = detail::scope_exit([&] {
  20500. svr.stop();
  20501. t.join();
  20502. ASSERT_FALSE(svr.is_running());
  20503. });
  20504. svr.wait_until_ready();
  20505. // The client supplies the first field line; the trusted proxy appends the
  20506. // address it observed as a second one.
  20507. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20508. "Host: localhost\r\n"
  20509. "X-Forwarded-For: 1.2.3.4\r\n"
  20510. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20511. "Connection: close\r\n"
  20512. "\r\n";
  20513. std::string out;
  20514. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20515. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20516. EXPECT_EQ(observed_xff_count, 2U);
  20517. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20518. // The same chain spread over one field line per hop derives the same client
  20519. // address, i.e. the split and the comma-joined representations agree.
  20520. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20521. "Host: localhost\r\n"
  20522. "X-Forwarded-For: 1.2.3.4\r\n"
  20523. "X-Forwarded-For: 198.51.100.23\r\n"
  20524. "X-Forwarded-For: 192.0.2.45\r\n"
  20525. "Connection: close\r\n"
  20526. "\r\n";
  20527. out.clear();
  20528. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20529. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20530. EXPECT_EQ(observed_xff_count, 3U);
  20531. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20532. }
  20533. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20534. // crash the server (it used to call front() on an empty vector inside
  20535. // get_client_ip). The connection-level remote address must be retained instead.
  20536. static void run_malformed_xff_test(const std::string &xff_value) {
  20537. Server svr;
  20538. svr.set_trusted_proxies({"192.0.2.45"});
  20539. std::string observed_remote_addr;
  20540. svr.Get("/ip", [&](const Request &req, Response &res) {
  20541. observed_remote_addr = req.remote_addr;
  20542. res.set_content("ok", "text/plain");
  20543. });
  20544. int port = 0;
  20545. thread t = thread([&]() {
  20546. port = svr.bind_to_any_port(HOST);
  20547. svr.listen_after_bind();
  20548. });
  20549. auto se = detail::scope_exit([&] {
  20550. svr.stop();
  20551. t.join();
  20552. ASSERT_FALSE(svr.is_running());
  20553. });
  20554. svr.wait_until_ready();
  20555. Client cli(HOST, port);
  20556. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20558. EXPECT_EQ(StatusCode::OK_200, res->status);
  20559. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20560. observed_remote_addr == "127.0.0.1");
  20561. }
  20562. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20563. run_malformed_xff_test("");
  20564. }
  20565. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20566. run_malformed_xff_test(",");
  20567. }
  20568. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20569. run_malformed_xff_test(", , ,");
  20570. }
  20571. // The same rule applies to Accept: a request whose acceptable types are spread
  20572. // over several field lines must be negotiated against all of them.
  20573. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20574. // case-insensitive connection options. Comparing the whole field value against
  20575. // one option misses a client that sends several of them, and misses every
  20576. // casing but the one written in the comparison.
  20577. //
  20578. // Sends req, reads the response, then reuses the same socket for a second
  20579. // request to find out whether the server kept the connection.
  20580. static void probe_connection_reuse(int port, const std::string &req,
  20581. bool *announced_close, bool *reusable) {
  20582. auto error = Error::Success;
  20583. auto sock = detail::create_client_socket(
  20584. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20585. /*connection_timeout_sec=*/5, 0,
  20586. /*read_timeout_sec=*/1, 0,
  20587. /*write_timeout_sec=*/5, 0, std::string(), error);
  20588. ASSERT_NE(sock, INVALID_SOCKET);
  20589. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20590. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20591. "Host: localhost\r\n"
  20592. "Connection: close\r\n"
  20593. "\r\n";
  20594. std::string first_response;
  20595. std::string second_response;
  20596. detail::process_client_socket(
  20597. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20598. [&](Stream &strm) {
  20599. if (strm.write(req.data(), req.size()) !=
  20600. static_cast<ssize_t>(req.size())) {
  20601. return false;
  20602. }
  20603. char buf[512];
  20604. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20605. // Headers plus the two-byte body of the handler below
  20606. while (reader.getline()) {
  20607. first_response += reader.ptr();
  20608. if (first_response.find("ok") != std::string::npos) { break; }
  20609. }
  20610. if (strm.write(second.data(), second.size()) !=
  20611. static_cast<ssize_t>(second.size())) {
  20612. return true;
  20613. }
  20614. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20615. while (reader2.getline()) {
  20616. second_response += reader2.ptr();
  20617. if (second_response.find("ok") != std::string::npos) { break; }
  20618. }
  20619. return true;
  20620. });
  20621. *announced_close =
  20622. first_response.find("Connection: close") != std::string::npos;
  20623. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20624. }
  20625. class ConnectionTokenTest : public ::testing::Test {
  20626. protected:
  20627. void SetUp() override {
  20628. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20629. res.set_content("ok", "text/plain");
  20630. });
  20631. port_ = svr_.bind_to_any_port(HOST);
  20632. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20633. svr_.wait_until_ready();
  20634. }
  20635. void TearDown() override {
  20636. svr_.stop();
  20637. if (thread_.joinable()) { thread_.join(); }
  20638. }
  20639. Server svr_;
  20640. int port_ = 0;
  20641. thread thread_;
  20642. };
  20643. // "close" alongside another option still closes the connection, and the
  20644. // response says so rather than leaving the peer to discover it.
  20645. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20646. bool announced_close = false;
  20647. bool reusable = true;
  20648. probe_connection_reuse(port_,
  20649. "GET /keepalive HTTP/1.1\r\n"
  20650. "Host: localhost\r\n"
  20651. "Connection: keep-alive, close\r\n"
  20652. "\r\n",
  20653. &announced_close, &reusable);
  20654. EXPECT_TRUE(announced_close);
  20655. EXPECT_FALSE(reusable);
  20656. }
  20657. // "close" split over two field lines is the same list, so it is honored too.
  20658. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20659. bool announced_close = false;
  20660. bool reusable = true;
  20661. probe_connection_reuse(port_,
  20662. "GET /keepalive HTTP/1.1\r\n"
  20663. "Host: localhost\r\n"
  20664. "Connection: keep-alive\r\n"
  20665. "Connection: close\r\n"
  20666. "\r\n",
  20667. &announced_close, &reusable);
  20668. EXPECT_TRUE(announced_close);
  20669. EXPECT_FALSE(reusable);
  20670. }
  20671. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20672. // keep-alive in the spelling everyone actually sends keeps its connection.
  20673. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20674. bool announced_close = false;
  20675. bool reusable = false;
  20676. probe_connection_reuse(port_,
  20677. "GET /keepalive HTTP/1.0\r\n"
  20678. "Host: localhost\r\n"
  20679. "Connection: keep-alive\r\n"
  20680. "\r\n",
  20681. &announced_close, &reusable);
  20682. EXPECT_FALSE(announced_close);
  20683. EXPECT_TRUE(reusable);
  20684. }
  20685. // A token the value merely contains is not the token itself.
  20686. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20687. bool announced_close = false;
  20688. bool reusable = false;
  20689. probe_connection_reuse(port_,
  20690. "GET /keepalive HTTP/1.1\r\n"
  20691. "Host: localhost\r\n"
  20692. "Connection: notclose\r\n"
  20693. "\r\n",
  20694. &announced_close, &reusable);
  20695. EXPECT_FALSE(announced_close);
  20696. EXPECT_TRUE(reusable);
  20697. }
  20698. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20699. Server svr;
  20700. std::vector<std::string> observed_types;
  20701. svr.Get("/", [&](const Request &req, Response &res) {
  20702. observed_types = req.accept_content_types;
  20703. res.set_content("ok", "text/plain");
  20704. });
  20705. auto port = svr.bind_to_any_port(HOST);
  20706. thread t = thread([&]() { svr.listen_after_bind(); });
  20707. auto se = detail::scope_exit([&] {
  20708. svr.stop();
  20709. t.join();
  20710. ASSERT_FALSE(svr.is_running());
  20711. });
  20712. svr.wait_until_ready();
  20713. Client cli(HOST, port);
  20714. Headers headers;
  20715. headers.emplace("Accept", "text/plain;q=0.5");
  20716. headers.emplace("Accept", "application/json");
  20717. auto res = cli.Get("/", headers);
  20718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20719. EXPECT_EQ(StatusCode::OK_200, res->status);
  20720. // Sorted by q-value, so the second field line's type comes first
  20721. ASSERT_EQ(2U, observed_types.size());
  20722. EXPECT_EQ("application/json", observed_types[0]);
  20723. EXPECT_EQ("text/plain", observed_types[1]);
  20724. }
  20725. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20726. // empty field line must not contribute a bare comma to the combined value.
  20727. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20728. Server svr;
  20729. std::vector<std::string> observed_types;
  20730. svr.Get("/", [&](const Request &req, Response &res) {
  20731. observed_types = req.accept_content_types;
  20732. res.set_content("ok", "text/plain");
  20733. });
  20734. auto port = svr.bind_to_any_port(HOST);
  20735. thread t = thread([&]() { svr.listen_after_bind(); });
  20736. auto se = detail::scope_exit([&] {
  20737. svr.stop();
  20738. t.join();
  20739. ASSERT_FALSE(svr.is_running());
  20740. });
  20741. svr.wait_until_ready();
  20742. // Empty first field line, then a real one
  20743. std::string raw_req = "GET / HTTP/1.1\r\n"
  20744. "Host: localhost\r\n"
  20745. "Accept:\r\n"
  20746. "Accept: application/json\r\n"
  20747. "Connection: close\r\n"
  20748. "\r\n";
  20749. std::string out;
  20750. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20751. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20752. ASSERT_EQ(1U, observed_types.size());
  20753. EXPECT_EQ("application/json", observed_types[0]);
  20754. }
  20755. // The skip in get_combined_header_value() is what keeps an empty field line
  20756. // from contributing a bare comma. Only a trailing empty field line exercises
  20757. // it: a leading one is already covered by the "combined is still empty" check,
  20758. // and parse_accept_header() now ignores the empty element either way, so the
  20759. // request-level test above can no longer tell the two apart.
  20760. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20761. Headers headers;
  20762. headers.emplace("Accept", "text/html");
  20763. headers.emplace("Accept", "");
  20764. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20765. headers.clear();
  20766. headers.emplace("Accept", "");
  20767. headers.emplace("Accept", "application/json");
  20768. EXPECT_EQ("application/json",
  20769. detail::get_combined_header_value(headers, "Accept"));
  20770. }
  20771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20772. // An encoding offered on a later Accept-Encoding field line is still offered.
  20773. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20774. Server svr;
  20775. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20776. res.set_content(std::string(1024, 'x'), "text/plain");
  20777. });
  20778. auto port = svr.bind_to_any_port(HOST);
  20779. thread t = thread([&]() { svr.listen_after_bind(); });
  20780. auto se = detail::scope_exit([&] {
  20781. svr.stop();
  20782. t.join();
  20783. ASSERT_FALSE(svr.is_running());
  20784. });
  20785. svr.wait_until_ready();
  20786. Client cli(HOST, port);
  20787. cli.set_decompress(false);
  20788. Headers headers;
  20789. headers.emplace("Accept-Encoding", "identity");
  20790. headers.emplace("Accept-Encoding", "gzip");
  20791. auto res = cli.Get("/", headers);
  20792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20793. EXPECT_EQ(StatusCode::OK_200, res->status);
  20794. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20795. }
  20796. #endif
  20797. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20798. // Transfer-Encoding is not its body.
  20799. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20800. Server svr;
  20801. svr.set_payload_max_length(8);
  20802. svr.Post("/test", [](const Request &, Response &res) {
  20803. res.set_content("ok", "text/plain");
  20804. });
  20805. auto port = svr.bind_to_any_port(HOST);
  20806. ASSERT_GT(port, 0);
  20807. thread t = thread([&] { svr.listen_after_bind(); });
  20808. auto se = detail::scope_exit([&] {
  20809. svr.stop();
  20810. t.join();
  20811. ASSERT_FALSE(svr.is_running());
  20812. });
  20813. svr.wait_until_ready();
  20814. std::string resp;
  20815. ASSERT_TRUE(send_request(1,
  20816. "POST /test HTTP/1.1\r\n"
  20817. "Host: localhost\r\n"
  20818. "Connection: close\r\n"
  20819. "\r\n" +
  20820. std::string(16, 'X'),
  20821. &resp, port));
  20822. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20823. }
  20824. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20825. Server svr;
  20826. svr.Post("/post", [&](const Request &req, Response &res) {
  20827. res.set_content(req.body, "text/plain");
  20828. });
  20829. svr.Put("/put", [&](const Request &req, Response &res) {
  20830. res.set_content(req.body, "text/plain");
  20831. });
  20832. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20833. res.set_content(req.body, "text/plain");
  20834. });
  20835. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20836. res.set_content(req.body, "text/plain");
  20837. });
  20838. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20839. auto se = detail::scope_exit([&] {
  20840. svr.stop();
  20841. t.join();
  20842. ASSERT_FALSE(svr.is_running());
  20843. });
  20844. svr.wait_until_ready();
  20845. std::string resp;
  20846. // POST without Content-Length
  20847. ASSERT_TRUE(send_request(5,
  20848. "POST /post HTTP/1.1\r\n"
  20849. "Host: localhost\r\n"
  20850. "Connection: close\r\n"
  20851. "\r\n",
  20852. &resp));
  20853. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20854. // PUT without Content-Length
  20855. resp.clear();
  20856. ASSERT_TRUE(send_request(5,
  20857. "PUT /put HTTP/1.1\r\n"
  20858. "Host: localhost\r\n"
  20859. "Connection: close\r\n"
  20860. "\r\n",
  20861. &resp));
  20862. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20863. // PATCH without Content-Length
  20864. resp.clear();
  20865. ASSERT_TRUE(send_request(5,
  20866. "PATCH /patch HTTP/1.1\r\n"
  20867. "Host: localhost\r\n"
  20868. "Connection: close\r\n"
  20869. "\r\n",
  20870. &resp));
  20871. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20872. // DELETE without Content-Length
  20873. resp.clear();
  20874. ASSERT_TRUE(send_request(5,
  20875. "DELETE /delete HTTP/1.1\r\n"
  20876. "Host: localhost\r\n"
  20877. "Connection: close\r\n"
  20878. "\r\n",
  20879. &resp));
  20880. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20881. }
  20882. //==============================================================================
  20883. // open_stream() Tests
  20884. //==============================================================================
  20885. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20886. std::string result;
  20887. char buf[8192];
  20888. ssize_t n;
  20889. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20890. result.append(buf, static_cast<size_t>(n));
  20891. }
  20892. return result;
  20893. }
  20894. // Mock stream for unit tests
  20895. class MockStream : public Stream {
  20896. public:
  20897. std::string data;
  20898. size_t pos = 0;
  20899. ssize_t error_after = -1; // -1 = no error
  20900. explicit MockStream(const std::string &d, ssize_t err = -1)
  20901. : data(d), error_after(err) {}
  20902. bool is_readable() const override { return true; }
  20903. bool wait_readable() const override { return true; }
  20904. bool wait_writable() const override { return true; }
  20905. ssize_t read(char *ptr, size_t size) override {
  20906. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20907. if (pos >= data.size()) return 0;
  20908. size_t limit =
  20909. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20910. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20911. std::memcpy(ptr, data.data() + pos, to_read);
  20912. pos += to_read;
  20913. return static_cast<ssize_t>(to_read);
  20914. }
  20915. ssize_t write(const char *, size_t) override { return -1; }
  20916. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20917. ip = "127.0.0.1";
  20918. port = 0;
  20919. }
  20920. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20921. ip = "127.0.0.1";
  20922. port = 0;
  20923. }
  20924. socket_t socket() const override { return INVALID_SOCKET; }
  20925. time_t duration() const override { return 0; }
  20926. };
  20927. TEST(StreamHandleTest, Basic) {
  20928. ClientImpl::StreamHandle handle;
  20929. EXPECT_FALSE(handle.is_valid());
  20930. handle.response = detail::make_unique<Response>();
  20931. handle.error = Error::Connection;
  20932. EXPECT_FALSE(handle.is_valid());
  20933. handle.error = Error::Success;
  20934. EXPECT_TRUE(handle.is_valid());
  20935. }
  20936. TEST(BodyReaderTest, Basic) {
  20937. MockStream stream("Hello, World!");
  20938. detail::BodyReader reader;
  20939. reader.stream = &stream;
  20940. reader.content_length = 13;
  20941. char buf[32];
  20942. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20943. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20944. EXPECT_TRUE(reader.eof);
  20945. }
  20946. TEST(BodyReaderTest, NoStream) {
  20947. detail::BodyReader reader;
  20948. char buf[32];
  20949. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20950. EXPECT_EQ(Error::Connection, reader.last_error);
  20951. }
  20952. TEST(BodyReaderTest, Error) {
  20953. MockStream stream("Hello, World!", 5);
  20954. detail::BodyReader reader;
  20955. reader.stream = &stream;
  20956. reader.content_length = 13;
  20957. char buf[32];
  20958. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20959. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20960. EXPECT_EQ(Error::Read, reader.last_error);
  20961. }
  20962. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20963. // Mock-based StreamHandle tests relying on private internals are removed.
  20964. class OpenStreamTest : public ::testing::Test {
  20965. protected:
  20966. void SetUp() override {
  20967. svr_.Get("/hello", [](const Request &, Response &res) {
  20968. res.set_content("Hello World!", "text/plain");
  20969. });
  20970. svr_.Get("/large", [](const Request &, Response &res) {
  20971. res.set_content(std::string(10000, 'X'), "text/plain");
  20972. });
  20973. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20974. res.set_content("Hello World!", "image/jpeg");
  20975. res.set_header("Content-Encoding", "UTF-8");
  20976. });
  20977. svr_.Get("/chunked", [](const Request &, Response &res) {
  20978. res.set_chunked_content_provider("text/plain",
  20979. [](size_t offset, DataSink &sink) {
  20980. if (offset < 15) {
  20981. sink.write("chunk", 5);
  20982. return true;
  20983. }
  20984. sink.done();
  20985. return true;
  20986. });
  20987. });
  20988. svr_.Get("/compressible", [](const Request &, Response &res) {
  20989. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20990. DataSink &sink) {
  20991. if (offset < 100 * 1024) {
  20992. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20993. sink.write(chunk.data(), chunk.size());
  20994. return true;
  20995. }
  20996. sink.done();
  20997. return true;
  20998. });
  20999. });
  21000. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  21001. [](const Request & /*req*/, Response &res) {
  21002. auto i = new int(0);
  21003. res.set_header("Trailer", "Content-Length, X-Allowed");
  21004. res.set_chunked_content_provider(
  21005. "text/plain",
  21006. [i](size_t /*offset*/, DataSink &sink) {
  21007. switch (*i) {
  21008. case 0: sink.os << "123"; break;
  21009. case 1: sink.os << "456"; break;
  21010. case 2: sink.os << "789"; break;
  21011. case 3: {
  21012. sink.done_with_trailer(
  21013. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  21014. } break;
  21015. }
  21016. (*i)++;
  21017. return true;
  21018. },
  21019. [i](bool success) {
  21020. EXPECT_TRUE(success);
  21021. delete i;
  21022. });
  21023. });
  21024. // Echo headers endpoint for header-related tests
  21025. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  21026. std::string body;
  21027. for (const auto &h : req.headers) {
  21028. body.append(h.first);
  21029. body.push_back(':');
  21030. body.append(h.second);
  21031. body.push_back('\n');
  21032. }
  21033. res.set_content(body, "text/plain");
  21034. });
  21035. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  21036. std::string body;
  21037. for (const auto &h : req.headers) {
  21038. body.append(h.first);
  21039. body.push_back(':');
  21040. body.append(h.second);
  21041. body.push_back('\n');
  21042. }
  21043. res.set_content(body, "text/plain");
  21044. });
  21045. port_ = svr_.bind_to_any_port("127.0.0.1");
  21046. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21047. svr_.wait_until_ready();
  21048. }
  21049. void TearDown() override {
  21050. svr_.stop();
  21051. if (thread_.joinable()) thread_.join();
  21052. }
  21053. Server svr_;
  21054. std::thread thread_;
  21055. int port_ = 0;
  21056. };
  21057. TEST_F(OpenStreamTest, Basic) {
  21058. Client cli("127.0.0.1", port_);
  21059. auto handle = cli.open_stream("GET", "/hello");
  21060. EXPECT_TRUE(handle.is_valid());
  21061. EXPECT_EQ("Hello World!", read_all(handle));
  21062. }
  21063. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  21064. Client cli("127.0.0.1", port_);
  21065. auto handle = cli.open_stream("GET", "/unknown-encoding");
  21066. ASSERT_TRUE(handle.is_valid());
  21067. EXPECT_EQ("Hello World!", read_all(handle));
  21068. }
  21069. TEST_F(OpenStreamTest, SmallBuffer) {
  21070. Client cli("127.0.0.1", port_);
  21071. auto handle = cli.open_stream("GET", "/hello");
  21072. std::string result;
  21073. char buf[4];
  21074. ssize_t n;
  21075. while ((n = handle.read(buf, sizeof(buf))) > 0)
  21076. result.append(buf, static_cast<size_t>(n));
  21077. EXPECT_EQ("Hello World!", result);
  21078. }
  21079. TEST_F(OpenStreamTest, DefaultHeaders) {
  21080. Client cli("127.0.0.1", port_);
  21081. // open_stream GET should include Host, User-Agent and Accept-Encoding
  21082. {
  21083. auto handle = cli.open_stream("GET", "/echo-headers");
  21084. ASSERT_TRUE(handle.is_valid());
  21085. auto body = read_all(handle);
  21086. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  21087. std::string::npos);
  21088. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  21089. std::string::npos);
  21090. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  21091. }
  21092. // open_stream POST with body and no explicit content_type should NOT add
  21093. // text/plain Content-Type (behavior differs from non-streaming path), but
  21094. // should include Content-Length
  21095. {
  21096. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  21097. ASSERT_TRUE(handle.is_valid());
  21098. auto body = read_all(handle);
  21099. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  21100. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  21101. }
  21102. // open_stream POST with explicit Content-Type should preserve it
  21103. {
  21104. auto handle = cli.open_stream("POST", "/echo-headers", {},
  21105. {{"Content-Type", "application/custom"}},
  21106. "{}", "application/custom");
  21107. ASSERT_TRUE(handle.is_valid());
  21108. auto body = read_all(handle);
  21109. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  21110. }
  21111. // User-specified User-Agent must not be overwritten for stream API
  21112. {
  21113. auto handle = cli.open_stream("GET", "/echo-headers", {},
  21114. {{"User-Agent", "MyAgent/1.2"}});
  21115. ASSERT_TRUE(handle.is_valid());
  21116. auto body = read_all(handle);
  21117. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  21118. }
  21119. }
  21120. TEST_F(OpenStreamTest, Large) {
  21121. Client cli("127.0.0.1", port_);
  21122. auto handle = cli.open_stream("GET", "/large");
  21123. EXPECT_EQ(10000u, read_all(handle).size());
  21124. }
  21125. TEST_F(OpenStreamTest, ConnectionError) {
  21126. Client cli("127.0.0.1", 9999);
  21127. auto handle = cli.open_stream("GET", "/hello");
  21128. EXPECT_FALSE(handle.is_valid());
  21129. }
  21130. TEST_F(OpenStreamTest, Chunked) {
  21131. Client cli("127.0.0.1", port_);
  21132. auto handle = cli.open_stream("GET", "/chunked");
  21133. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21134. "Transfer-Encoding") == "chunked");
  21135. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  21136. }
  21137. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  21138. Client cli("127.0.0.1", port_);
  21139. auto handle =
  21140. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  21141. ASSERT_TRUE(handle.is_valid());
  21142. // Consume body to allow trailers to be received/parsed
  21143. auto body = read_all(handle);
  21144. // Explicitly parse trailers (ensure trailers are available for assertion)
  21145. handle.parse_trailers_if_needed();
  21146. EXPECT_EQ(std::string("123456789"), body);
  21147. // The response should include a Trailer header declaring both names
  21148. ASSERT_TRUE(handle.response);
  21149. EXPECT_TRUE(handle.response->has_header("Trailer"));
  21150. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  21151. handle.response->get_header_value("Trailer"));
  21152. // Prohibited trailer must not be present
  21153. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  21154. // Allowed trailer should be present
  21155. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  21156. EXPECT_EQ(std::string("yes"),
  21157. handle.response->get_trailer_value("X-Allowed"));
  21158. // Verify trailers are NOT present as regular headers
  21159. EXPECT_EQ(std::string(""),
  21160. handle.response->get_header_value("Content-Length"));
  21161. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  21162. }
  21163. // Accepts one connection on an OS-assigned port, which it hands over through
  21164. // port_promise, reads the request head and sends back response. after_send,
  21165. // if given, runs on the connection before it is closed.
  21166. static std::thread
  21167. serve_single_response(std::promise<int> &port_promise,
  21168. const std::string &response,
  21169. std::function<void(socket_t)> after_send = nullptr) {
  21170. return std::thread([&port_promise, response, after_send] {
  21171. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21172. default_socket_options(srv);
  21173. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21175. sockaddr_in addr{};
  21176. addr.sin_family = AF_INET;
  21177. addr.sin_port = htons(0); // Let OS assign a free port
  21178. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21179. int opt = 1;
  21180. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  21181. #ifdef _WIN32
  21182. reinterpret_cast<const char *>(&opt),
  21183. #else
  21184. &opt,
  21185. #endif
  21186. sizeof(opt));
  21187. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21188. ::listen(srv, 1) != 0) {
  21189. port_promise.set_value(-1);
  21190. detail::close_socket(srv);
  21191. return;
  21192. }
  21193. socklen_t addr_len = sizeof(addr);
  21194. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21195. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21196. sockaddr_in cli_addr{};
  21197. socklen_t cli_len = sizeof(cli_addr);
  21198. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21199. if (cli != INVALID_SOCKET) {
  21200. // Read the complete HTTP request (until the blank line that terminates
  21201. // headers) before sending the response. If the server closes the socket
  21202. // while the client's request data is still unread in the kernel receive
  21203. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21204. // connection on both sides: it discards the client's receive buffer
  21205. // (which already holds our response) and causes any in-progress write on
  21206. // the client to fail with ECONNRESET. Reading all request data first
  21207. // ensures close() emits a graceful FIN.
  21208. {
  21209. char rbuf[256];
  21210. std::string req;
  21211. while (req.find("\r\n\r\n") == std::string::npos) {
  21212. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21213. if (n <= 0) { break; }
  21214. req.append(rbuf, static_cast<size_t>(n));
  21215. }
  21216. }
  21217. ::send(cli,
  21218. #ifdef _WIN32
  21219. static_cast<const char *>(response.c_str()),
  21220. static_cast<int>(response.size()),
  21221. #else
  21222. response.c_str(), response.size(),
  21223. #endif
  21224. 0);
  21225. if (after_send) { after_send(cli); }
  21226. detail::close_socket(cli);
  21227. }
  21228. detail::close_socket(srv);
  21229. });
  21230. }
  21231. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21232. #ifndef _WIN32
  21233. signal(SIGPIPE, SIG_IGN);
  21234. #endif
  21235. std::promise<int> port_promise;
  21236. auto port_future = port_promise.get_future();
  21237. auto server_thread =
  21238. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21239. "Content-Type: text/plain\r\n"
  21240. "Content-Length: not-a-number\r\n"
  21241. "Connection: close\r\n"
  21242. "\r\n"
  21243. "hello");
  21244. auto port = port_future.get();
  21245. ASSERT_GT(port, 0);
  21246. Client cli("127.0.0.1", port);
  21247. auto handle = cli.open_stream("GET", "/");
  21248. EXPECT_FALSE(handle.is_valid());
  21249. server_thread.join();
  21250. }
  21251. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21252. #ifndef _WIN32
  21253. signal(SIGPIPE, SIG_IGN);
  21254. #endif
  21255. std::promise<int> port_promise;
  21256. auto port_future = port_promise.get_future();
  21257. auto server_thread = serve_single_response(
  21258. port_promise, "HTTP/1.1 200 OK\r\n"
  21259. "Content-Type: text/plain\r\n"
  21260. "Content-Length: 99999999999999999999999999\r\n"
  21261. "Connection: close\r\n"
  21262. "\r\n"
  21263. "hello");
  21264. auto port = port_future.get();
  21265. ASSERT_GT(port, 0);
  21266. // Historically std::stoull would throw std::out_of_range here and crash
  21267. // the process, then parsing silently clamped to a bogus framing length and
  21268. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21269. // so the stream fails to open, matching the not-a-number case above. The
  21270. // process still must NOT terminate.
  21271. Client cli("127.0.0.1", port);
  21272. auto handle = cli.open_stream("GET", "/");
  21273. EXPECT_FALSE(handle.is_valid());
  21274. server_thread.join();
  21275. }
  21276. #ifndef _WIN32
  21277. // As above for the body of a streamed request: a send() cut short by the write
  21278. // timeout must not leave the rest of the body unsent.
  21279. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21280. signal(SIGPIPE, SIG_IGN);
  21281. Server svr;
  21282. svr.set_socket_options([](socket_t sock) {
  21283. int size = 8192;
  21284. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21285. reinterpret_cast<const char *>(&size), sizeof(size));
  21286. });
  21287. svr.Post("/size", [](const Request &, Response &res,
  21288. const ContentReader &content_reader) {
  21289. // Outlast the client's write timeout before reading the body.
  21290. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21291. size_t received = 0;
  21292. content_reader([&](const char *, size_t len) {
  21293. received += len;
  21294. return true;
  21295. });
  21296. res.set_content(std::to_string(received), "text/plain");
  21297. });
  21298. auto port = svr.bind_to_any_port(HOST);
  21299. std::thread t([&]() { svr.listen_after_bind(); });
  21300. auto se = detail::scope_exit([&] {
  21301. svr.stop();
  21302. t.join();
  21303. });
  21304. svr.wait_until_ready();
  21305. Client cli(HOST, port);
  21306. cli.set_write_timeout(0, 500000);
  21307. cli.set_socket_options([](socket_t sock) {
  21308. int size = 8192;
  21309. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21310. reinterpret_cast<const char *>(&size), sizeof(size));
  21311. });
  21312. const std::string body(4 * 1024 * 1024, 'A');
  21313. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21314. "application/octet-stream");
  21315. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21316. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21317. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21318. }
  21319. #endif
  21320. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21321. std::promise<void> slow_started;
  21322. auto slow_started_future = slow_started.get_future();
  21323. Server svr;
  21324. svr.Get("/slow", [&](const Request &, Response &res) {
  21325. slow_started.set_value();
  21326. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21327. res.set_content("slow", "text/plain");
  21328. });
  21329. svr.Get("/fast", [](const Request &, Response &res) {
  21330. res.set_content("fast", "text/plain");
  21331. });
  21332. auto port = svr.bind_to_any_port(HOST);
  21333. std::thread t([&]() { svr.listen_after_bind(); });
  21334. auto se = detail::scope_exit([&] {
  21335. svr.stop();
  21336. t.join();
  21337. });
  21338. svr.wait_until_ready();
  21339. Client cli(HOST, port);
  21340. std::string slow_body;
  21341. std::thread slow_thread([&] {
  21342. auto res = cli.Get("/slow");
  21343. if (res) { slow_body = res->body; }
  21344. });
  21345. slow_started_future.wait();
  21346. auto result = stream::Get(cli, "/fast");
  21347. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21348. slow_thread.join();
  21349. EXPECT_EQ("slow", slow_body);
  21350. EXPECT_EQ("fast", fast_body);
  21351. }
  21352. // Serves `response` to the single request `fn` makes with a fresh client.
  21353. template <typename Fn>
  21354. static void with_single_response(const std::string &response, Fn fn) {
  21355. #ifndef _WIN32
  21356. signal(SIGPIPE, SIG_IGN);
  21357. #endif
  21358. std::promise<int> port_promise;
  21359. auto port_future = port_promise.get_future();
  21360. auto server_thread = serve_single_response(port_promise, response);
  21361. auto se = detail::scope_exit([&] { server_thread.join(); });
  21362. auto port = port_future.get();
  21363. ASSERT_GT(port, 0);
  21364. Client cli("127.0.0.1", port);
  21365. fn(cli);
  21366. }
  21367. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21368. // too, also in a build without the decoder for the advertised coding.
  21369. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21370. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21371. const auto response = "HTTP/1.1 200 OK\r\n"
  21372. "Content-Encoding: gzip\r\n"
  21373. "Content-Length: " +
  21374. std::to_string(gzipped.size()) +
  21375. "\r\n"
  21376. "Connection: close\r\n\r\n" +
  21377. gzipped;
  21378. with_single_response(response, [&](Client &cli) {
  21379. cli.set_decompress(false);
  21380. auto handle = cli.open_stream("GET", "/");
  21381. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21382. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21383. EXPECT_EQ(gzipped, read_all(handle));
  21384. EXPECT_FALSE(handle.has_read_error());
  21385. });
  21386. with_single_response(response, [&](Client &cli) {
  21387. cli.set_decompress(false);
  21388. auto res = stream::Get(cli, "/", 7);
  21389. ASSERT_TRUE(res) << to_string(res.error());
  21390. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21391. EXPECT_EQ(gzipped, res.read_all());
  21392. EXPECT_FALSE(res.has_read_error());
  21393. });
  21394. }
  21395. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21396. // Neither Content-Length nor chunked: the body ends at the close
  21397. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21398. "Connection: close\r\n"
  21399. "\r\n"
  21400. "hello";
  21401. with_single_response(close_delimited, [](Client &cli) {
  21402. auto handle = cli.open_stream("GET", "/");
  21403. ASSERT_TRUE(handle.is_valid());
  21404. EXPECT_EQ("hello", read_all(handle));
  21405. EXPECT_FALSE(handle.has_read_error());
  21406. });
  21407. // A close before the end of the Content-Length is still an error
  21408. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21409. "Content-Length: 10\r\n"
  21410. "\r\n"
  21411. "hello";
  21412. with_single_response(short_content_length, [](Client &cli) {
  21413. auto handle = cli.open_stream("GET", "/");
  21414. ASSERT_TRUE(handle.is_valid());
  21415. read_all(handle);
  21416. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21417. });
  21418. // So is a close before the last chunk
  21419. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21420. "Transfer-Encoding: chunked\r\n"
  21421. "\r\n"
  21422. "5\r\nhello\r\n";
  21423. with_single_response(short_chunked, [](Client &cli) {
  21424. auto handle = cli.open_stream("GET", "/");
  21425. ASSERT_TRUE(handle.is_valid());
  21426. read_all(handle);
  21427. EXPECT_TRUE(handle.has_read_error());
  21428. });
  21429. }
  21430. #ifdef CPPHTTPLIB_SSL_ENABLED
  21431. // Serves `response` to one request, then closes with or without a close_notify
  21432. template <typename Fn>
  21433. static void with_single_tls_response(const std::string &response,
  21434. bool close_notify, Fn fn) {
  21435. #ifndef _WIN32
  21436. signal(SIGPIPE, SIG_IGN);
  21437. #endif
  21438. std::promise<int> port_promise;
  21439. auto port_future = port_promise.get_future();
  21440. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21441. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21442. default_socket_options(srv);
  21443. sockaddr_in addr{};
  21444. addr.sin_family = AF_INET;
  21445. addr.sin_port = htons(0);
  21446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21447. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21448. ::listen(srv, 1) != 0) {
  21449. port_promise.set_value(-1);
  21450. detail::close_socket(srv);
  21451. return;
  21452. }
  21453. socklen_t addr_len = sizeof(addr);
  21454. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21455. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21456. auto cli = ::accept(srv, nullptr, nullptr);
  21457. if (cli != INVALID_SOCKET) {
  21458. auto ctx = tls::create_server_context();
  21459. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21460. nullptr);
  21461. auto session = tls::create_session(ctx, cli);
  21462. tls::TlsError err;
  21463. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21464. // The request head first, so that closing the socket sends a FIN
  21465. // rather than an RST for the unread bytes.
  21466. std::string req;
  21467. char buf[256];
  21468. while (req.find("\r\n\r\n") == std::string::npos) {
  21469. auto n = tls::read(session, buf, sizeof(buf), err);
  21470. if (n <= 0) { break; }
  21471. req.append(buf, static_cast<size_t>(n));
  21472. }
  21473. size_t sent = 0;
  21474. while (sent < response.size()) {
  21475. auto n = tls::write(session, response.data() + sent,
  21476. response.size() - sent, err);
  21477. if (n <= 0) { break; }
  21478. sent += static_cast<size_t>(n);
  21479. }
  21480. if (close_notify) { tls::shutdown(session, true); }
  21481. }
  21482. tls::free_session(session);
  21483. detail::close_socket(cli);
  21484. tls::free_context(ctx);
  21485. }
  21486. detail::close_socket(srv);
  21487. });
  21488. auto se = detail::scope_exit([&] { server_thread.join(); });
  21489. auto port = port_future.get();
  21490. ASSERT_GT(port, 0);
  21491. SSLClient cli("127.0.0.1", port);
  21492. cli.enable_server_certificate_verification(false);
  21493. fn(cli);
  21494. }
  21495. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21496. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21497. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21498. "Connection: close\r\n"
  21499. "\r\n"
  21500. "hello";
  21501. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21502. auto res = cli.Get("/");
  21503. ASSERT_TRUE(res) << to_string(res.error());
  21504. EXPECT_EQ("hello", res->body);
  21505. });
  21506. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21507. auto res = cli.Get("/");
  21508. ASSERT_FALSE(res);
  21509. EXPECT_EQ(Error::Read, res.error());
  21510. });
  21511. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21512. auto handle = cli.open_stream("GET", "/");
  21513. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21514. read_all(handle);
  21515. EXPECT_TRUE(handle.has_read_error());
  21516. });
  21517. // A framed body ends where its framing says, with or without the alert
  21518. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21519. "Content-Length: 5\r\n"
  21520. "Connection: close\r\n"
  21521. "\r\n"
  21522. "hello";
  21523. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21524. auto res = cli.Get("/");
  21525. ASSERT_TRUE(res) << to_string(res.error());
  21526. EXPECT_EQ("hello", res->body);
  21527. });
  21528. }
  21529. #endif
  21530. TEST(ResponseHeaderLengthTest, ClientReadsLongerFieldsThanServer) {
  21531. const auto value = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH * 2, 'a');
  21532. const auto response = "HTTP/1.1 200 OK\r\n"
  21533. "X-Long: " +
  21534. value +
  21535. "\r\n"
  21536. "Content-Length: 2\r\n"
  21537. "Connection: close\r\n\r\nok";
  21538. with_single_response(response, [&](Client &cli) {
  21539. auto res = cli.Get("/");
  21540. ASSERT_TRUE(res) << to_string(res.error());
  21541. EXPECT_EQ(value, res->get_header_value("X-Long"));
  21542. });
  21543. with_single_response(response, [&](Client &cli) {
  21544. auto handle = cli.open_stream("GET", "/");
  21545. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21546. EXPECT_EQ(value, handle.response->get_header_value("X-Long"));
  21547. });
  21548. std::string out;
  21549. test_raw_request("GET /hi HTTP/1.1\r\n"
  21550. "Host: localhost\r\n"
  21551. "X-Long: " +
  21552. value + "\r\n\r\n",
  21553. &out);
  21554. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  21555. }
  21556. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21557. const char *responses[] = {
  21558. "HTTP/1.1 103 Early Hints\r\n"
  21559. "Link: </style.css>; rel=preload\r\n"
  21560. "\r\n"
  21561. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21562. "HTTP/1.1 100 Continue\r\n"
  21563. "X-Note: interim\r\n"
  21564. "\r\n"
  21565. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21566. };
  21567. for (auto response : responses) {
  21568. with_single_response(response, [](Client &cli) {
  21569. auto res = cli.Get("/");
  21570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21571. EXPECT_EQ(StatusCode::OK_200, res->status);
  21572. EXPECT_EQ("ok", res->body);
  21573. });
  21574. }
  21575. }
  21576. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21577. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21578. const std::string final_response =
  21579. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21580. std::string interims;
  21581. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21582. interims += interim;
  21583. }
  21584. with_single_response(interims + final_response, [](Client &cli) {
  21585. auto res = cli.Get("/");
  21586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21587. EXPECT_EQ("ok", res->body);
  21588. });
  21589. with_single_response(interims + interim + final_response, [](Client &cli) {
  21590. auto res = cli.Get("/");
  21591. ASSERT_FALSE(res);
  21592. EXPECT_EQ(Error::Read, res.error());
  21593. });
  21594. }
  21595. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21596. #ifndef _WIN32
  21597. signal(SIGPIPE, SIG_IGN);
  21598. #endif
  21599. // The server answers the head without asking for the body. Bytes it then
  21600. // reads on the connection would be taken for the body the request declared.
  21601. auto closed_by_client = false;
  21602. std::promise<int> port_promise;
  21603. auto server_thread = serve_single_response(
  21604. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21605. [&](socket_t sock) {
  21606. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21607. char buf[256];
  21608. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21609. });
  21610. Client cli("127.0.0.1", port_promise.get_future().get());
  21611. cli.set_keep_alive(true);
  21612. cli.set_read_timeout(1, 0);
  21613. // Long enough for the client to send Expect: 100-continue.
  21614. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21617. cli.Get("/second");
  21618. server_thread.join();
  21619. EXPECT_TRUE(closed_by_client);
  21620. }
  21621. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21622. // Long enough for the client to send Expect: 100-continue
  21623. with_single_response(
  21624. "HTTP/1.1 103 Early Hints\r\n"
  21625. "Link: </style.css>; rel=preload\r\n"
  21626. "\r\n"
  21627. "HTTP/1.1 401 Unauthorized\r\n"
  21628. "Content-Length: 0\r\n\r\n",
  21629. [](Client &cli) {
  21630. cli.set_read_timeout(2, 0);
  21631. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21633. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21634. });
  21635. }
  21636. #ifdef CPPHTTPLIB_SSL_ENABLED
  21637. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21638. #ifndef _WIN32
  21639. signal(SIGPIPE, SIG_IGN);
  21640. #endif
  21641. auto reused = false;
  21642. std::promise<int> port_promise;
  21643. auto server_thread = serve_single_response(
  21644. port_promise,
  21645. "HTTP/1.1 401 Unauthorized\r\n"
  21646. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21647. "Content-Length: 0\r\n\r\n",
  21648. [&](socket_t sock) {
  21649. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21650. char buf[256];
  21651. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21652. });
  21653. Client cli("127.0.0.1", port_promise.get_future().get());
  21654. cli.set_keep_alive(true);
  21655. cli.set_digest_auth("user", "pass");
  21656. cli.set_read_timeout(1, 0);
  21657. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21658. server_thread.join();
  21659. EXPECT_FALSE(reused);
  21660. }
  21661. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21662. // Any other answer to CONNECT would read as the origin's response.
  21663. struct {
  21664. const char *response;
  21665. bool passed_on;
  21666. } cases[] = {
  21667. {"HTTP/1.1 201 Created\r\n"
  21668. "Set-Cookie: session=from-proxy\r\n"
  21669. "Content-Length: 0\r\n\r\n",
  21670. false},
  21671. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21672. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21673. "Content-Length: 0\r\n\r\n",
  21674. true},
  21675. };
  21676. for (const auto &c : cases) {
  21677. std::promise<int> port_promise;
  21678. auto server_thread = serve_single_response(port_promise, c.response);
  21679. SSLClient cli("example.com", 443);
  21680. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21681. auto res = cli.Get("/");
  21682. server_thread.join();
  21683. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21684. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21685. if (res) {
  21686. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21687. }
  21688. }
  21689. }
  21690. #endif
  21691. // Records the client's error logger calls as "error METHOD path", or
  21692. // "error null" for a call without a request
  21693. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21694. return [&log](const Error &err, const Request *req) {
  21695. log.push_back(to_string(err) + " " +
  21696. (req ? req->method + " " + req->path : "null"));
  21697. };
  21698. }
  21699. // A failed request is reported once, with the request the caller made
  21700. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21701. Server svr;
  21702. svr.Get("/big", [](const Request &, Response &res) {
  21703. res.set_content(std::string(100000, 'b'), "text/plain");
  21704. });
  21705. auto port = svr.bind_to_any_port(HOST);
  21706. std::thread t([&]() { svr.listen_after_bind(); });
  21707. auto se = detail::scope_exit([&] {
  21708. svr.stop();
  21709. t.join();
  21710. });
  21711. svr.wait_until_ready();
  21712. Client cli(HOST, port);
  21713. std::vector<std::string> log;
  21714. cli.set_error_logger(record_errors(log));
  21715. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21716. cli.Get("/big", [](const char *, size_t) { return false; });
  21717. EXPECT_EQ(expected, log);
  21718. log.clear();
  21719. cli.Get("/big", [](size_t, size_t) { return false; });
  21720. EXPECT_EQ(expected, log);
  21721. }
  21722. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21723. // Fails while the body is read
  21724. auto broken = [](const Request &, Response &res) {
  21725. res.set_content_provider(10, "text/plain",
  21726. [](size_t, size_t, DataSink &) { return false; });
  21727. };
  21728. Server other;
  21729. other.Get("/broken", broken);
  21730. auto other_port = other.bind_to_any_port(HOST);
  21731. std::thread other_t([&]() { other.listen_after_bind(); });
  21732. auto other_se = detail::scope_exit([&] {
  21733. other.stop();
  21734. other_t.join();
  21735. });
  21736. other.wait_until_ready();
  21737. Server svr;
  21738. svr.Get("/broken", broken);
  21739. svr.Get("/same-origin",
  21740. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21741. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21742. res.set_redirect("http://" + std::string(HOST) + ":" +
  21743. std::to_string(other_port) + "/broken");
  21744. });
  21745. auto port = svr.bind_to_any_port(HOST);
  21746. std::thread t([&]() { svr.listen_after_bind(); });
  21747. auto se = detail::scope_exit([&] {
  21748. svr.stop();
  21749. t.join();
  21750. });
  21751. svr.wait_until_ready();
  21752. Client cli(HOST, port);
  21753. cli.set_follow_location(true);
  21754. std::vector<std::string> log;
  21755. cli.set_error_logger(record_errors(log));
  21756. for (auto path : {"/same-origin", "/cross-origin"}) {
  21757. log.clear();
  21758. auto res = cli.Get(path);
  21759. ASSERT_FALSE(res);
  21760. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21761. log);
  21762. }
  21763. }
  21764. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21765. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21766. std::vector<std::string> log;
  21767. cli.set_error_logger(record_errors(log));
  21768. auto handle = cli.open_stream("GET", "/x");
  21769. EXPECT_FALSE(handle.is_valid());
  21770. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21771. log);
  21772. });
  21773. }
  21774. #ifdef CPPHTTPLIB_SSL_ENABLED
  21775. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21776. // Not a TLS server, so the handshake fails. It waits for a request line in
  21777. // the handshake bytes, so a short read timeout lets it close quickly.
  21778. Server svr;
  21779. svr.set_read_timeout(0, 100000);
  21780. svr.Get("/x", [](const Request &, Response &res) {
  21781. res.set_content("x", "text/plain");
  21782. });
  21783. auto port = svr.bind_to_any_port(HOST);
  21784. std::thread t([&]() { svr.listen_after_bind(); });
  21785. auto se = detail::scope_exit([&] {
  21786. svr.stop();
  21787. t.join();
  21788. });
  21789. svr.wait_until_ready();
  21790. std::vector<std::string> log;
  21791. SSLClient cli(HOST, port);
  21792. cli.enable_server_certificate_verification(false);
  21793. cli.set_error_logger(record_errors(log));
  21794. auto res = cli.Get("/x");
  21795. ASSERT_FALSE(res);
  21796. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21797. log.clear();
  21798. auto handle = cli.open_stream("GET", "/x");
  21799. EXPECT_FALSE(handle.is_valid());
  21800. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21801. log.clear();
  21802. SSLClient no_ca(HOST, port);
  21803. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21804. no_ca.set_error_logger(record_errors(log));
  21805. res = no_ca.Get("/x");
  21806. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21807. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21808. }
  21809. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21810. #ifndef _WIN32
  21811. signal(SIGPIPE, SIG_IGN);
  21812. #endif
  21813. // Refused, answered with a challenge, or closed without an answer
  21814. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21815. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21816. "Content-Length: 0\r\n\r\n",
  21817. ""}) {
  21818. std::promise<int> port_promise;
  21819. auto server_thread = serve_single_response(port_promise, response);
  21820. SSLClient cli("example.com", 443);
  21821. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21822. std::vector<std::string> log;
  21823. cli.set_error_logger(record_errors(log));
  21824. auto res = cli.Get("/");
  21825. server_thread.join();
  21826. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21827. << response;
  21828. }
  21829. }
  21830. #endif
  21831. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21832. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21833. // the chunked coding and drop Content-Length, so a front-end that trusts
  21834. // Content-Length would disagree about where the body ends (response
  21835. // smuggling). The client must reject such a response.
  21836. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21837. for (const char *te : {"chunked", "gzip, chunked"}) {
  21838. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21839. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21840. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21841. "5\r\nhello\r\n0\r\n\r\n";
  21842. with_single_response(response, [&](Client &cli) {
  21843. auto res = cli.Get("/");
  21844. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21845. EXPECT_EQ(Error::Read, res.error()) << te;
  21846. });
  21847. with_single_response(response, [&](Client &cli) {
  21848. auto handle = cli.open_stream("GET", "/");
  21849. EXPECT_FALSE(handle.is_valid()) << te;
  21850. EXPECT_EQ(Error::Read, handle.error) << te;
  21851. });
  21852. }
  21853. }
  21854. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21855. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21856. // closing the connection (unlike a request, which must be rejected).
  21857. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21858. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21859. "Transfer-Encoding: chunked\r\n"
  21860. "Connection: close\r\n"
  21861. "\r\n"
  21862. "5\r\nhello\r\n0\r\n\r\n",
  21863. "HTTP/1.1 200 OK\r\n"
  21864. "Transfer-Encoding: gzip\r\n"
  21865. "Connection: close\r\n"
  21866. "\r\n"
  21867. "hello"}) {
  21868. with_single_response(response, [&](Client &cli) {
  21869. auto res = cli.Get("/");
  21870. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21871. EXPECT_EQ("hello", res->body);
  21872. });
  21873. with_single_response(response, [&](Client &cli) {
  21874. auto handle = cli.open_stream("GET", "/");
  21875. ASSERT_TRUE(handle.is_valid()) << response;
  21876. EXPECT_EQ("hello", read_all(handle));
  21877. });
  21878. }
  21879. }
  21880. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21881. // framing headers describe nothing to read and must not be rejected.
  21882. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21883. const std::string framing = "Content-Length: 5\r\n"
  21884. "Transfer-Encoding: chunked\r\n"
  21885. "Connection: close\r\n"
  21886. "\r\n";
  21887. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21888. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21889. });
  21890. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21891. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21892. });
  21893. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21894. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21895. with_single_response(response, [&](Client &cli) {
  21896. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21897. });
  21898. with_single_response(response, [&](Client &cli) {
  21899. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21900. });
  21901. }
  21902. }
  21903. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21904. // header section, so a stream opened on one has nothing to read, whatever
  21905. // framing or coding headers it carries.
  21906. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21907. struct Case {
  21908. const char *method;
  21909. const char *status;
  21910. };
  21911. // A reader of the declared body reports an early close when nothing
  21912. // follows, and hands back what does.
  21913. struct Framing {
  21914. const char *headers;
  21915. const char *after;
  21916. };
  21917. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21918. Case{"GET", "304 Not Modified"}}) {
  21919. for (const auto &f :
  21920. {Framing{"Content-Length: 5\r\n", ""},
  21921. Framing{"Content-Length: 5\r\n", "hello"},
  21922. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21923. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21924. // Not decoded, so a build without Brotli opens it too
  21925. Framing{"Content-Encoding: br\r\n", ""}}) {
  21926. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21927. "Connection: close\r\n"
  21928. "\r\n" +
  21929. f.after;
  21930. with_single_response(response, [&](Client &cli) {
  21931. auto handle = cli.open_stream(c.method, "/");
  21932. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21933. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21934. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21935. });
  21936. }
  21937. }
  21938. }
  21939. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21940. // response, is faulty framing, so the connection is not reused after it.
  21941. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21942. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21943. "Content-Length: 0\r\n"
  21944. "Transfer-Encoding: chunked\r\n"
  21945. "\r\n"
  21946. "5\r\nhello\r\n0\r\n\r\n",
  21947. "HTTP/1.0 200 Connection established\r\n"
  21948. "Connection: keep-alive\r\n"
  21949. "Transfer-Encoding: chunked\r\n"
  21950. "\r\n"
  21951. "5\r\nhello\r\n0\r\n\r\n"}) {
  21952. with_single_response(response, [&](Client &cli) {
  21953. cli.set_keep_alive(true);
  21954. auto res = cli.Get("/");
  21955. ASSERT_TRUE(res) << response;
  21956. EXPECT_EQ("hello", res->body);
  21957. EXPECT_FALSE(cli.is_socket_open()) << response;
  21958. });
  21959. }
  21960. }
  21961. // A payload max length of 0 means no limit, however the body is framed.
  21962. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21963. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21964. "Transfer-Encoding: chunked\r\n"
  21965. "\r\n"
  21966. "5\r\nhello\r\n0\r\n\r\n",
  21967. "HTTP/1.1 200 OK\r\n"
  21968. "Connection: close\r\n"
  21969. "\r\n"
  21970. "hello"}) {
  21971. with_single_response(response, [&](Client &cli) {
  21972. cli.set_payload_max_length(0);
  21973. auto res = cli.Get("/");
  21974. ASSERT_TRUE(res) << response;
  21975. EXPECT_EQ("hello", res->body) << response;
  21976. });
  21977. }
  21978. }
  21979. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21980. Server svr;
  21981. svr.set_payload_max_length(0);
  21982. svr.Post("/echo", [](const Request &req, Response &res) {
  21983. res.set_content(req.body, "text/plain");
  21984. });
  21985. auto port = svr.bind_to_any_port(HOST);
  21986. thread t = thread([&] { svr.listen_after_bind(); });
  21987. auto se = detail::scope_exit([&] {
  21988. svr.stop();
  21989. t.join();
  21990. ASSERT_FALSE(svr.is_running());
  21991. });
  21992. svr.wait_until_ready();
  21993. Client cli(HOST, port);
  21994. auto res = cli.Post(
  21995. "/echo",
  21996. [](size_t /*offset*/, DataSink &sink) {
  21997. sink.write("hello", 5);
  21998. sink.done();
  21999. return true;
  22000. },
  22001. "text/plain");
  22002. ASSERT_TRUE(res);
  22003. EXPECT_EQ(StatusCode::OK_200, res->status);
  22004. EXPECT_EQ("hello", res->body);
  22005. }
  22006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22007. TEST_F(OpenStreamTest, Gzip) {
  22008. Client cli("127.0.0.1", port_);
  22009. auto handle = cli.open_stream("GET", "/compressible", {},
  22010. {{"Accept-Encoding", "gzip"}});
  22011. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  22012. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22013. }
  22014. TEST_F(OpenStreamTest, TrailersWithGzip) {
  22015. Client cli("127.0.0.1", port_);
  22016. auto handle =
  22017. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  22018. {{"Accept-Encoding", "gzip"}});
  22019. ASSERT_TRUE(handle.is_valid());
  22020. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  22021. EXPECT_EQ("123456789", read_all(handle));
  22022. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  22023. }
  22024. #endif
  22025. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22026. TEST_F(OpenStreamTest, Brotli) {
  22027. Client cli("127.0.0.1", port_);
  22028. auto handle =
  22029. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  22030. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  22031. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22032. }
  22033. #endif
  22034. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22035. TEST_F(OpenStreamTest, Zstd) {
  22036. Client cli("127.0.0.1", port_);
  22037. auto handle = cli.open_stream("GET", "/compressible", {},
  22038. {{"Accept-Encoding", "zstd"}});
  22039. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  22040. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22041. }
  22042. #endif
  22043. #ifdef CPPHTTPLIB_SSL_ENABLED
  22044. class SSLOpenStreamTest : public ::testing::Test {
  22045. protected:
  22046. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  22047. void SetUp() override {
  22048. svr_.Get("/hello", [](const Request &, Response &res) {
  22049. res.set_content("Hello SSL World!", "text/plain");
  22050. });
  22051. svr_.Get("/chunked", [](const Request &, Response &res) {
  22052. res.set_chunked_content_provider("text/plain",
  22053. [](size_t offset, DataSink &sink) {
  22054. if (offset < 15) {
  22055. sink.write("chunk", 5);
  22056. return true;
  22057. }
  22058. sink.done();
  22059. return true;
  22060. });
  22061. });
  22062. svr_.Post("/echo", [](const Request &req, Response &res) {
  22063. res.set_content(req.body, req.get_header_value("Content-Type"));
  22064. });
  22065. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  22066. std::string body = req.body;
  22067. res.set_chunked_content_provider(
  22068. "text/plain", [body](size_t offset, DataSink &sink) {
  22069. if (offset < body.size()) {
  22070. sink.write(body.data() + offset, body.size() - offset);
  22071. }
  22072. sink.done();
  22073. return true;
  22074. });
  22075. });
  22076. port_ = svr_.bind_to_any_port("127.0.0.1");
  22077. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22078. svr_.wait_until_ready();
  22079. }
  22080. void TearDown() override {
  22081. svr_.stop();
  22082. if (thread_.joinable()) thread_.join();
  22083. }
  22084. SSLServer svr_;
  22085. std::thread thread_;
  22086. int port_ = 0;
  22087. };
  22088. TEST_F(SSLOpenStreamTest, Basic) {
  22089. SSLClient cli("127.0.0.1", port_);
  22090. cli.enable_server_certificate_verification(false);
  22091. auto handle = cli.open_stream("GET", "/hello");
  22092. ASSERT_TRUE(handle.is_valid());
  22093. EXPECT_EQ("Hello SSL World!", read_all(handle));
  22094. }
  22095. TEST_F(SSLOpenStreamTest, Chunked) {
  22096. SSLClient cli("127.0.0.1", port_);
  22097. cli.enable_server_certificate_verification(false);
  22098. auto handle = cli.open_stream("GET", "/chunked");
  22099. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  22100. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  22101. "Transfer-Encoding") == "chunked");
  22102. auto body = read_all(handle);
  22103. EXPECT_EQ("chunkchunkchunk", body);
  22104. }
  22105. TEST_F(SSLOpenStreamTest, Post) {
  22106. SSLClient cli("127.0.0.1", port_);
  22107. cli.enable_server_certificate_verification(false);
  22108. auto handle =
  22109. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  22110. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  22111. EXPECT_EQ(200, handle.response->status);
  22112. auto body = read_all(handle);
  22113. EXPECT_EQ("Hello SSL POST", body);
  22114. }
  22115. TEST_F(SSLOpenStreamTest, PostChunked) {
  22116. SSLClient cli("127.0.0.1", port_);
  22117. cli.enable_server_certificate_verification(false);
  22118. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  22119. "Chunked SSL Data", "text/plain");
  22120. ASSERT_TRUE(handle.is_valid());
  22121. EXPECT_EQ(200, handle.response->status);
  22122. auto body = read_all(handle);
  22123. EXPECT_EQ("Chunked SSL Data", body);
  22124. }
  22125. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  22126. // Content-Length is terminated by the server closing the connection. When the
  22127. // SSL peer sends a close_notify after the body, the client must treat it as a
  22128. // clean EOF and return a successful response rather than an error.
  22129. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  22130. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22131. ASSERT_TRUE(svr.is_valid());
  22132. svr.set_keep_alive_max_count(1);
  22133. const std::string expected_body = "Hello from connection-close response!";
  22134. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  22135. res.set_content_provider("text/plain",
  22136. [&](size_t offset, DataSink &sink) -> bool {
  22137. if (offset < expected_body.size()) {
  22138. sink.write(expected_body.data() + offset,
  22139. expected_body.size() - offset);
  22140. }
  22141. sink.done();
  22142. return true;
  22143. });
  22144. });
  22145. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  22146. auto se = detail::scope_exit([&] {
  22147. svr.stop();
  22148. listen_thread.join();
  22149. ASSERT_FALSE(svr.is_running());
  22150. });
  22151. svr.wait_until_ready();
  22152. SSLClient cli(HOST, PORT);
  22153. cli.enable_server_certificate_verification(false);
  22154. auto res = cli.Get("/no-content-length");
  22155. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  22156. EXPECT_EQ(StatusCode::OK_200, res->status);
  22157. EXPECT_EQ(expected_body, res->body);
  22158. }
  22159. // Without Content-Length, the full buffer size reaches tls::read().
  22160. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  22161. if (sizeof(size_t) <= sizeof(int)) {
  22162. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  22163. }
  22164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22165. ASSERT_TRUE(svr.is_valid());
  22166. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  22167. res.set_content_provider("text/plain",
  22168. [&](size_t offset, DataSink &sink) -> bool {
  22169. if (offset == 0) { sink.write("Hello", 5); }
  22170. sink.done();
  22171. return true;
  22172. });
  22173. });
  22174. auto port = svr.bind_to_any_port(HOST);
  22175. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  22176. auto se = detail::scope_exit([&] {
  22177. svr.stop();
  22178. listen_thread.join();
  22179. });
  22180. svr.wait_until_ready();
  22181. SSLClient cli(HOST, port);
  22182. cli.enable_server_certificate_verification(false);
  22183. auto handle = cli.open_stream("GET", "/no-content-length");
  22184. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  22185. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  22186. std::unique_ptr<char[]> buf(new char[len]);
  22187. std::string body;
  22188. ssize_t n;
  22189. while ((n = handle.read(buf.get(), len)) > 0) {
  22190. body.append(buf.get(), static_cast<size_t>(n));
  22191. }
  22192. EXPECT_EQ(0, n);
  22193. EXPECT_EQ("Hello", body);
  22194. }
  22195. #endif // CPPHTTPLIB_SSL_ENABLED
  22196. //==============================================================================
  22197. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  22198. // results for various scenarios.
  22199. //==============================================================================
  22200. TEST(ParityTest, GetVsOpenStream) {
  22201. Server svr;
  22202. const std::string path = "/parity";
  22203. const std::string content = "Parity test content: hello world";
  22204. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22205. res.set_content(content, "text/plain");
  22206. });
  22207. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22208. auto se = detail::scope_exit([&] {
  22209. svr.stop();
  22210. t.join();
  22211. ASSERT_FALSE(svr.is_running());
  22212. });
  22213. svr.wait_until_ready();
  22214. Client cli(HOST, PORT);
  22215. // Non-stream path
  22216. auto r1 = cli.Get(path);
  22217. ASSERT_TRUE(r1);
  22218. EXPECT_EQ(StatusCode::OK_200, r1->status);
  22219. // Stream path
  22220. auto h = cli.open_stream("GET", path);
  22221. ASSERT_TRUE(h.is_valid());
  22222. EXPECT_EQ(r1->body, read_all(h));
  22223. }
  22224. // Helper to compress data with provided compressor type T
  22225. template <typename Compressor>
  22226. static std::string compress_payload_for_parity(const std::string &in) {
  22227. std::string out;
  22228. Compressor compressor;
  22229. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22230. [&](const char *data, size_t n) {
  22231. out.append(data, n);
  22232. return true;
  22233. });
  22234. EXPECT_TRUE(ok);
  22235. return out;
  22236. }
  22237. // Helper function for compression parity tests
  22238. template <typename Compressor>
  22239. static void test_compression_parity(const std::string &original,
  22240. const std::string &path,
  22241. const std::string &encoding) {
  22242. const std::string compressed =
  22243. compress_payload_for_parity<Compressor>(original);
  22244. Server svr;
  22245. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22246. res.set_content(compressed, "application/octet-stream");
  22247. res.set_header("Content-Encoding", encoding);
  22248. });
  22249. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22250. auto se = detail::scope_exit([&] {
  22251. svr.stop();
  22252. t.join();
  22253. ASSERT_FALSE(svr.is_running());
  22254. });
  22255. svr.wait_until_ready();
  22256. Client cli(HOST, PORT);
  22257. // Non-streaming
  22258. {
  22259. auto res = cli.Get(path);
  22260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22261. EXPECT_EQ(StatusCode::OK_200, res->status);
  22262. EXPECT_EQ(original, res->body);
  22263. }
  22264. // Streaming
  22265. {
  22266. auto h = cli.open_stream("GET", path);
  22267. ASSERT_TRUE(h.is_valid());
  22268. EXPECT_EQ(original, read_all(h));
  22269. }
  22270. }
  22271. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22272. TEST(ParityTest, Gzip) {
  22273. test_compression_parity<detail::gzip_compressor>(
  22274. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22275. }
  22276. #endif
  22277. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22278. TEST(ParityTest, Brotli) {
  22279. test_compression_parity<detail::brotli_compressor>(
  22280. "Hello, brotli parity test payload", "/parity-br", "br");
  22281. }
  22282. #endif
  22283. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22284. TEST(ParityTest, Zstd) {
  22285. test_compression_parity<detail::zstd_compressor>(
  22286. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22287. }
  22288. #endif
  22289. //==============================================================================
  22290. // New Stream API Tests
  22291. //==============================================================================
  22292. inline std::string read_body(httplib::stream::Result &result) {
  22293. std::string body;
  22294. while (result.next()) {
  22295. body.append(result.data(), result.size());
  22296. }
  22297. return body;
  22298. }
  22299. TEST(ClientConnectionTest, Basic) {
  22300. httplib::ClientConnection conn;
  22301. EXPECT_FALSE(conn.is_open());
  22302. conn.sock = 1;
  22303. EXPECT_TRUE(conn.is_open());
  22304. httplib::ClientConnection conn2(std::move(conn));
  22305. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22306. conn2.sock = INVALID_SOCKET;
  22307. }
  22308. // Unified test server for all stream::* tests
  22309. class StreamApiTest : public ::testing::Test {
  22310. protected:
  22311. void SetUp() override {
  22312. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22313. res.set_content("Hello World!", "text/plain");
  22314. });
  22315. svr_.Get("/echo-params",
  22316. [](const httplib::Request &req, httplib::Response &res) {
  22317. std::string r;
  22318. for (const auto &p : req.params) {
  22319. if (!r.empty()) r += "&";
  22320. r += p.first + "=" + p.second;
  22321. }
  22322. res.set_content(r, "text/plain");
  22323. });
  22324. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22325. res.set_content(req.body, req.get_header_value("Content-Type"));
  22326. });
  22327. svr_.Post("/echo-headers",
  22328. [](const httplib::Request &req, httplib::Response &res) {
  22329. std::string r;
  22330. for (const auto &h : req.headers)
  22331. r += h.first + ": " + h.second + "\n";
  22332. res.set_content(r, "text/plain");
  22333. });
  22334. svr_.Post("/echo-params",
  22335. [](const httplib::Request &req, httplib::Response &res) {
  22336. std::string r = "params:";
  22337. for (const auto &p : req.params)
  22338. r += p.first + "=" + p.second + ";";
  22339. res.set_content(r + " body:" + req.body, "text/plain");
  22340. });
  22341. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22342. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22343. });
  22344. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22345. res.set_content("PUT:" + req.body, "text/plain");
  22346. });
  22347. svr_.Patch("/echo",
  22348. [](const httplib::Request &req, httplib::Response &res) {
  22349. res.set_content("PATCH:" + req.body, "text/plain");
  22350. });
  22351. svr_.Delete(
  22352. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22353. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22354. "text/plain");
  22355. });
  22356. svr_.Get("/head-test",
  22357. [](const httplib::Request &, httplib::Response &res) {
  22358. res.set_content("body for HEAD", "text/plain");
  22359. });
  22360. svr_.Options("/options",
  22361. [](const httplib::Request &, httplib::Response &res) {
  22362. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22363. });
  22364. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22365. svr_.wait_until_ready();
  22366. }
  22367. void TearDown() override {
  22368. svr_.stop();
  22369. if (thread_.joinable()) thread_.join();
  22370. }
  22371. httplib::Server svr_;
  22372. std::thread thread_;
  22373. };
  22374. // stream::Get tests
  22375. TEST_F(StreamApiTest, GetBasic) {
  22376. httplib::Client cli(HOST, PORT);
  22377. auto result = httplib::stream::Get(cli, "/hello");
  22378. ASSERT_TRUE(result.is_valid());
  22379. EXPECT_EQ(200, result.status());
  22380. EXPECT_EQ("Hello World!", read_body(result));
  22381. }
  22382. TEST_F(StreamApiTest, GetWithParams) {
  22383. httplib::Client cli(HOST, PORT);
  22384. httplib::Params params{{"foo", "bar"}};
  22385. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22386. ASSERT_TRUE(result.is_valid());
  22387. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22388. }
  22389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22390. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22391. httplib::Client cli(HOST, PORT);
  22392. cli.set_payload_max_length(0);
  22393. auto result = httplib::stream::Get(cli, "/hello");
  22394. ASSERT_TRUE(result.is_valid());
  22395. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22396. EXPECT_EQ("Hello World!", read_body(result));
  22397. }
  22398. #endif
  22399. TEST_F(StreamApiTest, GetConnectionError) {
  22400. httplib::Client cli(HOST, 9999);
  22401. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22402. }
  22403. TEST_F(StreamApiTest, Get404) {
  22404. httplib::Client cli(HOST, PORT);
  22405. auto result = httplib::stream::Get(cli, "/nonexistent");
  22406. EXPECT_TRUE(result.is_valid());
  22407. EXPECT_EQ(404, result.status());
  22408. }
  22409. // stream::Post tests
  22410. TEST_F(StreamApiTest, PostBasic) {
  22411. httplib::Client cli(HOST, PORT);
  22412. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22413. "application/json");
  22414. ASSERT_TRUE(result.is_valid());
  22415. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22416. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22417. }
  22418. TEST_F(StreamApiTest, PostWithHeaders) {
  22419. httplib::Client cli(HOST, PORT);
  22420. httplib::Headers headers{{"X-Custom", "value"}};
  22421. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22422. "text/plain");
  22423. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22424. }
  22425. TEST_F(StreamApiTest, PostWithParams) {
  22426. httplib::Client cli(HOST, PORT);
  22427. httplib::Params params{{"k", "v"}};
  22428. auto result =
  22429. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22430. auto body = read_body(result);
  22431. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22432. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22433. }
  22434. TEST_F(StreamApiTest, PostLarge) {
  22435. httplib::Client cli(HOST, PORT);
  22436. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22437. size_t total = 0;
  22438. while (result.next()) {
  22439. total += result.size();
  22440. }
  22441. EXPECT_EQ(100u * 1024u, total);
  22442. }
  22443. // stream::Put/Patch tests
  22444. TEST_F(StreamApiTest, PutAndPatch) {
  22445. httplib::Client cli(HOST, PORT);
  22446. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22447. EXPECT_EQ("PUT:test", read_body(put));
  22448. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22449. EXPECT_EQ("PATCH:test", read_body(patch));
  22450. }
  22451. // stream::Delete tests
  22452. TEST_F(StreamApiTest, Delete) {
  22453. httplib::Client cli(HOST, PORT);
  22454. auto del1 = httplib::stream::Delete(cli, "/resource");
  22455. EXPECT_EQ("Deleted", read_body(del1));
  22456. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22457. EXPECT_EQ("Deleted:data", read_body(del2));
  22458. }
  22459. // stream::Head/Options tests
  22460. TEST_F(StreamApiTest, HeadAndOptions) {
  22461. httplib::Client cli(HOST, PORT);
  22462. auto head = httplib::stream::Head(cli, "/head-test");
  22463. EXPECT_TRUE(head.is_valid());
  22464. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22465. auto opts = httplib::stream::Options(cli, "/options");
  22466. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22467. }
  22468. // SSL stream::* tests
  22469. #ifdef CPPHTTPLIB_SSL_ENABLED
  22470. class SSLStreamApiTest : public ::testing::Test {
  22471. protected:
  22472. void SetUp() override {
  22473. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22474. res.set_content("Hello SSL!", "text/plain");
  22475. });
  22476. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22477. res.set_content(req.body, "text/plain");
  22478. });
  22479. port_ = svr_.bind_to_any_port("127.0.0.1");
  22480. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22481. svr_.wait_until_ready();
  22482. }
  22483. void TearDown() override {
  22484. svr_.stop();
  22485. if (thread_.joinable()) thread_.join();
  22486. }
  22487. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22488. std::thread thread_;
  22489. int port_ = 0;
  22490. };
  22491. TEST_F(SSLStreamApiTest, GetAndPost) {
  22492. httplib::SSLClient cli("127.0.0.1", port_);
  22493. cli.enable_server_certificate_verification(false);
  22494. auto get = httplib::stream::Get(cli, "/hello");
  22495. EXPECT_EQ("Hello SSL!", read_body(get));
  22496. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22497. EXPECT_EQ("test", read_body(post));
  22498. }
  22499. #endif
  22500. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22501. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22502. // BodyReader
  22503. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22504. // Test that read timeout during streaming is detected
  22505. // Use a large content-length response where server delays mid-stream
  22506. Server svr;
  22507. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22508. // Send a large response with delay in the middle
  22509. res.set_content_provider(
  22510. 1000, // content_length
  22511. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22512. if (offset < 100) {
  22513. // Send first 100 bytes immediately
  22514. std::string data(100, 'A');
  22515. sink.write(data.c_str(), data.size());
  22516. return true;
  22517. }
  22518. // Then delay longer than client timeout
  22519. std::this_thread::sleep_for(std::chrono::seconds(3));
  22520. std::string data(900, 'B');
  22521. sink.write(data.c_str(), data.size());
  22522. return true;
  22523. });
  22524. });
  22525. auto port = 8091;
  22526. std::thread t([&]() { svr.listen("localhost", port); });
  22527. svr.wait_until_ready();
  22528. Client cli("localhost", port);
  22529. cli.set_read_timeout(1, 0); // 1 second timeout
  22530. auto handle = cli.open_stream("GET", "/slow-stream");
  22531. ASSERT_TRUE(handle.is_valid());
  22532. char buf[256];
  22533. ssize_t total = 0;
  22534. ssize_t n;
  22535. bool got_error = false;
  22536. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22537. total += n;
  22538. }
  22539. if (n < 0) {
  22540. got_error = true;
  22541. // Should be timeout or read error
  22542. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22543. handle.get_read_error() == Error::Read)
  22544. << "Actual error: " << to_string(handle.get_read_error());
  22545. }
  22546. // Either we got an error, or we got less data than expected
  22547. EXPECT_TRUE(got_error || total < 1000)
  22548. << "Expected timeout but got all " << total << " bytes";
  22549. svr.stop();
  22550. t.join();
  22551. }
  22552. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22553. // Test connection closed detection via BodyReader
  22554. Server svr;
  22555. std::atomic<bool> close_now{false};
  22556. svr.Get("/will-close", [&](const Request &, Response &res) {
  22557. res.set_content_provider(
  22558. 10000, // Large content_length that we won't fully send
  22559. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22560. if (offset < 100) {
  22561. std::string data(100, 'X');
  22562. sink.write(data.c_str(), data.size());
  22563. return true;
  22564. }
  22565. // Wait for signal then abort
  22566. while (!close_now) {
  22567. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22568. }
  22569. return false; // Abort - server will close connection
  22570. });
  22571. });
  22572. auto port = 8092;
  22573. std::thread t([&]() { svr.listen("localhost", port); });
  22574. svr.wait_until_ready();
  22575. Client cli("localhost", port);
  22576. auto handle = cli.open_stream("GET", "/will-close");
  22577. ASSERT_TRUE(handle.is_valid());
  22578. char buf[256];
  22579. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22580. EXPECT_GT(n, 0) << "First read should succeed";
  22581. // Signal server to close
  22582. close_now = true;
  22583. // Keep reading until error or EOF
  22584. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22585. // Keep reading
  22586. }
  22587. // Should get an error since content_length wasn't satisfied
  22588. if (n < 0) {
  22589. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22590. handle.get_read_error() == Error::Read)
  22591. << "Actual error: " << to_string(handle.get_read_error());
  22592. }
  22593. svr.stop();
  22594. t.join();
  22595. }
  22596. #ifdef CPPHTTPLIB_SSL_ENABLED
  22597. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22598. // Test that read timeout during SSL streaming is detected
  22599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22600. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22601. res.set_content_provider(
  22602. 1000, "text/plain",
  22603. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22604. if (offset < 100) {
  22605. std::string data(100, 'A');
  22606. sink.write(data.c_str(), data.size());
  22607. return true;
  22608. }
  22609. std::this_thread::sleep_for(std::chrono::seconds(3));
  22610. std::string data(900, 'B');
  22611. sink.write(data.c_str(), data.size());
  22612. return true;
  22613. });
  22614. });
  22615. auto port = 8093;
  22616. std::thread t([&]() { svr.listen("localhost", port); });
  22617. svr.wait_until_ready();
  22618. SSLClient cli("localhost", port);
  22619. cli.enable_server_certificate_verification(false);
  22620. cli.set_read_timeout(1, 0); // 1 second timeout
  22621. auto handle = cli.open_stream("GET", "/slow-stream");
  22622. ASSERT_TRUE(handle.is_valid());
  22623. char buf[256];
  22624. ssize_t total = 0;
  22625. ssize_t n;
  22626. bool got_error = false;
  22627. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22628. total += n;
  22629. }
  22630. if (n < 0) {
  22631. got_error = true;
  22632. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22633. handle.get_read_error() == Error::Read)
  22634. << "Actual error: " << to_string(handle.get_read_error());
  22635. }
  22636. EXPECT_TRUE(got_error || total < 1000)
  22637. << "Expected timeout but got all " << total << " bytes";
  22638. svr.stop();
  22639. t.join();
  22640. }
  22641. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22642. // Test SSL connection closed detection
  22643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22644. std::atomic<bool> close_now{false};
  22645. svr.Get("/will-close", [&](const Request &, Response &res) {
  22646. res.set_content_provider(
  22647. 10000, "text/plain",
  22648. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22649. if (offset < 100) {
  22650. std::string data(100, 'X');
  22651. sink.write(data.c_str(), data.size());
  22652. return true;
  22653. }
  22654. while (!close_now) {
  22655. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22656. }
  22657. return false;
  22658. });
  22659. });
  22660. auto port = 8094;
  22661. std::thread t([&]() { svr.listen("localhost", port); });
  22662. svr.wait_until_ready();
  22663. SSLClient cli("localhost", port);
  22664. cli.enable_server_certificate_verification(false);
  22665. auto handle = cli.open_stream("GET", "/will-close");
  22666. ASSERT_TRUE(handle.is_valid());
  22667. char buf[256];
  22668. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22669. EXPECT_GT(n, 0);
  22670. // Signal server to close
  22671. close_now = true;
  22672. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22673. // Keep reading
  22674. }
  22675. if (n < 0) {
  22676. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22677. handle.get_read_error() == Error::Read)
  22678. << "Actual error: " << to_string(handle.get_read_error());
  22679. }
  22680. svr.stop();
  22681. t.join();
  22682. }
  22683. #endif
  22684. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22685. using namespace httplib;
  22686. // Create a test file
  22687. const char *fname = "etag_testfile.txt";
  22688. const char *content = "etag-content";
  22689. {
  22690. std::ofstream ofs(fname);
  22691. ofs << content;
  22692. ASSERT_TRUE(ofs.good());
  22693. }
  22694. Server svr;
  22695. svr.set_mount_point("/static", ".");
  22696. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22697. svr.wait_until_ready();
  22698. Client cli(HOST, PORT);
  22699. // First request: should get 200 with ETag header
  22700. auto res1 = cli.Get("/static/etag_testfile.txt");
  22701. ASSERT_TRUE(res1);
  22702. ASSERT_EQ(200, res1->status);
  22703. ASSERT_TRUE(res1->has_header("ETag"));
  22704. std::string etag = res1->get_header_value("ETag");
  22705. EXPECT_FALSE(etag.empty());
  22706. // Verify ETag format: W/"hex-hex"
  22707. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22708. EXPECT_EQ('W', etag[0]);
  22709. EXPECT_EQ('/', etag[1]);
  22710. EXPECT_EQ('"', etag[2]);
  22711. EXPECT_EQ('"', etag.back());
  22712. // Exact match: expect 304 Not Modified
  22713. Headers h2 = {{"If-None-Match", etag}};
  22714. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22715. ASSERT_TRUE(res2);
  22716. EXPECT_EQ(304, res2->status);
  22717. // Wildcard match: expect 304 Not Modified
  22718. Headers h3 = {{"If-None-Match", "*"}};
  22719. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22720. ASSERT_TRUE(res3);
  22721. EXPECT_EQ(304, res3->status);
  22722. // Non-matching ETag: expect 200
  22723. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22724. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22725. ASSERT_TRUE(res4);
  22726. EXPECT_EQ(200, res4->status);
  22727. // Multiple ETags with one matching: expect 304
  22728. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22729. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22730. ASSERT_TRUE(res5);
  22731. EXPECT_EQ(304, res5->status);
  22732. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22733. // that equivalent to the single comma-separated list above, so the match on
  22734. // the second line must still be found.
  22735. Headers h6;
  22736. h6.emplace("If-None-Match", "W/\"other\"");
  22737. h6.emplace("If-None-Match", etag);
  22738. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22739. ASSERT_TRUE(res6);
  22740. EXPECT_EQ(304, res6->status);
  22741. svr.stop();
  22742. t.join();
  22743. std::remove(fname);
  22744. }
  22745. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22746. using namespace httplib;
  22747. Server svr;
  22748. svr.set_mount_point("/static", ".");
  22749. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22750. svr.wait_until_ready();
  22751. Client cli(HOST, PORT);
  22752. // Send If-None-Match: * to a non-existent file
  22753. Headers h = {{"If-None-Match", "*"}};
  22754. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22756. EXPECT_EQ(404, res->status);
  22757. svr.stop();
  22758. t.join();
  22759. }
  22760. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22761. using namespace httplib;
  22762. // Create a test file
  22763. const char *fname = "etag_boundary_testfile.txt";
  22764. const char *content = "boundary-test";
  22765. {
  22766. std::ofstream ofs(fname);
  22767. ofs << content;
  22768. ASSERT_TRUE(ofs.good());
  22769. }
  22770. Server svr;
  22771. svr.set_mount_point("/static", ".");
  22772. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22773. svr.wait_until_ready();
  22774. Client cli(HOST, PORT);
  22775. // Get the actual ETag
  22776. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22777. ASSERT_TRUE(res1);
  22778. ASSERT_EQ(200, res1->status);
  22779. ASSERT_TRUE(res1->has_header("ETag"));
  22780. std::string etag = res1->get_header_value("ETag");
  22781. // Test 1: Very long ETag value (longer than actual ETag)
  22782. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22783. Headers h1 = {{"If-None-Match", "W/"
  22784. "\"very-long-etag-value-that-is-much-longer-"
  22785. "than-the-actual-etag-value\""}};
  22786. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22787. ASSERT_TRUE(res2);
  22788. EXPECT_EQ(200, res2->status); // Should not match
  22789. // Test 2: Long string followed by wildcard
  22790. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22791. // string)
  22792. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22793. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22794. ASSERT_TRUE(res3);
  22795. EXPECT_EQ(304, res3->status); // Should match on "*"
  22796. // Test 3: Wildcard followed by long string
  22797. // Should match on "*" immediately and return 304
  22798. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22799. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22800. ASSERT_TRUE(res4);
  22801. EXPECT_EQ(304, res4->status); // Should match on "*"
  22802. // Test 4: Multiple long non-matching values
  22803. // Should NOT match and return 200 (test that all comparisons are safe)
  22804. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22805. "W/\"second-long-non-matching-value\", "
  22806. "W/\"third-long-non-matching-value\""}};
  22807. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22808. ASSERT_TRUE(res5);
  22809. EXPECT_EQ(200, res5->status); // Should not match
  22810. // Test 5: Single character that is not "*" (edge case)
  22811. Headers h5 = {{"If-None-Match", "X"}};
  22812. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22813. ASSERT_TRUE(res6);
  22814. EXPECT_EQ(200, res6->status); // Should not match
  22815. svr.stop();
  22816. t.join();
  22817. std::remove(fname);
  22818. }
  22819. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22820. using namespace httplib;
  22821. // Create a test file
  22822. const char *fname = "ims_testfile.txt";
  22823. const char *content = "if-modified-since-test";
  22824. {
  22825. std::ofstream ofs(fname);
  22826. ofs << content;
  22827. ASSERT_TRUE(ofs.good());
  22828. }
  22829. Server svr;
  22830. svr.set_mount_point("/static", ".");
  22831. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22832. svr.wait_until_ready();
  22833. Client cli(HOST, PORT);
  22834. // First request: should get 200 with Last-Modified header
  22835. auto res1 = cli.Get("/static/ims_testfile.txt");
  22836. ASSERT_TRUE(res1);
  22837. ASSERT_EQ(200, res1->status);
  22838. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22839. std::string last_modified = res1->get_header_value("Last-Modified");
  22840. EXPECT_FALSE(last_modified.empty());
  22841. // If-Modified-Since with same time: expect 304
  22842. Headers h2 = {{"If-Modified-Since", last_modified}};
  22843. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22844. ASSERT_TRUE(res2);
  22845. EXPECT_EQ(304, res2->status);
  22846. // If-Modified-Since with future time: expect 304
  22847. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22848. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22849. ASSERT_TRUE(res3);
  22850. EXPECT_EQ(304, res3->status);
  22851. // If-Modified-Since with past time: expect 200
  22852. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22853. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22854. ASSERT_TRUE(res4);
  22855. EXPECT_EQ(200, res4->status);
  22856. // If-None-Match takes precedence over If-Modified-Since
  22857. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22858. ASSERT_TRUE(res1->has_header("ETag"));
  22859. std::string etag = res1->get_header_value("ETag");
  22860. Headers h5 = {{"If-None-Match", etag},
  22861. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22862. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22863. ASSERT_TRUE(res5);
  22864. EXPECT_EQ(304, res5->status);
  22865. svr.stop();
  22866. t.join();
  22867. std::remove(fname);
  22868. }
  22869. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22870. using namespace httplib;
  22871. Server svr;
  22872. // Endpoint that returns compressible content
  22873. svr.Get("/compressible", [](const Request &, Response &res) {
  22874. // Return a large enough body to trigger compression
  22875. std::string body(1000, 'a');
  22876. res.set_content(body, "text/plain");
  22877. });
  22878. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22879. svr.wait_until_ready();
  22880. Client cli(HOST, PORT);
  22881. // Request with gzip support: should get Vary header when compressed
  22882. cli.set_compress(true);
  22883. auto res1 = cli.Get("/compressible");
  22884. ASSERT_TRUE(res1);
  22885. EXPECT_EQ(200, res1->status);
  22886. // If Content-Encoding is set, Vary should also be set
  22887. if (res1->has_header("Content-Encoding")) {
  22888. EXPECT_TRUE(res1->has_header("Vary"));
  22889. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22890. }
  22891. // Request without Accept-Encoding header: should not have compression
  22892. Headers h_no_compress;
  22893. auto res2 = cli.Get("/compressible", h_no_compress);
  22894. ASSERT_TRUE(res2);
  22895. EXPECT_EQ(200, res2->status);
  22896. // Verify Vary header is present when compression is applied
  22897. // (the exact behavior depends on server configuration)
  22898. svr.stop();
  22899. t.join();
  22900. }
  22901. TEST(ETagTest, IfRangeWithETag) {
  22902. using namespace httplib;
  22903. // Create a test file with known content
  22904. const char *fname = "if_range_testfile.txt";
  22905. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22906. {
  22907. std::ofstream ofs(fname);
  22908. ofs << content;
  22909. ASSERT_TRUE(ofs.good());
  22910. }
  22911. Server svr;
  22912. svr.set_mount_point("/static", ".");
  22913. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22914. svr.wait_until_ready();
  22915. Client cli(HOST, PORT);
  22916. // First request: get ETag
  22917. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22918. ASSERT_TRUE(res1);
  22919. ASSERT_EQ(200, res1->status);
  22920. ASSERT_TRUE(res1->has_header("ETag"));
  22921. std::string etag = res1->get_header_value("ETag");
  22922. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22923. // Since our server generates weak ETags (W/"..."), If-Range with our
  22924. // ETag should NOT result in partial content - it should return full content.
  22925. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22926. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22927. ASSERT_TRUE(res2);
  22928. // Weak ETag in If-Range -> full content (200), not partial (206)
  22929. EXPECT_EQ(200, res2->status);
  22930. EXPECT_EQ(content, res2->body);
  22931. EXPECT_FALSE(res2->has_header("Content-Range"));
  22932. // Range request with non-matching If-Range (ETag): should get 200 (full
  22933. // content)
  22934. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22935. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22936. ASSERT_TRUE(res3);
  22937. EXPECT_EQ(200, res3->status);
  22938. EXPECT_EQ(content, res3->body);
  22939. EXPECT_FALSE(res3->has_header("Content-Range"));
  22940. // Range request with strong ETag (hypothetical - our server doesn't generate
  22941. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22942. // should return full content)
  22943. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22944. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22945. ASSERT_TRUE(res4);
  22946. EXPECT_EQ(200, res4->status);
  22947. EXPECT_EQ(content, res4->body);
  22948. EXPECT_FALSE(res4->has_header("Content-Range"));
  22949. svr.stop();
  22950. t.join();
  22951. std::remove(fname);
  22952. }
  22953. TEST(ETagTest, IfRangeWithDate) {
  22954. using namespace httplib;
  22955. // Create a test file
  22956. const char *fname = "if_range_date_testfile.txt";
  22957. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22958. {
  22959. std::ofstream ofs(fname);
  22960. ofs << content;
  22961. ASSERT_TRUE(ofs.good());
  22962. }
  22963. Server svr;
  22964. svr.set_mount_point("/static", ".");
  22965. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22966. svr.wait_until_ready();
  22967. Client cli(HOST, PORT);
  22968. // First request: get Last-Modified
  22969. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22970. ASSERT_TRUE(res1);
  22971. ASSERT_EQ(200, res1->status);
  22972. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22973. std::string last_modified = res1->get_header_value("Last-Modified");
  22974. // Range request with matching If-Range (date): should get 206
  22975. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22976. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22977. ASSERT_TRUE(res2);
  22978. EXPECT_EQ(206, res2->status);
  22979. EXPECT_EQ("FGHIJ", res2->body);
  22980. // Range request with old If-Range date: should get 200 (full content)
  22981. Headers h3 = {{"Range", "bytes=5-9"},
  22982. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22983. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22984. ASSERT_TRUE(res3);
  22985. EXPECT_EQ(200, res3->status);
  22986. EXPECT_EQ(content, res3->body);
  22987. // Range request with future If-Range date: should get 200 (full content)
  22988. Headers h4 = {{"Range", "bytes=0-4"},
  22989. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22990. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22991. ASSERT_TRUE(res4);
  22992. EXPECT_EQ(200, res4->status);
  22993. EXPECT_EQ(content, res4->body);
  22994. #if defined(__APPLE__) || defined(__linux__)
  22995. // File replaced by one with an older mtime: should get 200 (full content)
  22996. const std::string replaced = "abcdefghij9876543210";
  22997. {
  22998. std::ofstream ofs(fname);
  22999. ofs << replaced;
  23000. ASSERT_TRUE(ofs.good());
  23001. }
  23002. struct timeval times[2];
  23003. times[0].tv_sec = time(nullptr);
  23004. times[0].tv_usec = 0;
  23005. times[1].tv_sec = time(nullptr) - 3600;
  23006. times[1].tv_usec = 0;
  23007. ASSERT_EQ(0, utimes(fname, times));
  23008. Headers h5 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  23009. auto res5 = cli.Get("/static/if_range_date_testfile.txt", h5);
  23010. ASSERT_TRUE(res5);
  23011. EXPECT_EQ(200, res5->status);
  23012. EXPECT_EQ(replaced, res5->body);
  23013. #endif
  23014. svr.stop();
  23015. t.join();
  23016. std::remove(fname);
  23017. }
  23018. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  23019. using namespace httplib;
  23020. const char *fname = "etag_malformed.txt";
  23021. const char *content = "malformed-etag";
  23022. {
  23023. std::ofstream ofs(fname);
  23024. ofs << content;
  23025. ASSERT_TRUE(ofs.good());
  23026. }
  23027. Server svr;
  23028. svr.set_mount_point("/static", ".");
  23029. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23030. svr.wait_until_ready();
  23031. Client cli(HOST, PORT);
  23032. // baseline: should get 200 and an ETag
  23033. auto res1 = cli.Get("/static/etag_malformed.txt");
  23034. ASSERT_TRUE(res1);
  23035. ASSERT_EQ(200, res1->status);
  23036. ASSERT_TRUE(res1->has_header("ETag"));
  23037. // Malformed ETag value (missing quotes) should be treated as non-matching
  23038. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  23039. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  23040. ASSERT_TRUE(res_bad);
  23041. EXPECT_EQ(200, res_bad->status);
  23042. // Whitespace-only header value should be considered invalid / non-matching
  23043. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  23044. "Host: localhost\r\n"
  23045. "If-None-Match: \r\n"
  23046. "Connection: close\r\n"
  23047. "\r\n";
  23048. std::string out;
  23049. ASSERT_TRUE(send_request(5, raw_req, &out));
  23050. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  23051. svr.stop();
  23052. t.join();
  23053. std::remove(fname);
  23054. }
  23055. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  23056. using namespace httplib;
  23057. const char *fname = "ims_invalid_format.txt";
  23058. const char *content = "ims-bad-format";
  23059. {
  23060. std::ofstream ofs(fname);
  23061. ofs << content;
  23062. ASSERT_TRUE(ofs.good());
  23063. }
  23064. Server svr;
  23065. svr.set_mount_point("/static", ".");
  23066. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23067. svr.wait_until_ready();
  23068. Client cli(HOST, PORT);
  23069. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  23070. ASSERT_TRUE(res1);
  23071. ASSERT_EQ(200, res1->status);
  23072. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23073. // If-Modified-Since with invalid format should not result in 304
  23074. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  23075. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  23076. ASSERT_TRUE(res_bad);
  23077. EXPECT_EQ(200, res_bad->status);
  23078. // If-Range with invalid date format should be treated as mismatch -> full
  23079. // content (200)
  23080. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  23081. {"If-Range", "invalid-date"}};
  23082. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  23083. ASSERT_TRUE(res_ifrange);
  23084. EXPECT_EQ(200, res_ifrange->status);
  23085. svr.stop();
  23086. t.join();
  23087. std::remove(fname);
  23088. }
  23089. TEST(ETagTest, IfRangeWithMalformedETag) {
  23090. using namespace httplib;
  23091. const char *fname = "ifrange_malformed.txt";
  23092. const std::string content = "0123456789";
  23093. {
  23094. std::ofstream ofs(fname);
  23095. ofs << content;
  23096. ASSERT_TRUE(ofs.good());
  23097. }
  23098. Server svr;
  23099. svr.set_mount_point("/static", ".");
  23100. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23101. svr.wait_until_ready();
  23102. Client cli(HOST, PORT);
  23103. // First request: get ETag
  23104. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  23105. ASSERT_TRUE(res1);
  23106. ASSERT_EQ(200, res1->status);
  23107. ASSERT_TRUE(res1->has_header("ETag"));
  23108. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  23109. // full content (200)
  23110. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  23111. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  23112. ASSERT_TRUE(res2);
  23113. EXPECT_EQ(200, res2->status);
  23114. EXPECT_EQ(content, res2->body);
  23115. svr.stop();
  23116. t.join();
  23117. std::remove(fname);
  23118. }
  23119. TEST(ETagTest, ExtremeLargeDateValues) {
  23120. using namespace httplib;
  23121. const char *fname = "ims_extreme_date.txt";
  23122. const char *content = "ims-extreme-date";
  23123. {
  23124. std::ofstream ofs(fname);
  23125. ofs << content;
  23126. ASSERT_TRUE(ofs.good());
  23127. }
  23128. Server svr;
  23129. svr.set_mount_point("/static", ".");
  23130. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23131. svr.wait_until_ready();
  23132. Client cli(HOST, PORT);
  23133. auto res1 = cli.Get(std::string("/static/") + fname);
  23134. ASSERT_TRUE(res1);
  23135. ASSERT_EQ(200, res1->status);
  23136. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23137. // Extremely large year that may overflow date parsing routines.
  23138. Headers h_large_date = {
  23139. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23140. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  23141. ASSERT_TRUE(res_bad);
  23142. // Expect server to treat this as invalid/mismatch and return full content
  23143. EXPECT_EQ(200, res_bad->status);
  23144. // If-Range with extremely large date should be treated as mismatch -> full
  23145. // content (200)
  23146. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  23147. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23148. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  23149. ASSERT_TRUE(res_ifrange);
  23150. EXPECT_EQ(200, res_ifrange->status);
  23151. svr.stop();
  23152. t.join();
  23153. std::remove(fname);
  23154. }
  23155. TEST(ETagTest, NegativeFileModificationTime) {
  23156. using namespace httplib;
  23157. const char *fname = "ims_negative_mtime.txt";
  23158. const std::string content = "negative-mtime";
  23159. {
  23160. std::ofstream ofs(fname);
  23161. ofs << content;
  23162. ASSERT_TRUE(ofs.good());
  23163. }
  23164. // Try to set file mtime to a negative value. This may fail on some
  23165. // platforms/filesystems; if it fails, the test will still verify server
  23166. // behaves safely by performing a regular conditional request.
  23167. #if defined(__APPLE__) || defined(__linux__)
  23168. bool set_negative = false;
  23169. do {
  23170. struct timeval times[2];
  23171. // access time: now
  23172. times[0].tv_sec = time(nullptr);
  23173. times[0].tv_usec = 0;
  23174. // modification time: negative (e.g., -1)
  23175. times[1].tv_sec = -1;
  23176. times[1].tv_usec = 0;
  23177. if (utimes(fname, times) == 0) { set_negative = true; }
  23178. } while (0);
  23179. #else
  23180. bool set_negative = false;
  23181. #endif
  23182. Server svr;
  23183. svr.set_mount_point("/static", ".");
  23184. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23185. svr.wait_until_ready();
  23186. Client cli(HOST, PORT);
  23187. auto res1 = cli.Get(std::string("/static/") + fname);
  23188. ASSERT_TRUE(res1);
  23189. ASSERT_EQ(200, res1->status);
  23190. bool has_last_modified = res1->has_header("Last-Modified");
  23191. std::string last_modified;
  23192. if (has_last_modified) {
  23193. last_modified = res1->get_header_value("Last-Modified");
  23194. }
  23195. if (set_negative) {
  23196. // If we successfully set a negative mtime, ensure server returns a
  23197. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  23198. // with an old date and ensure server handles it without crash.
  23199. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  23200. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  23201. ASSERT_TRUE(res2);
  23202. // Behavior may vary; at minimum ensure server responds (200 or 304).
  23203. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  23204. } else {
  23205. // Could not set negative mtime on this platform; fall back to verifying
  23206. // that normal invalid/malformed dates are treated safely (non-304).
  23207. Headers h_bad_date = {
  23208. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23209. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  23210. ASSERT_TRUE(res_bad);
  23211. EXPECT_EQ(200, res_bad->status);
  23212. }
  23213. svr.stop();
  23214. t.join();
  23215. std::remove(fname);
  23216. }
  23217. //==============================================================================
  23218. // Integration Tests with Server
  23219. //==============================================================================
  23220. class SSEIntegrationTest : public ::testing::Test {
  23221. protected:
  23222. void SetUp() override {
  23223. stop_server_.store(false);
  23224. events_.clear();
  23225. server_ = httplib::detail::make_unique<Server>();
  23226. setup_server();
  23227. start_server();
  23228. }
  23229. void TearDown() override {
  23230. stop_server_.store(true);
  23231. event_cv_.notify_all();
  23232. server_->stop();
  23233. if (server_thread_.joinable()) { server_thread_.join(); }
  23234. }
  23235. void setup_server() {
  23236. // Simple SSE endpoint
  23237. server_->Get("/events", [this](const Request &req, Response &res) {
  23238. auto last_id = req.get_header_value("Last-Event-ID");
  23239. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  23240. res.set_chunked_content_provider(
  23241. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23242. std::unique_lock<std::mutex> lock(event_mutex_);
  23243. if (event_cv_.wait_for(
  23244. lock, std::chrono::milliseconds(200), [this] {
  23245. return !events_.empty() || stop_server_.load();
  23246. })) {
  23247. if (stop_server_.load()) { return false; }
  23248. if (!events_.empty()) {
  23249. std::string event = events_.front();
  23250. events_.erase(events_.begin());
  23251. sink.write(event.data(), event.size());
  23252. return true;
  23253. }
  23254. }
  23255. return !stop_server_.load();
  23256. });
  23257. });
  23258. // Endpoint that returns error
  23259. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23260. res.status = 500;
  23261. res.set_content("Internal Server Error", "text/plain");
  23262. });
  23263. // Endpoint for custom event types
  23264. server_->Get("/custom-events", [](const Request &, Response &res) {
  23265. res.set_chunked_content_provider(
  23266. "text/event-stream", [](size_t offset, DataSink &sink) {
  23267. if (offset == 0) {
  23268. std::string event = "event: update\ndata: updated\n\n"
  23269. "event: delete\ndata: deleted\n\n";
  23270. sink.write(event.data(), event.size());
  23271. }
  23272. return false; // End stream after sending
  23273. });
  23274. });
  23275. }
  23276. void start_server() {
  23277. port_ = server_->bind_to_any_port(HOST);
  23278. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23279. // Wait for server to start
  23280. while (!server_->is_running()) {
  23281. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23282. }
  23283. }
  23284. int get_port() const { return port_; }
  23285. void send_event(const std::string &event) {
  23286. std::lock_guard<std::mutex> lock(event_mutex_);
  23287. events_.push_back(event);
  23288. event_cv_.notify_all();
  23289. }
  23290. std::unique_ptr<Server> server_;
  23291. std::thread server_thread_;
  23292. std::mutex event_mutex_;
  23293. std::condition_variable event_cv_;
  23294. std::vector<std::string> events_;
  23295. std::atomic<bool> stop_server_{false};
  23296. std::string last_received_event_id_;
  23297. int port_ = 0;
  23298. };
  23299. //==============================================================================
  23300. // SSE Parser Tests
  23301. //==============================================================================
  23302. struct SSEParseResult {
  23303. std::vector<sse::SSEMessage> events;
  23304. std::vector<std::string> ids;
  23305. std::vector<int> retries;
  23306. bool ok = true;
  23307. std::string trace; // Every handler call in order
  23308. };
  23309. static SSEParseResult
  23310. sse_parse(const std::vector<std::string> &chunks,
  23311. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23312. SSEParseResult r;
  23313. detail::SSEParser parser(
  23314. [&](const sse::SSEMessage &msg) {
  23315. r.events.push_back(msg);
  23316. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23317. },
  23318. [&](const std::string &id) {
  23319. r.ids.push_back(id);
  23320. r.trace += "id[" + id + "]";
  23321. },
  23322. [&](int retry_ms) {
  23323. r.retries.push_back(retry_ms);
  23324. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23325. },
  23326. max_event_length);
  23327. for (const auto &chunk : chunks) {
  23328. if (!parser.parse(chunk.data(), chunk.size())) {
  23329. r.ok = false;
  23330. break;
  23331. }
  23332. }
  23333. return r;
  23334. }
  23335. static SSEParseResult sse_parse(const std::string &stream) {
  23336. return sse_parse(std::vector<std::string>{stream});
  23337. }
  23338. TEST(SSEParserTest, SingleLineData) {
  23339. auto r = sse_parse("data: hello\n\n");
  23340. ASSERT_EQ(r.events.size(), 1u);
  23341. EXPECT_EQ(r.events[0].data, "hello");
  23342. EXPECT_EQ(r.events[0].event, "message");
  23343. }
  23344. TEST(SSEParserTest, MultiLineData) {
  23345. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23346. ASSERT_EQ(r.events.size(), 1u);
  23347. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23348. }
  23349. TEST(SSEParserTest, CustomEventType) {
  23350. auto r = sse_parse("event: update\ndata: payload\n\n");
  23351. ASSERT_EQ(r.events.size(), 1u);
  23352. EXPECT_EQ(r.events[0].event, "update");
  23353. EXPECT_EQ(r.events[0].data, "payload");
  23354. }
  23355. TEST(SSEParserTest, EventIdHandling) {
  23356. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23357. ASSERT_EQ(r.events.size(), 1u);
  23358. EXPECT_EQ(r.events[0].id, "12345");
  23359. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23360. }
  23361. TEST(SSEParserTest, EmptyEventId) {
  23362. auto r = sse_parse("id:\ndata: test\n\n");
  23363. ASSERT_EQ(r.events.size(), 1u);
  23364. EXPECT_EQ(r.events[0].id, "");
  23365. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23366. }
  23367. TEST(SSEParserTest, CommentsIgnored) {
  23368. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23369. ASSERT_EQ(r.events.size(), 1u);
  23370. EXPECT_EQ(r.events[0].data, "hello");
  23371. EXPECT_EQ(r.events[0].event, "message");
  23372. }
  23373. TEST(SSEParserTest, ColonInValue) {
  23374. auto r = sse_parse("data: hello:world:test\n\n");
  23375. ASSERT_EQ(r.events.size(), 1u);
  23376. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23377. }
  23378. TEST(SSEParserTest, FieldNameOnly) {
  23379. // A line without a colon is a field name with an empty value
  23380. auto r = sse_parse("data\n\n");
  23381. ASSERT_EQ(r.events.size(), 1u);
  23382. EXPECT_EQ(r.events[0].data, "");
  23383. }
  23384. TEST(SSEParserTest, TrailingCarriageReturn) {
  23385. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23386. ASSERT_EQ(r.events.size(), 1u);
  23387. EXPECT_EQ(r.events[0].event, "update");
  23388. EXPECT_EQ(r.events[0].data, "hello");
  23389. }
  23390. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23391. auto r = sse_parse("data\r\n\r\n");
  23392. ASSERT_EQ(r.events.size(), 1u);
  23393. EXPECT_EQ(r.events[0].data, "");
  23394. }
  23395. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23396. auto r = sse_parse("event: update\rdata: hello\r\r");
  23397. ASSERT_EQ(r.events.size(), 1u);
  23398. EXPECT_EQ(r.events[0].event, "update");
  23399. EXPECT_EQ(r.events[0].data, "hello");
  23400. }
  23401. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23402. // Chunk boundaries fall inside every \r\n and right before the first one
  23403. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23404. "\ndata: hello\r", "\n\r", "\n"});
  23405. ASSERT_EQ(r.events.size(), 1u);
  23406. EXPECT_EQ(r.events[0].event, "update");
  23407. EXPECT_EQ(r.events[0].data, "hello");
  23408. }
  23409. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23410. // Only a BOM at the start of the stream is ignored
  23411. auto r = sse_parse("\xEF\xBB\xBF"
  23412. "data: first\n\n"
  23413. "\xEF\xBB\xBF"
  23414. "data: second\n\n");
  23415. ASSERT_EQ(r.events.size(), 1u);
  23416. EXPECT_EQ(r.events[0].data, "first");
  23417. }
  23418. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23419. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23420. ASSERT_EQ(r.events.size(), 1u);
  23421. EXPECT_EQ(r.events[0].data, "hello");
  23422. EXPECT_EQ(r.events[0].event, "message");
  23423. }
  23424. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23425. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23426. ASSERT_EQ(r.events.size(), 2u);
  23427. EXPECT_EQ(r.events[0].data, "hello");
  23428. EXPECT_EQ(r.events[1].data, "hello");
  23429. }
  23430. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23431. // An event without data is not dispatched, and its type must not leak
  23432. // into the next event
  23433. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23434. ASSERT_EQ(r.events.size(), 1u);
  23435. EXPECT_EQ(r.events[0].event, "message");
  23436. EXPECT_EQ(r.events[0].data, "hello");
  23437. }
  23438. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23439. // Also when the empty field replaces an earlier type
  23440. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23441. ASSERT_EQ(r.events.size(), 2u);
  23442. EXPECT_EQ(r.events[0].event, "message");
  23443. EXPECT_EQ(r.events[1].event, "message");
  23444. }
  23445. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23446. auto r = sse_parse("id: 42\n\n");
  23447. EXPECT_TRUE(r.events.empty());
  23448. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23449. }
  23450. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23451. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23452. ASSERT_EQ(r.events.size(), 2u);
  23453. EXPECT_EQ(r.events[0].id, "1");
  23454. EXPECT_EQ(r.events[1].id, "");
  23455. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23456. }
  23457. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23458. // Ids that cannot be carried in a Last-Event-ID header
  23459. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23460. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23461. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23462. }
  23463. TEST(SSEParserTest, RetryDigitsOnly) {
  23464. auto r = sse_parse("retry: 1000\n");
  23465. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23466. // A value that is not all ASCII digits, or does not fit, is ignored
  23467. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23468. EXPECT_TRUE(r.retries.empty());
  23469. }
  23470. TEST(SSEParserTest, CompleteEventParsing) {
  23471. auto r = sse_parse("event: notification\nid: evt-42\n"
  23472. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23473. ASSERT_EQ(r.events.size(), 1u);
  23474. EXPECT_EQ(r.events[0].event, "notification");
  23475. EXPECT_EQ(r.events[0].id, "evt-42");
  23476. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23477. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23478. }
  23479. TEST(SSEParserTest, IncompleteEventNotReported) {
  23480. // An event still waiting for its blank line when the stream ends is
  23481. // discarded per the SSE spec
  23482. auto r = sse_parse("id: 1\ndata: x\n");
  23483. EXPECT_TRUE(r.events.empty());
  23484. EXPECT_TRUE(r.ids.empty());
  23485. }
  23486. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23487. const std::vector<std::string> streams = {
  23488. "\xEF\xBB\xBF"
  23489. "data: bom\r\n\r\n",
  23490. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23491. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23492. };
  23493. for (const auto &stream : streams) {
  23494. auto expected = sse_parse(stream).trace;
  23495. ASSERT_FALSE(expected.empty());
  23496. for (size_t i = 0; i <= stream.size(); i++) {
  23497. auto r = sse_parse(
  23498. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23499. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23500. }
  23501. std::vector<std::string> bytes;
  23502. for (auto c : stream) {
  23503. bytes.emplace_back(1, c);
  23504. }
  23505. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23506. }
  23507. }
  23508. TEST(SSEParserTest, MaxEventLength) {
  23509. // A line still waiting for its end
  23510. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23511. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23512. // Data accumulated over the lines of one event
  23513. EXPECT_TRUE(
  23514. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23515. EXPECT_FALSE(
  23516. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23517. // 0 means no limit
  23518. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23519. // Events completed in the same chunk are still reported
  23520. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23521. EXPECT_FALSE(r.ok);
  23522. ASSERT_EQ(r.events.size(), 1u);
  23523. EXPECT_EQ(r.events[0].data, "a");
  23524. }
  23525. TEST(SSEMessageTest, Clear) {
  23526. sse::SSEMessage msg;
  23527. msg.event = "custom";
  23528. msg.data = "some data";
  23529. msg.id = "123";
  23530. msg.clear();
  23531. EXPECT_EQ(msg.event, "message");
  23532. EXPECT_EQ(msg.data, "");
  23533. EXPECT_EQ(msg.id, "");
  23534. }
  23535. //==============================================================================
  23536. // SSE Integration Tests
  23537. //==============================================================================
  23538. // Test: Successful connection and on_open callback
  23539. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23540. // Add a simple endpoint that sends one event and closes
  23541. server_->Get("/simple-event", [](const Request &, Response &res) {
  23542. res.set_chunked_content_provider(
  23543. "text/event-stream", [](size_t offset, DataSink &sink) {
  23544. if (offset == 0) {
  23545. std::string event = "data: hello\n\n";
  23546. sink.write(event.data(), event.size());
  23547. }
  23548. return false; // Close stream after sending
  23549. });
  23550. });
  23551. Client client("localhost", get_port());
  23552. sse::SSEClient sse(client, "/simple-event");
  23553. std::atomic<bool> open_called{false};
  23554. std::atomic<bool> message_received{false};
  23555. sse.on_open([&open_called]() { open_called.store(true); });
  23556. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23557. if (msg.data == "hello") { message_received.store(true); }
  23558. });
  23559. sse.set_reconnect_interval(100);
  23560. sse.set_max_reconnect_attempts(1);
  23561. // Start async
  23562. sse.start_async();
  23563. // Wait for message to be processed
  23564. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23565. sse.stop();
  23566. EXPECT_TRUE(open_called.load());
  23567. EXPECT_TRUE(message_received.load());
  23568. }
  23569. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23570. // A data line that never ends.
  23571. server_->Get("/endless-line", [](const Request &, Response &res) {
  23572. res.set_chunked_content_provider(
  23573. "text/event-stream", [](size_t offset, DataSink &sink) {
  23574. if (offset == 0) { sink.write("data: ", 6); }
  23575. std::string chunk(64 * 1024, 'A');
  23576. return sink.write(chunk.data(), chunk.size());
  23577. });
  23578. });
  23579. Client client("localhost", get_port());
  23580. sse::SSEClient sse(client, "/endless-line");
  23581. std::atomic<bool> too_long{false};
  23582. sse.on_error([&](Error err) {
  23583. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23584. });
  23585. sse.set_max_reconnect_attempts(1);
  23586. sse.start_async();
  23587. for (int i = 0; i < 500 && !too_long; i++) {
  23588. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23589. }
  23590. sse.stop();
  23591. EXPECT_TRUE(too_long);
  23592. }
  23593. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23594. // Far more in all than the client's payload limit below.
  23595. server_->Get("/many-events", [](const Request &, Response &res) {
  23596. res.set_chunked_content_provider(
  23597. "text/event-stream", [](size_t offset, DataSink &sink) {
  23598. if (offset == 0) {
  23599. std::string events;
  23600. for (int i = 0; i < 1000; i++) {
  23601. events += "data: message\n\n";
  23602. }
  23603. sink.write(events.data(), events.size());
  23604. }
  23605. return false;
  23606. });
  23607. });
  23608. Client client("localhost", get_port());
  23609. client.set_payload_max_length(1024);
  23610. sse::SSEClient sse(client, "/many-events");
  23611. std::atomic<int> messages{0};
  23612. std::atomic<bool> too_large{false};
  23613. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23614. sse.on_error([&](Error err) {
  23615. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23616. });
  23617. sse.set_max_reconnect_attempts(1);
  23618. sse.start_async();
  23619. for (int i = 0; i < 500 && messages < 1000; i++) {
  23620. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23621. }
  23622. sse.stop();
  23623. EXPECT_GE(messages.load(), 1000);
  23624. EXPECT_FALSE(too_large);
  23625. }
  23626. // Test: on_message callback
  23627. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23628. // Endpoint that sends multiple events then closes
  23629. server_->Get("/multi-event", [](const Request &, Response &res) {
  23630. res.set_chunked_content_provider(
  23631. "text/event-stream", [](size_t offset, DataSink &sink) {
  23632. if (offset == 0) {
  23633. std::string events = "data: message1\n\ndata: message2\n\n";
  23634. sink.write(events.data(), events.size());
  23635. }
  23636. return false;
  23637. });
  23638. });
  23639. Client client("localhost", get_port());
  23640. sse::SSEClient sse(client, "/multi-event");
  23641. std::vector<std::string> received_messages;
  23642. std::mutex messages_mutex;
  23643. sse.on_message([&](const sse::SSEMessage &msg) {
  23644. std::lock_guard<std::mutex> lock(messages_mutex);
  23645. received_messages.push_back(msg.data);
  23646. });
  23647. sse.set_reconnect_interval(100);
  23648. sse.set_max_reconnect_attempts(1);
  23649. sse.start_async();
  23650. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23651. sse.stop();
  23652. std::lock_guard<std::mutex> lock(messages_mutex);
  23653. EXPECT_GE(received_messages.size(), 2u);
  23654. if (received_messages.size() >= 2) {
  23655. EXPECT_EQ(received_messages[0], "message1");
  23656. EXPECT_EQ(received_messages[1], "message2");
  23657. }
  23658. }
  23659. // Test: on_event for specific types
  23660. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23661. Client client("localhost", get_port());
  23662. sse::SSEClient sse(client, "/custom-events");
  23663. std::atomic<bool> update_received{false};
  23664. std::atomic<bool> delete_received{false};
  23665. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23666. if (msg.data == "updated") { update_received.store(true); }
  23667. });
  23668. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23669. if (msg.data == "deleted") { delete_received.store(true); }
  23670. });
  23671. sse.set_max_reconnect_attempts(1);
  23672. sse.start_async();
  23673. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23674. sse.stop();
  23675. EXPECT_TRUE(update_received.load());
  23676. EXPECT_TRUE(delete_received.load());
  23677. }
  23678. // Test: on_error callback on connection failure
  23679. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23680. // Connect to a non-existent port
  23681. Client client("localhost", 59999);
  23682. sse::SSEClient sse(client, "/events");
  23683. std::atomic<bool> error_called{false};
  23684. Error received_error = Error::Success;
  23685. sse.on_error([&](Error err) {
  23686. error_called.store(true);
  23687. received_error = err;
  23688. });
  23689. sse.set_reconnect_interval(50);
  23690. sse.set_max_reconnect_attempts(1);
  23691. sse.start_async();
  23692. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23693. sse.stop();
  23694. EXPECT_TRUE(error_called.load());
  23695. EXPECT_NE(received_error, Error::Success);
  23696. }
  23697. // Test: Last-Event-ID header sent on reconnect
  23698. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23699. // Endpoint that sends event with ID
  23700. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23701. res.set_chunked_content_provider(
  23702. "text/event-stream", [](size_t offset, DataSink &sink) {
  23703. if (offset == 0) {
  23704. std::string event = "id: evt-123\ndata: test\n\n";
  23705. sink.write(event.data(), event.size());
  23706. }
  23707. return false;
  23708. });
  23709. });
  23710. Client client("localhost", get_port());
  23711. sse::SSEClient sse(client, "/event-with-id");
  23712. std::atomic<bool> id_received{false};
  23713. sse.on_message([&](const sse::SSEMessage &msg) {
  23714. if (!msg.id.empty()) { id_received.store(true); }
  23715. });
  23716. sse.set_reconnect_interval(100);
  23717. sse.set_max_reconnect_attempts(1);
  23718. sse.start_async();
  23719. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23720. sse.stop();
  23721. EXPECT_TRUE(id_received.load());
  23722. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23723. }
  23724. // Test: last_event_id() read from another thread while start_async() runs
  23725. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23726. // Ids of every length up to 200, so the stored id keeps changing size
  23727. server_->Get("/many-ids", [](const Request &, Response &res) {
  23728. res.set_chunked_content_provider(
  23729. "text/event-stream", [](size_t offset, DataSink &sink) {
  23730. if (offset == 0) {
  23731. std::string events;
  23732. for (size_t i = 0; i < 2000; i++) {
  23733. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23734. events += "data: x\n\n";
  23735. }
  23736. events += "id: end\ndata: x\n\n";
  23737. sink.write(events.data(), events.size());
  23738. }
  23739. return false;
  23740. });
  23741. });
  23742. Client client("localhost", get_port());
  23743. sse::SSEClient sse(client, "/many-ids");
  23744. // Wait out the rest of the test rather than replay the stream
  23745. sse.set_reconnect_interval(10000);
  23746. sse.set_max_reconnect_attempts(1);
  23747. sse.start_async();
  23748. auto well_formed = true;
  23749. std::string id;
  23750. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23751. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23752. id = sse.last_event_id();
  23753. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23754. well_formed = false;
  23755. }
  23756. }
  23757. sse.stop();
  23758. EXPECT_TRUE(well_formed);
  23759. EXPECT_EQ(sse.last_event_id(), "end");
  23760. }
  23761. // Test: Manual stop
  23762. TEST_F(SSEIntegrationTest, ManualStop) {
  23763. // Endpoint that sends one event and stays open briefly. The server outlives
  23764. // this test body, so the provider uses the fixture's flag, not a local.
  23765. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23766. res.set_chunked_content_provider(
  23767. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23768. if (offset == 0) {
  23769. std::string event = "data: connected\n\n";
  23770. sink.write(event.data(), event.size());
  23771. }
  23772. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23773. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23774. }
  23775. return false;
  23776. });
  23777. });
  23778. Client client("localhost", get_port());
  23779. sse::SSEClient sse(client, "/stay-open");
  23780. std::atomic<bool> connected{false};
  23781. sse.on_open([&connected]() { connected.store(true); });
  23782. sse.set_reconnect_interval(100);
  23783. sse.set_max_reconnect_attempts(1);
  23784. sse.start_async();
  23785. // Wait for connection to establish
  23786. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23787. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23788. }
  23789. EXPECT_TRUE(connected.load());
  23790. EXPECT_TRUE(sse.is_connected());
  23791. // Signal handler to stop
  23792. stop_server_.store(true);
  23793. // Stop SSE client
  23794. sse.stop();
  23795. EXPECT_FALSE(sse.is_connected());
  23796. }
  23797. // Sends one event, then nothing until stop is set
  23798. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23799. return [&stop](const Request &, Response &res) {
  23800. res.set_chunked_content_provider(
  23801. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23802. if (offset == 0) {
  23803. std::string event = "data: hello\n\n";
  23804. sink.write(event.data(), event.size());
  23805. }
  23806. while (!stop.load()) {
  23807. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23808. }
  23809. return false;
  23810. });
  23811. };
  23812. }
  23813. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23814. static void check_stop_interrupts_blocked_read(Client &client) {
  23815. client.set_read_timeout(30, 0);
  23816. for (auto by_destructor : {false, true}) {
  23817. std::atomic<bool> received{false};
  23818. std::chrono::steady_clock::time_point start;
  23819. {
  23820. sse::SSEClient sse(client, "/idle-stream");
  23821. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23822. sse.start_async();
  23823. for (int i = 0; i < 500 && !received.load(); ++i) {
  23824. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23825. }
  23826. ASSERT_TRUE(received.load());
  23827. // Let the client block in the next read
  23828. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23829. start = std::chrono::steady_clock::now();
  23830. if (!by_destructor) { sse.stop(); }
  23831. }
  23832. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23833. std::chrono::seconds(2));
  23834. }
  23835. }
  23836. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23837. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23838. Client client("localhost", get_port());
  23839. check_stop_interrupts_blocked_read(client);
  23840. }
  23841. #ifdef CPPHTTPLIB_SSL_ENABLED
  23842. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23844. std::atomic<bool> done{false};
  23845. svr.Get("/idle-stream", idle_event_stream(done));
  23846. auto port = svr.bind_to_any_port(HOST);
  23847. std::thread t([&] { svr.listen_after_bind(); });
  23848. auto se = detail::scope_exit([&] {
  23849. done.store(true);
  23850. svr.stop();
  23851. t.join();
  23852. });
  23853. svr.wait_until_ready();
  23854. Client client("https://localhost:" + std::to_string(port));
  23855. client.enable_server_certificate_verification(false);
  23856. check_stop_interrupts_blocked_read(client);
  23857. }
  23858. #endif
  23859. // Test: SSEClient with custom headers
  23860. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23861. // Setup a server endpoint that checks for custom header
  23862. std::atomic<bool> header_received{false};
  23863. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23864. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23865. header_received.store(true);
  23866. }
  23867. res.set_chunked_content_provider("text/event-stream",
  23868. [](size_t, DataSink &) { return false; });
  23869. });
  23870. Client client("localhost", get_port());
  23871. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23872. sse::SSEClient sse(client, "/header-check", headers);
  23873. sse.set_max_reconnect_attempts(1);
  23874. sse.start_async();
  23875. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23876. sse.stop();
  23877. EXPECT_TRUE(header_received.load());
  23878. }
  23879. // Test: Reconnect interval configuration
  23880. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23881. Client client("localhost", get_port());
  23882. sse::SSEClient sse(client, "/events");
  23883. auto &result = sse.set_reconnect_interval(500);
  23884. // Builder pattern should return reference to self
  23885. EXPECT_EQ(&result, &sse);
  23886. }
  23887. // Test: Max reconnect attempts
  23888. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23889. // Connect to non-existent port to force reconnects
  23890. Client client("localhost", 59998);
  23891. sse::SSEClient sse(client, "/events");
  23892. std::atomic<int> error_count{0};
  23893. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23894. sse.set_reconnect_interval(50);
  23895. sse.set_max_reconnect_attempts(2);
  23896. auto start = std::chrono::steady_clock::now();
  23897. sse.start(); // Blocking call
  23898. auto end = std::chrono::steady_clock::now();
  23899. // Should have stopped after 2 failed attempts
  23900. EXPECT_GE(error_count.load(), 2);
  23901. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23902. auto duration =
  23903. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23904. #ifdef _WIN32
  23905. // Windows is much slower for socket connection failures
  23906. EXPECT_LT(duration.count(), 7000);
  23907. #else
  23908. EXPECT_LT(duration.count(), 1000);
  23909. #endif
  23910. }
  23911. // Test: Multi-line data in integration
  23912. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23913. // Endpoint with multi-line data
  23914. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23915. res.set_chunked_content_provider(
  23916. "text/event-stream", [](size_t offset, DataSink &sink) {
  23917. if (offset == 0) {
  23918. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23919. sink.write(event.data(), event.size());
  23920. }
  23921. return false;
  23922. });
  23923. });
  23924. Client client("localhost", get_port());
  23925. sse::SSEClient sse(client, "/multiline-data");
  23926. std::string received_data;
  23927. std::mutex data_mutex;
  23928. sse.on_message([&](const sse::SSEMessage &msg) {
  23929. std::lock_guard<std::mutex> lock(data_mutex);
  23930. received_data = msg.data;
  23931. });
  23932. sse.set_reconnect_interval(100);
  23933. sse.set_max_reconnect_attempts(1);
  23934. sse.start_async();
  23935. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23936. sse.stop();
  23937. std::lock_guard<std::mutex> lock(data_mutex);
  23938. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23939. }
  23940. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23941. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23942. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23943. DataSink &sink) {
  23944. if (offset == 0) {
  23945. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23946. sink.write(events.data(), events.size());
  23947. }
  23948. return false;
  23949. });
  23950. });
  23951. Client client("localhost", get_port());
  23952. sse::SSEClient sse(client, "/empty-data-lines");
  23953. std::mutex mutex;
  23954. std::condition_variable cv;
  23955. std::vector<std::string> received;
  23956. sse.on_message([&](const sse::SSEMessage &msg) {
  23957. std::lock_guard<std::mutex> lock(mutex);
  23958. received.push_back(msg.data);
  23959. cv.notify_all();
  23960. });
  23961. sse.set_max_reconnect_attempts(1);
  23962. sse.start_async();
  23963. {
  23964. std::unique_lock<std::mutex> lock(mutex);
  23965. cv.wait_for(lock, std::chrono::seconds(2),
  23966. [&] { return received.size() >= 3; });
  23967. }
  23968. sse.stop();
  23969. ASSERT_GE(received.size(), 3u);
  23970. EXPECT_EQ(received[0], "");
  23971. EXPECT_EQ(received[1], "\nhello");
  23972. EXPECT_EQ(received[2], "");
  23973. }
  23974. // Test: Auto-reconnect after server disconnection
  23975. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23976. std::atomic<int> connection_count{0};
  23977. std::atomic<int> message_count{0};
  23978. // Endpoint that sends one event and closes, forcing reconnect
  23979. server_->Get("/reconnect-test",
  23980. [&connection_count](const Request &, Response &res) {
  23981. connection_count.fetch_add(1);
  23982. res.set_chunked_content_provider(
  23983. "text/event-stream", [](size_t offset, DataSink &sink) {
  23984. if (offset == 0) {
  23985. std::string event = "data: hello\n\n";
  23986. sink.write(event.data(), event.size());
  23987. }
  23988. return false; // Close connection after sending
  23989. });
  23990. });
  23991. Client client("localhost", get_port());
  23992. sse::SSEClient sse(client, "/reconnect-test");
  23993. sse.on_message([&message_count](const sse::SSEMessage &) {
  23994. message_count.fetch_add(1);
  23995. });
  23996. sse.set_reconnect_interval(100);
  23997. sse.set_max_reconnect_attempts(3);
  23998. sse.start_async();
  23999. // Wait long enough for multiple reconnects
  24000. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24001. sse.stop();
  24002. // Should have connected multiple times (initial + reconnects)
  24003. EXPECT_GE(connection_count.load(), 2);
  24004. // Should have received messages from multiple connections
  24005. EXPECT_GE(message_count.load(), 2);
  24006. }
  24007. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  24008. std::atomic<int> connection_count{0};
  24009. // Neither Content-Length nor chunked: the close ends the stream
  24010. server_->Get("/close-delimited",
  24011. [&connection_count](const Request &, Response &res) {
  24012. connection_count.fetch_add(1);
  24013. res.set_content_provider(
  24014. "text/event-stream", [](size_t offset, DataSink &sink) {
  24015. if (offset == 0) {
  24016. std::string event = "data: hello\n\n";
  24017. sink.write(event.data(), event.size());
  24018. } else {
  24019. sink.done();
  24020. }
  24021. return true;
  24022. });
  24023. });
  24024. Client client("localhost", get_port());
  24025. sse::SSEClient sse(client, "/close-delimited");
  24026. std::atomic<int> error_count{0};
  24027. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  24028. sse.set_reconnect_interval(100);
  24029. sse.start_async();
  24030. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  24031. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24032. }
  24033. sse.stop();
  24034. // Reconnects as after any end of the stream, but reports no error
  24035. EXPECT_GE(connection_count.load(), 2);
  24036. EXPECT_EQ(0, error_count.load());
  24037. }
  24038. // Test: A retry field of all ASCII digits sets the reconnection time
  24039. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  24040. std::mutex mutex;
  24041. std::condition_variable cv;
  24042. std::vector<std::chrono::steady_clock::time_point> connected_at;
  24043. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  24044. {
  24045. std::lock_guard<std::mutex> lock(mutex);
  24046. connected_at.push_back(std::chrono::steady_clock::now());
  24047. cv.notify_all();
  24048. }
  24049. res.set_chunked_content_provider(
  24050. "text/event-stream", [](size_t offset, DataSink &sink) {
  24051. if (offset == 0) {
  24052. std::string event = "retry: 0\ndata: hello\n\n";
  24053. sink.write(event.data(), event.size());
  24054. }
  24055. return false;
  24056. });
  24057. });
  24058. Client client("localhost", get_port());
  24059. sse::SSEClient sse(client, "/zero-retry");
  24060. sse.set_reconnect_interval(10000);
  24061. sse.start_async();
  24062. {
  24063. std::unique_lock<std::mutex> lock(mutex);
  24064. cv.wait_for(lock, std::chrono::seconds(5),
  24065. [&] { return connected_at.size() >= 2; });
  24066. }
  24067. sse.stop();
  24068. // The server-supplied interval is applied, but never below 100ms, so
  24069. // "retry: 0" does not cause a busy reconnect loop
  24070. std::lock_guard<std::mutex> lock(mutex);
  24071. ASSERT_GE(connected_at.size(), 2u);
  24072. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  24073. connected_at[1] - connected_at[0])
  24074. .count();
  24075. EXPECT_GE(interval_ms, 100);
  24076. }
  24077. // Test: Last-Event-ID sent on reconnect
  24078. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  24079. std::atomic<int> connection_count{0};
  24080. std::vector<std::string> received_last_event_ids;
  24081. std::mutex id_mutex;
  24082. // Endpoint that checks Last-Event-ID header and sends event with ID
  24083. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  24084. int conn = connection_count.fetch_add(1);
  24085. // Capture the Last-Event-ID header from each connection
  24086. {
  24087. std::lock_guard<std::mutex> lock(id_mutex);
  24088. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  24089. }
  24090. res.set_chunked_content_provider(
  24091. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  24092. if (offset == 0) {
  24093. std::string event =
  24094. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  24095. sink.write(event.data(), event.size());
  24096. }
  24097. return false;
  24098. });
  24099. });
  24100. Client client("localhost", get_port());
  24101. sse::SSEClient sse(client, "/reconnect-with-id");
  24102. sse.set_reconnect_interval(100);
  24103. sse.set_max_reconnect_attempts(3);
  24104. sse.start_async();
  24105. // Wait for at least 2 connections
  24106. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  24107. sse.stop();
  24108. // Verify behavior
  24109. std::lock_guard<std::mutex> lock(id_mutex);
  24110. EXPECT_GE(received_last_event_ids.size(), 2u);
  24111. // First connection should have no Last-Event-ID
  24112. if (!received_last_event_ids.empty()) {
  24113. EXPECT_EQ(received_last_event_ids[0], "");
  24114. }
  24115. // Second connection should have Last-Event-ID from first connection
  24116. if (received_last_event_ids.size() >= 2) {
  24117. EXPECT_EQ(received_last_event_ids[1], "event-0");
  24118. }
  24119. }
  24120. // Test: set_headers updates headers used on reconnect
  24121. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  24122. std::vector<std::string> received_tokens;
  24123. std::mutex token_mutex;
  24124. // Endpoint that captures Authorization header
  24125. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  24126. {
  24127. std::lock_guard<std::mutex> lock(token_mutex);
  24128. received_tokens.push_back(req.get_header_value("Authorization"));
  24129. }
  24130. res.set_chunked_content_provider(
  24131. "text/event-stream", [](size_t offset, DataSink &sink) {
  24132. if (offset == 0) {
  24133. std::string event = "data: hello\n\n";
  24134. sink.write(event.data(), event.size());
  24135. }
  24136. return false; // Close connection to trigger reconnect
  24137. });
  24138. });
  24139. Client client("localhost", get_port());
  24140. Headers headers = {{"Authorization", "Bearer old-token"}};
  24141. sse::SSEClient sse(client, "/auth-check", headers);
  24142. // Update headers on each successful connection
  24143. sse.on_open(
  24144. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  24145. sse.set_reconnect_interval(100);
  24146. sse.set_max_reconnect_attempts(3);
  24147. sse.start_async();
  24148. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24149. sse.stop();
  24150. std::lock_guard<std::mutex> lock(token_mutex);
  24151. ASSERT_GE(received_tokens.size(), 2u);
  24152. // First connection uses original header
  24153. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  24154. // Second connection uses updated header from set_headers
  24155. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  24156. }
  24157. // Test: 401 allows reconnection (so on_error can refresh headers)
  24158. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  24159. std::atomic<int> connection_count{0};
  24160. // Endpoint: returns 401 on first attempt, 200 on second
  24161. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  24162. int conn = connection_count.fetch_add(1);
  24163. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  24164. res.status = StatusCode::Unauthorized_401;
  24165. res.set_content("Unauthorized", "text/plain");
  24166. return;
  24167. }
  24168. res.set_chunked_content_provider(
  24169. "text/event-stream", [](size_t offset, DataSink &sink) {
  24170. if (offset == 0) {
  24171. std::string event = "data: authenticated\n\n";
  24172. sink.write(event.data(), event.size());
  24173. }
  24174. return false;
  24175. });
  24176. });
  24177. Client client("localhost", get_port());
  24178. Headers headers = {{"Authorization", "Bearer expired"}};
  24179. sse::SSEClient sse(client, "/auth-retry", headers);
  24180. std::atomic<bool> message_received{false};
  24181. // Refresh token on error
  24182. sse.on_error(
  24183. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  24184. sse.on_message([&](const sse::SSEMessage &msg) {
  24185. if (msg.data == "authenticated") { message_received.store(true); }
  24186. });
  24187. sse.set_reconnect_interval(100);
  24188. sse.set_max_reconnect_attempts(3);
  24189. sse.start_async();
  24190. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24191. sse.stop();
  24192. // Should have reconnected after 401 and succeeded with new token
  24193. EXPECT_GE(connection_count.load(), 2);
  24194. EXPECT_TRUE(message_received.load());
  24195. }
  24196. TEST(Issue2318Test, EmptyHostString) {
  24197. {
  24198. httplib::Client cli_empty("", PORT);
  24199. auto res = cli_empty.Get("/");
  24200. ASSERT_FALSE(res);
  24201. EXPECT_EQ(httplib::Error::Connection, res.error());
  24202. }
  24203. {
  24204. httplib::Client cli(" ", PORT);
  24205. auto res = cli.Get("/");
  24206. ASSERT_FALSE(res);
  24207. EXPECT_EQ(httplib::Error::Connection, res.error());
  24208. }
  24209. }
  24210. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  24211. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  24212. Server svr;
  24213. // Set a small payload limit (1KB)
  24214. svr.set_payload_max_length(1024);
  24215. svr.Post("/test", [&](const Request &req, Response &res) {
  24216. res.set_content("Body size: " + std::to_string(req.body.size()),
  24217. "text/plain");
  24218. });
  24219. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  24220. auto se = detail::scope_exit([&] {
  24221. svr.stop();
  24222. listen_thread.join();
  24223. });
  24224. svr.wait_until_ready();
  24225. // Create data that compresses well but exceeds limit when decompressed
  24226. // 8KB of repeated null bytes compresses to a very small size
  24227. std::string original_data(8 * 1024, '\0');
  24228. // Compress the data using gzip
  24229. std::string compressed_data;
  24230. detail::gzip_compressor compressor;
  24231. compressor.compress(original_data.data(), original_data.size(), true,
  24232. [&](const char *data, size_t size) {
  24233. compressed_data.append(data, size);
  24234. return true;
  24235. });
  24236. // Verify compression worked (compressed should be much smaller)
  24237. ASSERT_LT(compressed_data.size(), original_data.size());
  24238. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  24239. // Send compressed data with Content-Encoding: gzip
  24240. Client cli(HOST, PORT);
  24241. Headers headers = {{"Content-Encoding", "gzip"}};
  24242. auto res =
  24243. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24244. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24246. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24247. }
  24248. #endif
  24249. // ============================================================================
  24250. // OpenSSL-Specific Tests
  24251. // ============================================================================
  24252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24253. X509 *readCertificate(const std::string &strFileName) {
  24254. std::ifstream inStream(strFileName);
  24255. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24256. std::istreambuf_iterator<char>());
  24257. if (strCertPEM.empty()) return (nullptr);
  24258. BIO *pbCert = BIO_new(BIO_s_mem());
  24259. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24260. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24261. BIO_free(pbCert);
  24262. return (pCert);
  24263. }
  24264. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24265. std::ifstream inStream(strFileName);
  24266. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24267. std::istreambuf_iterator<char>());
  24268. if (strPrivateKeyPEM.empty()) return (nullptr);
  24269. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24270. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24271. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24272. BIO_free(pbPrivKey);
  24273. return (pPrivateKey);
  24274. }
  24275. TEST(BindServerTest, UpdateCerts) {
  24276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24277. int port = svr.bind_to_any_port("0.0.0.0");
  24278. ASSERT_TRUE(svr.is_valid());
  24279. ASSERT_TRUE(port > 0);
  24280. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24281. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24282. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24283. ASSERT_TRUE(cert != nullptr);
  24284. ASSERT_TRUE(ca_cert != nullptr);
  24285. ASSERT_TRUE(key != nullptr);
  24286. X509_STORE *cert_store = X509_STORE_new();
  24287. X509_STORE_add_cert(cert_store, ca_cert);
  24288. // svr.update_certs(cert, key, cert_store); // deprecated
  24289. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24290. CLIENT_CA_CERT_FILE);
  24291. ASSERT_TRUE(svr.is_valid());
  24292. svr.stop();
  24293. X509_STORE_free(cert_store);
  24294. X509_free(cert);
  24295. X509_free(ca_cert);
  24296. EVP_PKEY_free(key);
  24297. }
  24298. // Test that update_certs() updates client CA list correctly
  24299. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24300. // Start with file-based constructor
  24301. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24302. ASSERT_TRUE(svr.is_valid());
  24303. // Initially no client CA list should be set
  24304. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24305. ASSERT_TRUE(ssl_ctx != nullptr);
  24306. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24307. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24308. // Now update with client CA (PEM string)
  24309. std::string cert_pem, key_pem, ca_pem;
  24310. read_file(SERVER_CERT_FILE, cert_pem);
  24311. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24312. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24313. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24314. ASSERT_TRUE(svr.is_valid());
  24315. // Now client CA list should be set
  24316. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24317. ASSERT_TRUE(ca_list_after != nullptr);
  24318. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24319. }
  24320. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24321. // Test that the file-path SSLServer constructor properly sets the client CA
  24322. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24324. ASSERT_TRUE(svr.is_valid());
  24325. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24326. ASSERT_TRUE(ssl_ctx != nullptr);
  24327. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24328. ASSERT_TRUE(ca_list != nullptr);
  24329. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24330. }
  24331. #endif
  24332. // ============================================================================
  24333. // MbedTLS-Specific Tests
  24334. // ============================================================================
  24335. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24336. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24337. using namespace httplib::tls;
  24338. // Track if callback was invoked
  24339. bool callback_invoked = false;
  24340. // The callback receives void* ctx which is actually MbedTlsContext*
  24341. // We can access the mbedtls_ssl_config via the context
  24342. auto setup_callback = [&callback_invoked](void *ctx) {
  24343. callback_invoked = true;
  24344. // Cast to MbedTlsContext* to access the ssl config
  24345. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24346. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24347. // Use static variables to hold certificate data (simplified for test)
  24348. static mbedtls_x509_crt own_cert;
  24349. static mbedtls_pk_context own_key;
  24350. static mbedtls_x509_crt ca_chain;
  24351. static bool initialized = false;
  24352. if (!initialized) {
  24353. mbedtls_x509_crt_init(&own_cert);
  24354. mbedtls_pk_init(&own_key);
  24355. mbedtls_x509_crt_init(&ca_chain);
  24356. // Load server certificate
  24357. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24358. return false;
  24359. }
  24360. // Load server private key.
  24361. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24362. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24363. #if MBEDTLS_VERSION_MAJOR == 3
  24364. ,
  24365. mbedtls_ctr_drbg_random, nullptr
  24366. #endif
  24367. ) != 0) {
  24368. return false;
  24369. }
  24370. // Load CA chain for client verification
  24371. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24372. return false;
  24373. }
  24374. initialized = true;
  24375. }
  24376. // Configure the SSL config
  24377. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24378. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24379. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24380. // Set minimum TLS version using mbedTLS native API
  24381. #if MBEDTLS_VERSION_MAJOR >= 3
  24382. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24383. #else
  24384. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24385. MBEDTLS_SSL_MINOR_VERSION_3);
  24386. #endif
  24387. return true;
  24388. };
  24389. SSLServer svr(setup_callback);
  24390. ASSERT_TRUE(svr.is_valid());
  24391. ASSERT_TRUE(callback_invoked);
  24392. svr.Get("/test", [&](const Request &req, Response &res) {
  24393. res.set_content("test", "text/plain");
  24394. auto cert = req.peer_cert();
  24395. ASSERT_TRUE(static_cast<bool>(cert));
  24396. auto common_name = cert.subject_cn();
  24397. EXPECT_EQ("Common Name", common_name);
  24398. });
  24399. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24400. auto se = detail::scope_exit([&] {
  24401. svr.stop();
  24402. t.join();
  24403. ASSERT_FALSE(svr.is_running());
  24404. });
  24405. svr.wait_until_ready();
  24406. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24407. cli.enable_server_certificate_verification(false);
  24408. cli.set_connection_timeout(30);
  24409. auto res = cli.Get("/test");
  24410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24411. ASSERT_EQ(StatusCode::OK_200, res->status);
  24412. }
  24413. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24414. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24415. // keep-alive SSL session, which reads through that config in
  24416. // mbedtls_ssl_close_notify.
  24417. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24419. ASSERT_TRUE(svr.is_valid());
  24420. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24421. res.set_content("test", "text/plain");
  24422. });
  24423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24424. auto se = detail::scope_exit([&] {
  24425. svr.stop();
  24426. t.join();
  24427. ASSERT_FALSE(svr.is_running());
  24428. });
  24429. svr.wait_until_ready();
  24430. {
  24431. SSLClient cli(HOST, PORT);
  24432. cli.enable_server_certificate_verification(false);
  24433. cli.set_keep_alive(true);
  24434. auto res = cli.Get("/test");
  24435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24436. ASSERT_EQ(StatusCode::OK_200, res->status);
  24437. // cli is destructed here with the keep-alive SSL session still open.
  24438. }
  24439. }
  24440. #endif
  24441. // WebSocket Tests
  24442. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24443. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24444. // defining the meaning of these bits has been negotiated.
  24445. auto make_frame = [](uint8_t first_byte) {
  24446. std::string frame;
  24447. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24448. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24449. frame += "Hello";
  24450. return frame;
  24451. };
  24452. // RSV1 set (0x40)
  24453. {
  24454. detail::BufferStream strm;
  24455. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24456. ws::Opcode opcode;
  24457. std::string payload;
  24458. bool fin;
  24459. EXPECT_EQ(
  24460. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24461. ws::impl::FrameRead::ProtocolError);
  24462. }
  24463. // RSV2 set (0x20)
  24464. {
  24465. detail::BufferStream strm;
  24466. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24467. ws::Opcode opcode;
  24468. std::string payload;
  24469. bool fin;
  24470. EXPECT_EQ(
  24471. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24472. ws::impl::FrameRead::ProtocolError);
  24473. }
  24474. // RSV3 set (0x10)
  24475. {
  24476. detail::BufferStream strm;
  24477. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24478. ws::Opcode opcode;
  24479. std::string payload;
  24480. bool fin;
  24481. EXPECT_EQ(
  24482. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24483. ws::impl::FrameRead::ProtocolError);
  24484. }
  24485. // No RSV bits set - should succeed
  24486. {
  24487. detail::BufferStream strm;
  24488. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24489. ws::Opcode opcode;
  24490. std::string payload;
  24491. bool fin;
  24492. EXPECT_EQ(
  24493. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24494. ws::impl::FrameRead::Ok);
  24495. EXPECT_EQ(ws::Opcode::Text, opcode);
  24496. EXPECT_EQ("Hello", payload);
  24497. EXPECT_TRUE(fin);
  24498. }
  24499. }
  24500. TEST(WebSocketTest, ControlFrameValidation) {
  24501. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24502. // payload length <= 125.
  24503. // Ping with FIN=0 - must be rejected
  24504. {
  24505. detail::BufferStream strm;
  24506. std::string frame;
  24507. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24508. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24509. strm.write(frame.data(), frame.size());
  24510. ws::Opcode opcode;
  24511. std::string payload;
  24512. bool fin;
  24513. EXPECT_EQ(
  24514. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24515. ws::impl::FrameRead::ProtocolError);
  24516. }
  24517. // Close with FIN=0 - must be rejected
  24518. {
  24519. detail::BufferStream strm;
  24520. std::string frame;
  24521. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24522. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24523. strm.write(frame.data(), frame.size());
  24524. ws::Opcode opcode;
  24525. std::string payload;
  24526. bool fin;
  24527. EXPECT_EQ(
  24528. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24529. ws::impl::FrameRead::ProtocolError);
  24530. }
  24531. // Ping with payload_len=126 (extended length) - must be rejected
  24532. {
  24533. detail::BufferStream strm;
  24534. std::string frame;
  24535. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24536. frame += static_cast<char>(126); // payload_len=126 (>125)
  24537. frame += static_cast<char>(0x00); // extended length high byte
  24538. frame += static_cast<char>(126); // extended length low byte
  24539. frame += std::string(126, 'x');
  24540. strm.write(frame.data(), frame.size());
  24541. ws::Opcode opcode;
  24542. std::string payload;
  24543. bool fin;
  24544. EXPECT_EQ(
  24545. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24546. ws::impl::FrameRead::ProtocolError);
  24547. }
  24548. // Ping with FIN=1 and payload_len=125 - should succeed
  24549. {
  24550. detail::BufferStream strm;
  24551. std::string frame;
  24552. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24553. frame += static_cast<char>(125); // payload_len=125
  24554. frame += std::string(125, 'x');
  24555. strm.write(frame.data(), frame.size());
  24556. ws::Opcode opcode;
  24557. std::string payload;
  24558. bool fin;
  24559. EXPECT_EQ(
  24560. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24561. ws::impl::FrameRead::Ok);
  24562. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24563. EXPECT_EQ(125u, payload.size());
  24564. EXPECT_TRUE(fin);
  24565. }
  24566. }
  24567. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24568. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24569. // length MUST be 0.
  24570. // MSB set - must be rejected
  24571. {
  24572. detail::BufferStream strm;
  24573. std::string frame;
  24574. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24575. frame += static_cast<char>(127); // 64-bit extended length
  24576. frame += static_cast<char>(0x80); // MSB set (invalid)
  24577. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24578. strm.write(frame.data(), frame.size());
  24579. ws::Opcode opcode;
  24580. std::string payload;
  24581. bool fin;
  24582. EXPECT_EQ(
  24583. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24584. ws::impl::FrameRead::ProtocolError);
  24585. }
  24586. // MSB clear - should pass length parsing (will be rejected by max_len,
  24587. // but that's a different check; use a small length to verify)
  24588. {
  24589. detail::BufferStream strm;
  24590. std::string frame;
  24591. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24592. frame += static_cast<char>(127); // 64-bit extended length
  24593. frame += std::string(7, '\0'); // high bytes = 0
  24594. frame += static_cast<char>(0x03); // length = 3
  24595. frame += "abc";
  24596. strm.write(frame.data(), frame.size());
  24597. ws::Opcode opcode;
  24598. std::string payload;
  24599. bool fin;
  24600. EXPECT_EQ(
  24601. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24602. ws::impl::FrameRead::Ok);
  24603. EXPECT_EQ(ws::Opcode::Text, opcode);
  24604. EXPECT_EQ("abc", payload);
  24605. }
  24606. }
  24607. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24608. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24609. // Valid UTF-8
  24610. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24611. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24612. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24613. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24614. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24615. // Invalid UTF-8
  24616. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24617. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24618. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24619. EXPECT_FALSE(
  24620. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24621. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24622. }
  24623. TEST(WebSocketTest, ConnectAndDisconnect) {
  24624. Server svr;
  24625. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24626. std::string msg;
  24627. while (ws.read(msg)) {}
  24628. });
  24629. auto port = svr.bind_to_any_port(HOST);
  24630. std::thread t([&]() { svr.listen_after_bind(); });
  24631. svr.wait_until_ready();
  24632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24633. auto res = client.connect();
  24634. ASSERT_TRUE(res);
  24635. EXPECT_EQ(Error::Success, res.error());
  24636. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24637. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24638. EXPECT_TRUE(client.is_open());
  24639. client.close();
  24640. EXPECT_FALSE(client.is_open());
  24641. svr.stop();
  24642. t.join();
  24643. }
  24644. TEST(WebSocketTest, ValidURL) {
  24645. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24646. EXPECT_TRUE(ws1.is_valid());
  24647. ws::WebSocketClient ws2("ws://example.com/path");
  24648. EXPECT_TRUE(ws2.is_valid());
  24649. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24650. EXPECT_TRUE(ws3.is_valid());
  24651. #ifdef CPPHTTPLIB_SSL_ENABLED
  24652. ws::WebSocketClient wss1("wss://example.com/path");
  24653. EXPECT_TRUE(wss1.is_valid());
  24654. ws::WebSocketClient wss2("wss://example.com:443/path");
  24655. EXPECT_TRUE(wss2.is_valid());
  24656. #endif
  24657. }
  24658. TEST(WebSocketTest, InvalidURL) {
  24659. // No scheme
  24660. ws::WebSocketClient ws1("localhost:8080/path");
  24661. EXPECT_FALSE(ws1.is_valid());
  24662. // No path
  24663. ws::WebSocketClient ws2("ws://localhost:8080");
  24664. EXPECT_FALSE(ws2.is_valid());
  24665. // Empty string
  24666. ws::WebSocketClient ws3("");
  24667. EXPECT_FALSE(ws3.is_valid());
  24668. // Missing host
  24669. ws::WebSocketClient ws4("ws://:8080/path");
  24670. EXPECT_FALSE(ws4.is_valid());
  24671. // Port number overflow — should not crash
  24672. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24673. EXPECT_FALSE(ws5.is_valid());
  24674. // Port out of range
  24675. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24676. EXPECT_FALSE(ws6.is_valid());
  24677. }
  24678. TEST(WebSocketTest, UnsupportedScheme) {
  24679. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24680. ws::WebSocketClient ws1("http://localhost:8080/path");
  24681. EXPECT_FALSE(ws1.is_valid());
  24682. ws::WebSocketClient ws2("https://localhost:8080/path");
  24683. EXPECT_FALSE(ws2.is_valid());
  24684. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24685. EXPECT_FALSE(ws3.is_valid());
  24686. #else
  24687. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24688. std::invalid_argument);
  24689. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24690. std::invalid_argument);
  24691. #endif
  24692. }
  24693. TEST(WebSocketTest, ConnectWhenInvalid) {
  24694. ws::WebSocketClient ws("not a valid url");
  24695. EXPECT_FALSE(ws.is_valid());
  24696. auto res = ws.connect();
  24697. EXPECT_FALSE(res);
  24698. EXPECT_EQ(Error::Connection, res.error());
  24699. EXPECT_EQ(-1, res.status());
  24700. }
  24701. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24702. // Grab a port that is free, then close it again so nothing listens there
  24703. Server svr;
  24704. auto port = svr.bind_to_any_port(HOST);
  24705. svr.stop();
  24706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24707. auto res = client.connect();
  24708. ASSERT_FALSE(res);
  24709. EXPECT_EQ(Error::Connection, res.error());
  24710. EXPECT_EQ(-1, res.status());
  24711. }
  24712. TEST(WebSocketTest, DefaultPort) {
  24713. ws::WebSocketClient ws1("ws://example.com/path");
  24714. EXPECT_TRUE(ws1.is_valid());
  24715. // ws:// defaults to port 80 (verified by successful parse)
  24716. #ifdef CPPHTTPLIB_SSL_ENABLED
  24717. ws::WebSocketClient ws2("wss://example.com/path");
  24718. EXPECT_TRUE(ws2.is_valid());
  24719. // wss:// defaults to port 443 (verified by successful parse)
  24720. #endif
  24721. }
  24722. TEST(WebSocketTest, IPv6LiteralAddress) {
  24723. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24724. EXPECT_TRUE(ws1.is_valid());
  24725. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24726. EXPECT_TRUE(ws2.is_valid());
  24727. }
  24728. TEST(WebSocketTest, ComplexPath) {
  24729. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24730. EXPECT_TRUE(ws1.is_valid());
  24731. ws::WebSocketClient ws2("ws://localhost:8080/");
  24732. EXPECT_TRUE(ws2.is_valid());
  24733. }
  24734. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24735. Server svr;
  24736. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24737. std::string msg;
  24738. while (ws.read(msg)) {}
  24739. });
  24740. auto port = svr.bind_to_any_port(HOST);
  24741. std::thread t([&]() { svr.listen_after_bind(); });
  24742. svr.wait_until_ready();
  24743. auto another_host = "example.com";
  24744. auto wrong_ip = "192.0.2.1";
  24745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24746. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24747. ASSERT_TRUE(client.connect());
  24748. EXPECT_TRUE(client.is_open());
  24749. client.close();
  24750. svr.stop();
  24751. t.join();
  24752. }
  24753. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24754. Server svr;
  24755. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24756. std::string msg;
  24757. while (ws.read(msg)) {}
  24758. });
  24759. auto port = svr.bind_to_any_port(HOST);
  24760. std::thread t([&]() { svr.listen_after_bind(); });
  24761. svr.wait_until_ready();
  24762. auto wrong_ip = "192.0.2.1";
  24763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24764. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24765. client.set_connection_timeout(1);
  24766. client.set_read_timeout(1);
  24767. client.set_write_timeout(1);
  24768. EXPECT_FALSE(client.connect());
  24769. EXPECT_FALSE(client.is_open());
  24770. svr.stop();
  24771. t.join();
  24772. }
  24773. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24774. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24775. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24776. // (RFC 6761) is only a map key and the Host header value.
  24777. auto host = "target.invalid";
  24778. Server svr;
  24779. std::string received_host;
  24780. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24781. received_host = req.get_header_value("Host");
  24782. std::string msg;
  24783. while (ws.read(msg)) {}
  24784. });
  24785. auto port = svr.bind_to_any_port(HOST);
  24786. std::thread t([&]() { svr.listen_after_bind(); });
  24787. // ASSERT_* below returns from the test body, which would leave t joinable
  24788. // and make ~thread call std::terminate.
  24789. auto se = detail::scope_exit([&] {
  24790. svr.stop();
  24791. if (t.joinable()) { t.join(); }
  24792. });
  24793. svr.wait_until_ready();
  24794. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24795. std::to_string(port) + "/ws");
  24796. client.set_direct_hostname_addr_map({{host, HOST}});
  24797. ASSERT_TRUE(client.connect());
  24798. EXPECT_TRUE(client.is_open());
  24799. client.close();
  24800. svr.stop();
  24801. t.join();
  24802. // The mapping only redirects the connection; the identity stays host_.
  24803. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24804. }
  24805. class WebSocketIntegrationTest : public ::testing::Test {
  24806. protected:
  24807. void SetUp() override {
  24808. server_ = httplib::detail::make_unique<Server>();
  24809. setup_server();
  24810. start_server();
  24811. }
  24812. void TearDown() override {
  24813. server_->stop();
  24814. if (server_thread_.joinable()) { server_thread_.join(); }
  24815. }
  24816. void setup_server() {
  24817. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24818. std::string msg;
  24819. ws::ReadResult ret;
  24820. while ((ret = ws.read(msg))) {
  24821. if (ret == ws::Binary) {
  24822. ws.send(msg.data(), msg.size());
  24823. } else {
  24824. ws.send(msg);
  24825. }
  24826. }
  24827. });
  24828. server_->WebSocket("/ws-echo-string",
  24829. [](const Request &, ws::WebSocket &ws) {
  24830. std::string msg;
  24831. while (ws.read(msg)) {
  24832. ws.send("echo: " + msg);
  24833. }
  24834. });
  24835. server_->WebSocket(
  24836. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24837. // Echo back request metadata
  24838. ws.send("path:" + req.path);
  24839. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24840. std::string msg;
  24841. while (ws.read(msg)) {}
  24842. });
  24843. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24844. std::string msg;
  24845. ws.read(msg); // wait for a message
  24846. ws.close();
  24847. });
  24848. server_->WebSocket("/ws-close-status",
  24849. [](const Request &, ws::WebSocket &ws) {
  24850. std::string msg;
  24851. ws.read(msg); // wait for a message
  24852. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24853. });
  24854. server_->WebSocket(
  24855. "/ws-subprotocol",
  24856. [](const Request &, ws::WebSocket &ws) {
  24857. std::string msg;
  24858. while (ws.read(msg)) {
  24859. ws.send(msg);
  24860. }
  24861. },
  24862. [](const std::vector<std::string> &protocols) -> std::string {
  24863. for (const auto &p : protocols) {
  24864. if (p == "graphql-ws") { return p; }
  24865. }
  24866. return "";
  24867. });
  24868. server_->WebSocket(
  24869. "/ws-subprotocol-unoffered",
  24870. [](const Request &, ws::WebSocket &ws) {
  24871. std::string msg;
  24872. while (ws.read(msg)) {
  24873. ws.send(msg);
  24874. }
  24875. },
  24876. [](const std::vector<std::string> &) -> std::string {
  24877. return "admin";
  24878. });
  24879. }
  24880. void start_server() {
  24881. port_ = server_->bind_to_any_port(HOST);
  24882. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24883. server_->wait_until_ready();
  24884. }
  24885. std::unique_ptr<Server> server_;
  24886. std::thread server_thread_;
  24887. int port_ = 0;
  24888. };
  24889. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24891. "/ws-echo");
  24892. ASSERT_TRUE(client.connect());
  24893. ASSERT_TRUE(client.is_open());
  24894. ASSERT_TRUE(client.send("Hello WebSocket"));
  24895. std::string msg;
  24896. EXPECT_EQ(ws::Text, client.read(msg));
  24897. EXPECT_EQ("Hello WebSocket", msg);
  24898. client.close();
  24899. }
  24900. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24902. "/ws-echo");
  24903. ASSERT_TRUE(client.connect());
  24904. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24905. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24906. std::string msg;
  24907. EXPECT_EQ(ws::Binary, client.read(msg));
  24908. EXPECT_EQ(binary_data, msg);
  24909. client.close();
  24910. }
  24911. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24913. "/ws-echo");
  24914. ASSERT_TRUE(client.connect());
  24915. for (int i = 0; i < 10; i++) {
  24916. auto text = "message " + std::to_string(i);
  24917. ASSERT_TRUE(client.send(text));
  24918. std::string msg;
  24919. ASSERT_TRUE(client.read(msg));
  24920. EXPECT_EQ(text, msg);
  24921. }
  24922. client.close();
  24923. }
  24924. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24926. "/ws-close");
  24927. ASSERT_TRUE(client.connect());
  24928. // Send a message to trigger the server to close
  24929. ASSERT_TRUE(client.send("trigger close"));
  24930. // The server will close, so read should return false
  24931. std::string msg;
  24932. EXPECT_FALSE(client.read(msg));
  24933. EXPECT_FALSE(client.is_open());
  24934. EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
  24935. EXPECT_EQ("", client.close_reason());
  24936. }
  24937. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24939. "/ws-echo");
  24940. ASSERT_TRUE(client.connect());
  24941. // 128KB message
  24942. std::string large_data(128 * 1024, 'X');
  24943. ASSERT_TRUE(client.send(large_data));
  24944. std::string msg;
  24945. ASSERT_TRUE(client.read(msg));
  24946. EXPECT_EQ(large_data, msg);
  24947. client.close();
  24948. }
  24949. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24951. "/ws-echo");
  24952. ASSERT_TRUE(client.connect());
  24953. const int num_threads = 4;
  24954. std::vector<std::thread> threads;
  24955. std::atomic<int> send_count{0};
  24956. for (int t = 0; t < num_threads; t++) {
  24957. threads.emplace_back([&client, &send_count, t]() {
  24958. for (int i = 0; i < 5; i++) {
  24959. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24960. if (client.send(text)) { send_count++; }
  24961. }
  24962. });
  24963. }
  24964. for (auto &th : threads) {
  24965. th.join();
  24966. }
  24967. int received = 0;
  24968. std::string msg;
  24969. while (received < send_count.load()) {
  24970. if (!client.read(msg)) { break; }
  24971. received++;
  24972. }
  24973. EXPECT_EQ(send_count.load(), received);
  24974. client.close();
  24975. }
  24976. TEST_F(WebSocketIntegrationTest, ReadString) {
  24977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24978. "/ws-echo-string");
  24979. ASSERT_TRUE(client.connect());
  24980. ASSERT_TRUE(client.send("hello"));
  24981. std::string msg;
  24982. ASSERT_TRUE(client.read(msg));
  24983. EXPECT_EQ("echo: hello", msg);
  24984. ASSERT_TRUE(client.send("world"));
  24985. ASSERT_TRUE(client.read(msg));
  24986. EXPECT_EQ("echo: world", msg);
  24987. client.close();
  24988. }
  24989. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24990. Headers headers = {{"X-Test-Header", "test-value"}};
  24991. ws::WebSocketClient client(
  24992. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24993. ASSERT_TRUE(client.connect());
  24994. std::string msg;
  24995. ASSERT_TRUE(client.read(msg));
  24996. EXPECT_EQ("path:/ws-request-info", msg);
  24997. ASSERT_TRUE(client.read(msg));
  24998. EXPECT_EQ("header:test-value", msg);
  24999. client.close();
  25000. }
  25001. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  25002. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25003. "/ws-echo");
  25004. client.set_read_timeout(1, 0); // 1 second
  25005. ASSERT_TRUE(client.connect());
  25006. // Don't send anything — server echo handler waits for a message, so read()
  25007. // should time out. The connection survives it: nothing was consumed.
  25008. std::string msg;
  25009. EXPECT_EQ(client.read(msg), ws::Timeout);
  25010. EXPECT_TRUE(client.is_open());
  25011. // And it is still usable afterwards.
  25012. EXPECT_TRUE(client.send("after timeout"));
  25013. EXPECT_EQ(client.read(msg), ws::Text);
  25014. EXPECT_EQ(msg, "after timeout");
  25015. }
  25016. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  25017. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25018. "/ws-echo");
  25019. client.set_read_timeout(1, 0);
  25020. ASSERT_TRUE(client.connect());
  25021. ASSERT_TRUE(client.send("first"));
  25022. std::string msg;
  25023. ASSERT_EQ(client.read(msg), ws::Text);
  25024. ASSERT_EQ(msg, "first");
  25025. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  25026. // not be used with a read timeout: it would reprocess the previous message.
  25027. EXPECT_EQ(client.read(msg), ws::Timeout);
  25028. EXPECT_EQ(msg, "first");
  25029. }
  25030. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  25031. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25032. "/ws-echo");
  25033. ASSERT_TRUE(client.connect());
  25034. // Setting it once the connection is open reaches the live stream, not just
  25035. // the seed for the next connect().
  25036. client.set_read_timeout(1, 0);
  25037. std::string msg;
  25038. EXPECT_EQ(client.read(msg), ws::Timeout);
  25039. EXPECT_TRUE(client.is_open());
  25040. }
  25041. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  25042. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25043. "/nonexistent");
  25044. auto res = client.connect();
  25045. EXPECT_FALSE(res);
  25046. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25047. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  25048. EXPECT_FALSE(client.is_open());
  25049. }
  25050. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  25051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25052. "/ws-echo");
  25053. ASSERT_TRUE(client.connect());
  25054. ASSERT_TRUE(client.send(""));
  25055. std::string msg;
  25056. EXPECT_EQ(ws::Text, client.read(msg));
  25057. EXPECT_EQ("", msg);
  25058. client.close();
  25059. }
  25060. TEST_F(WebSocketIntegrationTest, Reconnect) {
  25061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25062. "/ws-echo");
  25063. // First connection
  25064. ASSERT_TRUE(client.connect());
  25065. ASSERT_TRUE(client.send("first"));
  25066. std::string msg;
  25067. ASSERT_TRUE(client.read(msg));
  25068. EXPECT_EQ("first", msg);
  25069. client.close();
  25070. EXPECT_FALSE(client.is_open());
  25071. // Reconnect using the same client object
  25072. ASSERT_TRUE(client.connect());
  25073. ASSERT_TRUE(client.is_open());
  25074. ASSERT_TRUE(client.send("second"));
  25075. ASSERT_TRUE(client.read(msg));
  25076. EXPECT_EQ("second", msg);
  25077. client.close();
  25078. }
  25079. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  25080. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25081. "/ws-close-status");
  25082. ASSERT_TRUE(client.connect());
  25083. // Trigger the server to close with GoingAway status
  25084. ASSERT_TRUE(client.send("trigger"));
  25085. // read() should return false after receiving the close frame
  25086. std::string msg;
  25087. EXPECT_FALSE(client.read(msg));
  25088. EXPECT_FALSE(client.is_open());
  25089. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  25090. EXPECT_EQ("shutting down", client.close_reason());
  25091. // A copy, so it outlives a reconnect that replaces the connection
  25092. static_assert(
  25093. std::is_same<decltype(client.close_reason()), std::string>::value, "");
  25094. }
  25095. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  25096. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25097. "/ws-echo");
  25098. EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
  25099. ASSERT_TRUE(client.connect());
  25100. client.close(ws::CloseStatus::GoingAway, "client leaving");
  25101. EXPECT_FALSE(client.is_open());
  25102. // The server echoes the Close it receives
  25103. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  25104. EXPECT_EQ("client leaving", client.close_reason());
  25105. }
  25106. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  25107. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  25108. ws::WebSocketClient client(
  25109. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25110. ASSERT_TRUE(client.connect());
  25111. // Server should have selected graphql-ws
  25112. EXPECT_EQ("graphql-ws", client.subprotocol());
  25113. client.close();
  25114. }
  25115. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  25116. Headers headers;
  25117. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  25118. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  25119. ws::WebSocketClient client(
  25120. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25121. ASSERT_TRUE(client.connect());
  25122. // The offer on the second field line counts too, so graphql-ws is selected
  25123. EXPECT_EQ("graphql-ws", client.subprotocol());
  25124. client.close();
  25125. }
  25126. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  25127. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  25128. ws::WebSocketClient client(
  25129. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25130. ASSERT_TRUE(client.connect());
  25131. // Server should not have selected any subprotocol
  25132. EXPECT_TRUE(client.subprotocol().empty());
  25133. client.close();
  25134. }
  25135. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  25136. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25137. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25138. "/ws-subprotocol-unoffered",
  25139. headers);
  25140. ASSERT_TRUE(client.connect());
  25141. EXPECT_TRUE(client.subprotocol().empty());
  25142. client.close();
  25143. }
  25144. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  25145. // Connect without requesting any subprotocol
  25146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25147. "/ws-subprotocol");
  25148. ASSERT_TRUE(client.connect());
  25149. EXPECT_TRUE(client.subprotocol().empty());
  25150. client.close();
  25151. }
  25152. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  25153. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25154. "/ws-echo");
  25155. client.set_tcp_nodelay(true);
  25156. client.set_connection_timeout(3, 0);
  25157. bool socket_options_called = false;
  25158. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  25159. ASSERT_TRUE(client.connect());
  25160. ASSERT_TRUE(client.is_open());
  25161. EXPECT_TRUE(socket_options_called);
  25162. ASSERT_TRUE(client.send("hello"));
  25163. std::string msg;
  25164. auto result = client.read(msg);
  25165. EXPECT_EQ(result, ws::ReadResult::Text);
  25166. EXPECT_EQ(msg, "hello");
  25167. client.close();
  25168. }
  25169. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  25170. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25171. "/ws-echo");
  25172. client.set_connection_timeout(std::chrono::seconds(3));
  25173. client.set_write_timeout(std::chrono::seconds(3));
  25174. // A sub-second remainder exercises the seconds/microseconds split.
  25175. client.set_read_timeout(std::chrono::milliseconds(1500));
  25176. ASSERT_TRUE(client.connect());
  25177. auto start = std::chrono::steady_clock::now();
  25178. std::string msg;
  25179. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  25180. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  25181. std::chrono::steady_clock::now() - start)
  25182. .count();
  25183. // Above 1s so that dropping the microseconds half of the split fails here.
  25184. // Ignoring the setter altogether would not reach this line at all: a client
  25185. // waits forever by default.
  25186. EXPECT_GE(elapsed, 1400);
  25187. EXPECT_LT(elapsed, 30000);
  25188. }
  25189. #ifndef _WIN32
  25190. // A send() that times out after part of the data went out returns the count
  25191. // written so far. Every byte of the frame must still be sent, or the peer reads
  25192. // the next frame's header and payload as the rest of this one.
  25193. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  25194. signal(SIGPIPE, SIG_IGN);
  25195. const std::string large(4 * 1024 * 1024, 'A');
  25196. std::atomic<bool> large_sent{false};
  25197. std::atomic<bool> small_sent{false};
  25198. Server svr;
  25199. svr.set_write_timeout(0, 500000);
  25200. svr.set_socket_options([](socket_t sock) {
  25201. int size = 8192;
  25202. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25203. reinterpret_cast<const char *>(&size), sizeof(size));
  25204. });
  25205. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25206. large_sent = ws.send(large.data(), large.size());
  25207. small_sent = ws.send("after");
  25208. std::string msg;
  25209. while (ws.read(msg)) {}
  25210. });
  25211. auto port = svr.bind_to_any_port(HOST);
  25212. std::thread t([&]() { svr.listen_after_bind(); });
  25213. auto se = detail::scope_exit([&] {
  25214. svr.stop();
  25215. t.join();
  25216. });
  25217. svr.wait_until_ready();
  25218. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25219. std::to_string(port) + "/ws");
  25220. client.set_read_timeout(5);
  25221. client.set_socket_options([](socket_t sock) {
  25222. int size = 8192;
  25223. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25224. reinterpret_cast<const char *>(&size), sizeof(size));
  25225. });
  25226. ASSERT_TRUE(client.connect());
  25227. // Outlast the server's write timeout, then drain.
  25228. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25229. std::string msg;
  25230. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25231. EXPECT_TRUE(msg == large);
  25232. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25233. EXPECT_EQ("after", msg);
  25234. EXPECT_TRUE(large_sent);
  25235. EXPECT_TRUE(small_sent);
  25236. client.close();
  25237. }
  25238. // A send() that fails partway leaves a frame on the wire whose header announces
  25239. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25240. // as the rest of it and a later payload's bytes as a frame of their own.
  25241. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25242. signal(SIGPIPE, SIG_IGN);
  25243. const std::string large(4 * 1024 * 1024, 'A');
  25244. std::atomic<bool> large_sent{true};
  25245. std::atomic<bool> open_after_failure{true};
  25246. std::atomic<bool> handler_done{false};
  25247. Server svr;
  25248. svr.set_write_timeout(0, 200000);
  25249. svr.set_socket_options([](socket_t sock) {
  25250. int size = 8192;
  25251. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25252. reinterpret_cast<const char *>(&size), sizeof(size));
  25253. });
  25254. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25255. large_sent = ws.send(large.data(), large.size());
  25256. open_after_failure = ws.is_open();
  25257. handler_done = true;
  25258. });
  25259. auto port = svr.bind_to_any_port(HOST);
  25260. std::thread t([&]() { svr.listen_after_bind(); });
  25261. auto se = detail::scope_exit([&] {
  25262. svr.stop();
  25263. t.join();
  25264. });
  25265. svr.wait_until_ready();
  25266. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25267. std::to_string(port) + "/ws");
  25268. client.set_socket_options([](socket_t sock) {
  25269. int size = 8192;
  25270. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25271. reinterpret_cast<const char *>(&size), sizeof(size));
  25272. });
  25273. ASSERT_TRUE(client.connect());
  25274. // Read nothing, so the server's write times out partway through the frame.
  25275. for (int i = 0; i < 100 && !handler_done; i++) {
  25276. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25277. }
  25278. ASSERT_TRUE(handler_done);
  25279. ASSERT_FALSE(large_sent);
  25280. EXPECT_FALSE(open_after_failure);
  25281. client.close();
  25282. }
  25283. #endif
  25284. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25285. Server svr;
  25286. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25287. if (!req.has_header("Authorization")) {
  25288. res.status = StatusCode::Unauthorized_401;
  25289. res.set_content("Unauthorized", "text/plain");
  25290. return Server::HandlerResponse::Handled;
  25291. }
  25292. return Server::HandlerResponse::Unhandled;
  25293. });
  25294. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25295. std::string msg;
  25296. while (ws.read(msg)) {
  25297. ws.send(msg);
  25298. }
  25299. });
  25300. auto port = svr.bind_to_any_port("localhost");
  25301. std::thread t([&]() { svr.listen_after_bind(); });
  25302. svr.wait_until_ready();
  25303. // Without Authorization header - should be rejected before upgrade
  25304. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25305. EXPECT_FALSE(client1.connect());
  25306. // The rejection is framed like any other HTTP response
  25307. {
  25308. Client cli("localhost", port);
  25309. Headers headers = {{"Upgrade", "websocket"},
  25310. {"Connection", "Upgrade"},
  25311. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25312. {"Sec-WebSocket-Version", "13"}};
  25313. auto res = cli.Get("/ws", headers);
  25314. ASSERT_TRUE(res);
  25315. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25316. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25317. EXPECT_EQ("Unauthorized", res->body);
  25318. }
  25319. // With Authorization header - should succeed
  25320. Headers headers = {{"Authorization", "Bearer token123"}};
  25321. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25322. headers);
  25323. ASSERT_TRUE(client2.connect());
  25324. ASSERT_TRUE(client2.send("hello"));
  25325. std::string msg;
  25326. ASSERT_TRUE(client2.read(msg));
  25327. EXPECT_EQ("hello", msg);
  25328. client2.close();
  25329. svr.stop();
  25330. t.join();
  25331. }
  25332. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25333. Server svr;
  25334. std::atomic<int> pre_routing_calls{0};
  25335. std::atomic<int> pre_request_calls{0};
  25336. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25337. pre_routing_calls++;
  25338. if (req.path == "/handled") {
  25339. res.set_content("handled", "text/plain");
  25340. return Server::HandlerResponse::Handled;
  25341. }
  25342. return Server::HandlerResponse::Unhandled;
  25343. });
  25344. svr.set_pre_request_handler([&](const Request &, Response &) {
  25345. pre_request_calls++;
  25346. return Server::HandlerResponse::Unhandled;
  25347. });
  25348. svr.Get("/http", [](const Request &, Response &res) {
  25349. res.set_content("http", "text/plain");
  25350. });
  25351. svr.WebSocket("/ws",
  25352. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25353. auto port = svr.bind_to_any_port("localhost");
  25354. std::thread t([&]() { svr.listen_after_bind(); });
  25355. auto se = detail::scope_exit([&] {
  25356. svr.stop();
  25357. t.join();
  25358. });
  25359. svr.wait_until_ready();
  25360. Headers upgrade = {{"Upgrade", "websocket"},
  25361. {"Connection", "Upgrade"},
  25362. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25363. {"Sec-WebSocket-Version", "13"}};
  25364. auto get = [&](const char *path) {
  25365. pre_routing_calls = 0;
  25366. return Client("localhost", port).Get(path, upgrade);
  25367. };
  25368. // No WebSocket route, but an HTTP one
  25369. auto res = get("/http");
  25370. ASSERT_TRUE(res);
  25371. EXPECT_EQ(StatusCode::OK_200, res->status);
  25372. EXPECT_EQ("http", res->body);
  25373. EXPECT_EQ(1, pre_routing_calls);
  25374. EXPECT_EQ(1, pre_request_calls);
  25375. // No route at all
  25376. res = get("/none");
  25377. ASSERT_TRUE(res);
  25378. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25379. EXPECT_EQ(1, pre_routing_calls);
  25380. // Answered by the pre-routing handler
  25381. res = get("/handled");
  25382. ASSERT_TRUE(res);
  25383. EXPECT_EQ(StatusCode::OK_200, res->status);
  25384. EXPECT_EQ("handled", res->body);
  25385. EXPECT_EQ(1, pre_routing_calls);
  25386. // A WebSocket route
  25387. pre_routing_calls = 0;
  25388. pre_request_calls = 0;
  25389. {
  25390. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25391. "/ws");
  25392. ASSERT_TRUE(client.connect());
  25393. std::string msg;
  25394. ASSERT_TRUE(client.read(msg));
  25395. EXPECT_EQ("ws", msg);
  25396. client.close();
  25397. }
  25398. EXPECT_EQ(1, pre_routing_calls);
  25399. EXPECT_EQ(1, pre_request_calls);
  25400. }
  25401. // An upgrade request answered by a hook leaves its body unread, so that body
  25402. // must not be served as the next request on the connection.
  25403. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25404. Server svr;
  25405. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25406. if (req.path == "/pre-routing") {
  25407. res.set_content("pre-routing", "text/plain");
  25408. return Server::HandlerResponse::Handled;
  25409. }
  25410. return Server::HandlerResponse::Unhandled;
  25411. });
  25412. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25413. if (req.matched_route == "/pre-request") {
  25414. res.set_content("pre-request", "text/plain");
  25415. return Server::HandlerResponse::Handled;
  25416. }
  25417. return Server::HandlerResponse::Unhandled;
  25418. });
  25419. svr.Get("/smuggled", [](const Request &, Response &res) {
  25420. res.set_content("smuggled", "text/plain");
  25421. });
  25422. svr.WebSocket("/pre-request",
  25423. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25424. auto port = svr.bind_to_any_port(HOST);
  25425. std::thread t([&]() { svr.listen_after_bind(); });
  25426. auto se = detail::scope_exit([&] {
  25427. svr.stop();
  25428. t.join();
  25429. });
  25430. svr.wait_until_ready();
  25431. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25432. for (auto path : {"/pre-routing", "/pre-request"}) {
  25433. std::string req = std::string("GET ") + path +
  25434. " HTTP/1.1\r\n"
  25435. "Host: localhost\r\n"
  25436. "Upgrade: websocket\r\n"
  25437. "Connection: Upgrade\r\n"
  25438. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25439. "Sec-WebSocket-Version: 13\r\n"
  25440. "Content-Length: " +
  25441. std::to_string(body.size()) + "\r\n\r\n" + body;
  25442. std::string res;
  25443. ASSERT_TRUE(send_request(5, req, &res, port));
  25444. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25445. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25446. // Only one response, and the body was not served as a request
  25447. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25448. }
  25449. }
  25450. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25451. Server svr;
  25452. std::atomic<int> pre_request_calls{0};
  25453. std::atomic<bool> route_matched{false};
  25454. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25455. pre_request_calls++;
  25456. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25457. if (req.get_header_value("Authorization") != "Bearer token123") {
  25458. res.status = StatusCode::Unauthorized_401;
  25459. res.set_content("Unauthorized", "text/plain");
  25460. return Server::HandlerResponse::Handled;
  25461. }
  25462. return Server::HandlerResponse::Unhandled;
  25463. });
  25464. std::atomic<bool> handler_called{false};
  25465. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25466. handler_called = true;
  25467. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25468. });
  25469. auto port = svr.bind_to_any_port("localhost");
  25470. std::thread t([&]() { svr.listen_after_bind(); });
  25471. svr.wait_until_ready();
  25472. // Without Authorization header - should be rejected before upgrade
  25473. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25474. "/ws/1");
  25475. EXPECT_FALSE(client1.connect());
  25476. EXPECT_FALSE(handler_called);
  25477. EXPECT_EQ(1, pre_request_calls);
  25478. EXPECT_TRUE(route_matched);
  25479. // The rejection is an ordinary HTTP response, not a protocol switch
  25480. {
  25481. Client cli("localhost", port);
  25482. Headers headers = {{"Upgrade", "websocket"},
  25483. {"Connection", "Upgrade"},
  25484. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25485. {"Sec-WebSocket-Version", "13"}};
  25486. auto res = cli.Get("/ws/1", headers);
  25487. ASSERT_TRUE(res);
  25488. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25489. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25490. EXPECT_EQ("Unauthorized", res->body);
  25491. }
  25492. EXPECT_FALSE(handler_called);
  25493. // With Authorization header - should succeed
  25494. Headers headers = {{"Authorization", "Bearer token123"}};
  25495. ws::WebSocketClient client2(
  25496. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25497. ASSERT_TRUE(client2.connect());
  25498. std::string msg;
  25499. ASSERT_TRUE(client2.read(msg));
  25500. EXPECT_EQ("/ws/:id 2", msg);
  25501. EXPECT_TRUE(handler_called);
  25502. client2.close();
  25503. svr.stop();
  25504. t.join();
  25505. }
  25506. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25507. static Headers websocket_upgrade_headers() {
  25508. return {{"Upgrade", "websocket"},
  25509. {"Connection", "Upgrade"},
  25510. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25511. {"Sec-WebSocket-Version", "13"},
  25512. {"Sec-WebSocket-Protocol", "chat"}};
  25513. }
  25514. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25515. Server svr;
  25516. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25517. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25518. return Server::HandlerResponse::Unhandled;
  25519. });
  25520. svr.set_pre_request_handler([](const Request &req, Response &) {
  25521. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25522. return Server::HandlerResponse::Unhandled;
  25523. });
  25524. svr.set_exception_handler(
  25525. [](const Request &, Response &res, std::exception_ptr ep) {
  25526. try {
  25527. std::rethrow_exception(ep);
  25528. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25529. });
  25530. auto handler = [](const Request &, ws::WebSocket &) {};
  25531. svr.WebSocket("/pre-routing", handler);
  25532. svr.WebSocket("/pre-request", handler);
  25533. svr.WebSocket("/sub-protocol", handler,
  25534. [](const std::vector<std::string> &) -> std::string {
  25535. throw std::runtime_error("/sub-protocol");
  25536. });
  25537. auto port = svr.bind_to_any_port(HOST);
  25538. ASSERT_GT(port, 0);
  25539. thread t = thread([&] { svr.listen_after_bind(); });
  25540. auto se = detail::scope_exit([&] {
  25541. svr.stop();
  25542. t.join();
  25543. ASSERT_FALSE(svr.is_running());
  25544. });
  25545. svr.wait_until_ready();
  25546. Client cli(HOST, port);
  25547. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25548. auto res = cli.Get(path, websocket_upgrade_headers());
  25549. if (!res) {
  25550. ADD_FAILURE() << path << ": " << to_string(res.error());
  25551. continue;
  25552. }
  25553. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25554. EXPECT_EQ(path, res->body);
  25555. }
  25556. }
  25557. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25558. Server svr;
  25559. svr.set_pre_routing_handler(
  25560. [](const Request &, Response &) -> Server::HandlerResponse {
  25561. throw std::runtime_error("pre-routing");
  25562. });
  25563. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25564. auto port = svr.bind_to_any_port(HOST);
  25565. ASSERT_GT(port, 0);
  25566. thread t = thread([&] { svr.listen_after_bind(); });
  25567. auto se = detail::scope_exit([&] {
  25568. svr.stop();
  25569. t.join();
  25570. ASSERT_FALSE(svr.is_running());
  25571. });
  25572. svr.wait_until_ready();
  25573. Client cli(HOST, port);
  25574. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25575. ASSERT_TRUE(res) << to_string(res.error());
  25576. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25577. }
  25578. #endif
  25579. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25580. Server svr;
  25581. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25582. // A read timeout is how a handler gets control back. Without it, a handler
  25583. // parked in read() can never write on the connection it is reading.
  25584. ws.set_read_timeout(std::chrono::milliseconds(100));
  25585. std::string msg;
  25586. while (ws.is_open()) {
  25587. auto r = ws.read(msg);
  25588. if (r == httplib::ws::Timeout) {
  25589. ws.send("tick");
  25590. continue;
  25591. }
  25592. if (r == httplib::ws::Fail) { break; }
  25593. ws.send(msg);
  25594. }
  25595. });
  25596. auto port = svr.bind_to_any_port("localhost");
  25597. std::thread t([&]() { svr.listen_after_bind(); });
  25598. svr.wait_until_ready();
  25599. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25600. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25601. ASSERT_TRUE(client.connect());
  25602. // The client sends nothing, so anything it receives came out of the
  25603. // handler's timeout path.
  25604. std::string msg;
  25605. ASSERT_EQ(client.read(msg), ws::Text);
  25606. EXPECT_EQ("tick", msg);
  25607. client.close();
  25608. svr.stop();
  25609. t.join();
  25610. }
  25611. // Stream::read may return fewer bytes than asked for. This is that contract at
  25612. // its worst -- one byte per call -- which is what a frame header straddling a
  25613. // read buffer's boundary looks like to the frame parser.
  25614. class WsByteAtATimeStream : public Stream {
  25615. public:
  25616. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25617. bool is_readable() const override { return true; }
  25618. bool wait_readable() const override { return true; }
  25619. bool wait_writable() const override { return true; }
  25620. ssize_t read(char *ptr, size_t size) override {
  25621. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25622. *ptr = data_[pos_++];
  25623. return 1;
  25624. }
  25625. ssize_t write(const char *, size_t size) override {
  25626. return static_cast<ssize_t>(size);
  25627. }
  25628. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25629. ip = "127.0.0.1";
  25630. port = 0;
  25631. }
  25632. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25633. ip = "127.0.0.1";
  25634. port = 0;
  25635. }
  25636. socket_t socket() const override { return INVALID_SOCKET; }
  25637. time_t duration() const override { return 0; }
  25638. private:
  25639. std::string data_;
  25640. size_t pos_ = 0;
  25641. };
  25642. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25643. // The payload uses the 16-bit extended length, so the header, the length
  25644. // and the mask key are all multi-byte fields here. Each used to be read
  25645. // with a single read() call, which fails as soon as one is split. The
  25646. // payload is also a little over one read chunk, so it is read in two.
  25647. std::string body;
  25648. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25649. body += static_cast<char>(i % 251);
  25650. }
  25651. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25652. std::string frame;
  25653. frame += static_cast<char>(0x81); // FIN + Text
  25654. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25655. frame += static_cast<char>(body.size() >> 8);
  25656. frame += static_cast<char>(body.size() & 0xff);
  25657. for (size_t i = 0; i < 4; i++) {
  25658. frame += static_cast<char>(mask[i]);
  25659. }
  25660. for (size_t i = 0; i < body.size(); i++) {
  25661. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25662. }
  25663. WsByteAtATimeStream strm(frame);
  25664. ws::Opcode opcode;
  25665. std::string payload;
  25666. bool fin = false;
  25667. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25668. /*expect_masked=*/true, body.size()),
  25669. ws::impl::FrameRead::Ok);
  25670. EXPECT_TRUE(fin);
  25671. EXPECT_EQ(opcode, ws::Opcode::Text);
  25672. EXPECT_EQ(payload, body);
  25673. }
  25674. // Keeps what is written, counting the writes, and reads it back.
  25675. class WsWriteCountingStream : public Stream {
  25676. public:
  25677. bool is_readable() const override { return true; }
  25678. bool wait_readable() const override { return true; }
  25679. bool wait_writable() const override { return true; }
  25680. ssize_t read(char *ptr, size_t size) override {
  25681. auto n = (std::min)(size, data_.size() - pos_);
  25682. if (n == 0) { return 0; }
  25683. memcpy(ptr, data_.data() + pos_, n);
  25684. pos_ += n;
  25685. return static_cast<ssize_t>(n);
  25686. }
  25687. ssize_t write(const char *ptr, size_t size) override {
  25688. writes++;
  25689. data_.append(ptr, size);
  25690. return static_cast<ssize_t>(size);
  25691. }
  25692. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25693. ip = "127.0.0.1";
  25694. port = 0;
  25695. }
  25696. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25697. ip = "127.0.0.1";
  25698. port = 0;
  25699. }
  25700. socket_t socket() const override { return INVALID_SOCKET; }
  25701. time_t duration() const override { return 0; }
  25702. int writes = 0;
  25703. private:
  25704. std::string data_;
  25705. size_t pos_ = 0;
  25706. };
  25707. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25708. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25709. // masked and not, reads back as written; a payload over one chunk follows
  25710. // its first in more writes.
  25711. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25712. for (auto mask : {false, true}) {
  25713. std::string body(len, '\0');
  25714. for (size_t i = 0; i < len; i++) {
  25715. body[i] = static_cast<char>(i % 251);
  25716. }
  25717. WsWriteCountingStream strm;
  25718. ASSERT_TRUE(detail::write_websocket_frame(
  25719. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25720. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25721. ws::Opcode opcode;
  25722. std::string payload;
  25723. bool fin = false;
  25724. ASSERT_EQ(
  25725. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25726. ws::impl::FrameRead::Ok)
  25727. << len << " " << mask;
  25728. EXPECT_TRUE(fin);
  25729. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25730. EXPECT_EQ(body, payload) << len << " " << mask;
  25731. }
  25732. }
  25733. }
  25734. // Hands out its pieces one read at a time, timing out between each two.
  25735. class WsTimeoutBetweenPiecesStream : public Stream {
  25736. public:
  25737. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25738. : pieces_(std::move(pieces)) {}
  25739. bool is_readable() const override { return true; }
  25740. bool wait_readable() const override { return true; }
  25741. bool wait_writable() const override { return true; }
  25742. ssize_t read(char *ptr, size_t size) override {
  25743. if (time_out_) {
  25744. time_out_ = false;
  25745. error_ = Error::Timeout;
  25746. return -1;
  25747. }
  25748. if (i_ >= pieces_.size()) {
  25749. error_ = Error::ConnectionClosed;
  25750. return 0;
  25751. }
  25752. auto &piece = pieces_[i_];
  25753. auto n = (std::min)(size, piece.size() - at_);
  25754. memcpy(ptr, piece.data() + at_, n);
  25755. at_ += n;
  25756. if (at_ == piece.size()) {
  25757. i_++;
  25758. at_ = 0;
  25759. time_out_ = true;
  25760. }
  25761. return static_cast<ssize_t>(n);
  25762. }
  25763. ssize_t write(const char *, size_t size) override {
  25764. return static_cast<ssize_t>(size);
  25765. }
  25766. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25767. ip = "127.0.0.1";
  25768. port = 0;
  25769. }
  25770. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25771. ip = "127.0.0.1";
  25772. port = 0;
  25773. }
  25774. socket_t socket() const override { return INVALID_SOCKET; }
  25775. time_t duration() const override { return 0; }
  25776. private:
  25777. std::vector<std::string> pieces_;
  25778. size_t i_ = 0;
  25779. size_t at_ = 0;
  25780. bool time_out_ = false;
  25781. };
  25782. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25783. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25784. std::string frame = "\x81\x85";
  25785. frame.append(4, '\0');
  25786. frame += "Hello";
  25787. // The header's first byte, then its second with half the mask key, then
  25788. // the rest
  25789. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25790. frame.substr(4)};
  25791. WsTimeoutBetweenPiecesStream strm(pieces);
  25792. ws::impl::FrameReader reader;
  25793. ws::Opcode opcode;
  25794. std::string payload;
  25795. bool fin = false;
  25796. for (int i = 0; i < 2; i++) {
  25797. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25798. reader.read(strm, opcode, payload, fin, true, 0));
  25799. EXPECT_TRUE(reader.begun());
  25800. }
  25801. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25802. reader.read(strm, opcode, payload, fin, true, 0));
  25803. EXPECT_FALSE(reader.begun());
  25804. EXPECT_TRUE(fin);
  25805. EXPECT_EQ(ws::Opcode::Text, opcode);
  25806. EXPECT_EQ("Hello", payload);
  25807. // Read in one go, the frame cannot be gone on with after a timeout
  25808. WsTimeoutBetweenPiecesStream again(pieces);
  25809. EXPECT_EQ(
  25810. ws::impl::FrameRead::Fail,
  25811. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25812. }
  25813. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25814. std::string body(2000, 'x');
  25815. std::string frame;
  25816. frame += static_cast<char>(0x82); // FIN + Binary
  25817. frame += static_cast<char>(126); // 16-bit length follows
  25818. frame += static_cast<char>(body.size() >> 8);
  25819. frame += static_cast<char>(body.size() & 0xff);
  25820. frame += body;
  25821. detail::BufferStream strm;
  25822. strm.write(frame.data(), frame.size());
  25823. ws::Opcode opcode;
  25824. std::string payload;
  25825. bool fin;
  25826. EXPECT_EQ(
  25827. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25828. ws::impl::FrameRead::Ok);
  25829. EXPECT_EQ(body, payload);
  25830. }
  25831. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25832. // The header announces the largest payload allowed, and only 3 bytes of it
  25833. // ever arrive.
  25834. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25835. std::string frame;
  25836. frame += static_cast<char>(0x82); // FIN + Binary
  25837. frame += static_cast<char>(127); // 64-bit length follows
  25838. for (int shift = 56; shift >= 0; shift -= 8) {
  25839. frame += static_cast<char>((len >> shift) & 0xff);
  25840. }
  25841. frame += "abc";
  25842. detail::BufferStream strm;
  25843. strm.write(frame.data(), frame.size());
  25844. ws::Opcode opcode;
  25845. std::string payload;
  25846. bool fin;
  25847. EXPECT_EQ(
  25848. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25849. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25850. ws::impl::FrameRead::Fail);
  25851. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25852. }
  25853. TEST(WebSocketTest, QueryStringInHandshake) {
  25854. Server svr;
  25855. std::mutex mtx;
  25856. std::string received_target;
  25857. std::string received_token;
  25858. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25859. {
  25860. std::lock_guard<std::mutex> lock(mtx);
  25861. received_target = req.target;
  25862. if (req.has_param("token")) {
  25863. received_token = req.get_param_value("token");
  25864. }
  25865. }
  25866. std::string msg;
  25867. while (ws.read(msg)) {
  25868. ws.send(msg);
  25869. }
  25870. });
  25871. auto port = svr.bind_to_any_port("localhost");
  25872. std::thread t([&]() { svr.listen_after_bind(); });
  25873. svr.wait_until_ready();
  25874. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25875. "/ws?token=ABC&session=123");
  25876. ASSERT_TRUE(client.connect());
  25877. // Round-trip ensures the handler has run and captured the request.
  25878. ASSERT_TRUE(client.send("hello"));
  25879. std::string msg;
  25880. ASSERT_TRUE(client.read(msg));
  25881. EXPECT_EQ("hello", msg);
  25882. client.close();
  25883. {
  25884. std::lock_guard<std::mutex> lock(mtx);
  25885. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25886. EXPECT_EQ("ABC", received_token);
  25887. }
  25888. svr.stop();
  25889. t.join();
  25890. }
  25891. // Run a handshake against a throwaway server and hand the request the server
  25892. // received back to the caller, so tests can assert on the headers the client
  25893. // actually put on the wire.
  25894. static void capture_websocket_handshake_request(
  25895. const Headers &client_headers,
  25896. std::function<void(const Request &, int port)> verify) {
  25897. Server svr;
  25898. std::mutex mtx;
  25899. Request received;
  25900. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25901. {
  25902. std::lock_guard<std::mutex> lock(mtx);
  25903. received = req;
  25904. }
  25905. std::string msg;
  25906. while (ws.read(msg)) {
  25907. ws.send(msg);
  25908. }
  25909. });
  25910. auto port = svr.bind_to_any_port("localhost");
  25911. std::thread t([&]() { svr.listen_after_bind(); });
  25912. auto se = detail::scope_exit([&] {
  25913. svr.stop();
  25914. t.join();
  25915. });
  25916. svr.wait_until_ready();
  25917. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25918. client_headers);
  25919. ASSERT_TRUE(client.connect());
  25920. ASSERT_TRUE(client.send("hello"));
  25921. std::string msg;
  25922. ASSERT_TRUE(client.read(msg));
  25923. client.close();
  25924. {
  25925. std::lock_guard<std::mutex> lock(mtx);
  25926. verify(received, port);
  25927. }
  25928. }
  25929. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25930. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25931. // Non-default port must be present in the Host header. Default ports
  25932. // (80/443) are omitted; that logic is covered by
  25933. // MakeHostAndPortStringTest.
  25934. EXPECT_EQ("localhost:" + std::to_string(port),
  25935. req.get_header_value("Host"));
  25936. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25937. req.get_header_value("User-Agent"));
  25938. EXPECT_FALSE(req.has_header("Accept"));
  25939. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25940. EXPECT_FALSE(req.has_header("Content-Length"));
  25941. });
  25942. }
  25943. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25944. capture_websocket_handshake_request(
  25945. {{"Host", "example.com"},
  25946. {"User-Agent", "custom-agent"},
  25947. {"X-Custom", "value"}},
  25948. [](const Request &req, int) {
  25949. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25950. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25951. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25952. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25953. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25954. });
  25955. }
  25956. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25957. capture_websocket_handshake_request(
  25958. {{"Upgrade", "bogus"},
  25959. {"Connection", "close"},
  25960. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25961. {"Sec-WebSocket-Version", "8"}},
  25962. [](const Request &req, int) {
  25963. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25964. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25965. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25966. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25967. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25968. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25969. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25970. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25971. req.get_header_value("Sec-WebSocket-Key"));
  25972. });
  25973. }
  25974. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25975. // A header the client refuses to send must abort the handshake before any
  25976. // part of it reaches the wire; a lone request line would otherwise sit in
  25977. // the peer's buffer as a truncated request.
  25978. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25979. ASSERT_NE(INVALID_SOCKET, srv);
  25980. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25981. sockaddr_in addr{};
  25982. addr.sin_family = AF_INET;
  25983. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25984. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25985. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25986. ASSERT_EQ(0, ::listen(srv, 1));
  25987. sockaddr_in bound{};
  25988. socklen_t bound_len = sizeof(bound);
  25989. ASSERT_EQ(
  25990. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25991. auto port = ntohs(bound.sin_port);
  25992. ssize_t received = -1;
  25993. std::thread t([&] {
  25994. // Bound every blocking call so a regression fails the test with a bad
  25995. // value instead of hanging the suite.
  25996. fd_set rfds;
  25997. FD_ZERO(&rfds);
  25998. FD_SET(srv, &rfds);
  25999. timeval tv{5, 0};
  26000. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  26001. 0) {
  26002. return;
  26003. }
  26004. sockaddr_in cli_addr{};
  26005. socklen_t cli_len = sizeof(cli_addr);
  26006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  26007. if (cli == INVALID_SOCKET) { return; }
  26008. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  26009. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26010. char buf[4096];
  26011. received = ::recv(cli, buf, sizeof(buf), 0);
  26012. });
  26013. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  26014. // connect() has already shut the socket down by the time it returns false,
  26015. // so the peer sees EOF without waiting for the client to be destroyed.
  26016. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  26017. {{"X-Bad", "a\r\nInjected: 1"}});
  26018. EXPECT_FALSE(client.connect());
  26019. t.join();
  26020. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  26021. EXPECT_EQ(0, received);
  26022. }
  26023. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  26024. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  26025. // contains "upgrade" as a substring is a different token and must not
  26026. // start a WebSocket handshake.
  26027. auto make_request = [](const std::vector<std::string> &connection_values) {
  26028. Request req;
  26029. req.method = "GET";
  26030. req.headers.emplace("Upgrade", "websocket");
  26031. for (const auto &value : connection_values) {
  26032. req.headers.emplace("Connection", value);
  26033. }
  26034. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  26035. req.headers.emplace("Sec-WebSocket-Version", "13");
  26036. return req;
  26037. };
  26038. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  26039. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  26040. EXPECT_TRUE(
  26041. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  26042. EXPECT_TRUE(
  26043. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  26044. EXPECT_TRUE(
  26045. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  26046. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  26047. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  26048. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  26049. EXPECT_FALSE(
  26050. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  26051. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  26052. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  26053. }
  26054. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  26055. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  26056. // asks recipients to match each protocol-name case-insensitively, and RFC
  26057. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  26058. // client naming websocket alongside another protocol, or on a second field
  26059. // line, is offering websocket; a value that merely contains "websocket" as a
  26060. // substring is a different protocol name and is not.
  26061. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  26062. Request req;
  26063. req.method = "GET";
  26064. for (const auto &value : upgrade_values) {
  26065. req.headers.emplace("Upgrade", value);
  26066. }
  26067. req.headers.emplace("Connection", "Upgrade");
  26068. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  26069. req.headers.emplace("Sec-WebSocket-Version", "13");
  26070. return req;
  26071. };
  26072. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  26073. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  26074. EXPECT_TRUE(
  26075. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  26076. EXPECT_TRUE(
  26077. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  26078. EXPECT_TRUE(
  26079. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  26080. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  26081. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  26082. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  26083. EXPECT_FALSE(
  26084. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  26085. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  26086. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  26087. }
  26088. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  26089. Server svr;
  26090. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  26091. auto port = svr.bind_to_any_port("localhost");
  26092. std::thread t([&]() { svr.listen_after_bind(); });
  26093. auto se = detail::scope_exit([&] {
  26094. svr.stop();
  26095. t.join();
  26096. });
  26097. svr.wait_until_ready();
  26098. Headers headers = {{"Upgrade", "websocket"},
  26099. {"Connection", "notupgrade"},
  26100. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  26101. {"Sec-WebSocket-Version", "13"}};
  26102. Client cli("localhost", port);
  26103. auto res = cli.Get("/ws", headers);
  26104. // The route exists only as a WebSocket route, so a request that fails the
  26105. // handshake check falls through to ordinary routing.
  26106. ASSERT_TRUE(res);
  26107. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  26108. }
  26109. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  26110. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  26111. // Connection value is the only thing left for the client to reject.
  26112. Server svr;
  26113. svr.Get("/ws", [](const Request &req, Response &res) {
  26114. res.status = StatusCode::SwitchingProtocol_101;
  26115. res.set_header("Upgrade", "websocket");
  26116. res.set_header("Connection", "notupgrade");
  26117. res.set_header("Sec-WebSocket-Accept",
  26118. detail::websocket_accept_key(
  26119. req.get_header_value("Sec-WebSocket-Key")));
  26120. });
  26121. auto port = svr.bind_to_any_port("localhost");
  26122. std::thread t([&]() { svr.listen_after_bind(); });
  26123. auto se = detail::scope_exit([&] {
  26124. svr.stop();
  26125. t.join();
  26126. });
  26127. svr.wait_until_ready();
  26128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26129. auto res = client.connect();
  26130. EXPECT_FALSE(res);
  26131. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26132. EXPECT_FALSE(client.is_open());
  26133. }
  26134. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  26135. Server svr;
  26136. svr.Get("/ws", [](const Request &req, Response &res) {
  26137. res.status = StatusCode::SwitchingProtocol_101;
  26138. res.set_header("Upgrade", "websocket");
  26139. res.set_header("Connection", "Upgrade");
  26140. res.set_header("Sec-WebSocket-Accept",
  26141. detail::websocket_accept_key(
  26142. req.get_header_value("Sec-WebSocket-Key")));
  26143. res.set_header("Sec-WebSocket-Protocol", "admin");
  26144. });
  26145. auto port = svr.bind_to_any_port("localhost");
  26146. std::thread t([&]() { svr.listen_after_bind(); });
  26147. auto se = detail::scope_exit([&] {
  26148. svr.stop();
  26149. t.join();
  26150. });
  26151. svr.wait_until_ready();
  26152. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  26153. // Server selects a subprotocol the client never offered
  26154. {
  26155. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  26156. ws::WebSocketClient client(url, headers);
  26157. auto res = client.connect();
  26158. EXPECT_FALSE(res);
  26159. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26160. EXPECT_FALSE(client.is_open());
  26161. EXPECT_TRUE(client.subprotocol().empty());
  26162. }
  26163. // Client offered none but the server named one anyway
  26164. {
  26165. ws::WebSocketClient client(url);
  26166. auto res = client.connect();
  26167. EXPECT_FALSE(res);
  26168. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26169. EXPECT_FALSE(client.is_open());
  26170. EXPECT_TRUE(client.subprotocol().empty());
  26171. }
  26172. }
  26173. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  26174. // The socket path doubles as the URL host, so it must not contain '/'.
  26175. const char *shard = getenv("GTEST_SHARD_INDEX");
  26176. const std::string sock_path =
  26177. shard ? std::string("httplib-ws-") + shard + ".sock"
  26178. : std::string("httplib-ws.sock");
  26179. std::remove(sock_path.c_str());
  26180. Server svr;
  26181. std::mutex mtx;
  26182. std::string received_host;
  26183. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  26184. {
  26185. std::lock_guard<std::mutex> lock(mtx);
  26186. received_host = req.get_header_value("Host");
  26187. }
  26188. std::string msg;
  26189. while (ws.read(msg)) {
  26190. ws.send(msg);
  26191. }
  26192. });
  26193. svr.set_address_family(AF_UNIX);
  26194. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  26195. auto se = detail::scope_exit([&] {
  26196. svr.stop();
  26197. t.join();
  26198. std::remove(sock_path.c_str());
  26199. });
  26200. svr.wait_until_ready();
  26201. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  26202. client.set_address_family(AF_UNIX);
  26203. ASSERT_TRUE(client.connect());
  26204. ASSERT_TRUE(client.send("hello"));
  26205. std::string msg;
  26206. ASSERT_TRUE(client.read(msg));
  26207. client.close();
  26208. {
  26209. std::lock_guard<std::mutex> lock(mtx);
  26210. // There is no host:port for a Unix socket, so the same "localhost"
  26211. // placeholder the HTTP client uses is expected.
  26212. EXPECT_EQ("localhost", received_host);
  26213. }
  26214. }
  26215. // Two threads must never parse WebSocket frames from the same stream.
  26216. // close() used to read the peer's Close reply with its own frame read, so it
  26217. // raced a reader thread that was in the middle of a payload: the payload loop
  26218. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  26219. // so bytes taken by close() were replaced with bytes from further along the
  26220. // stream. The message kept its length and silently changed content.
  26221. //
  26222. // The raw peer below sends a frame header plus part of the payload, waits for
  26223. // the handler to call close(), and only then sends the rest. Whichever thread
  26224. // would win the race for those bytes, the message must arrive intact, because
  26225. // close() must not touch the stream while read() owns it.
  26226. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  26227. #ifndef _WIN32
  26228. signal(SIGPIPE, SIG_IGN);
  26229. #endif
  26230. const size_t payload_len = 120; // fits the 7-bit length field
  26231. const size_t prefix_len = 8;
  26232. const int attempts = 8;
  26233. std::string expected(payload_len, '\0');
  26234. for (size_t i = 0; i < payload_len; i++) {
  26235. expected[i] = static_cast<char>('a' + i % 26);
  26236. }
  26237. std::atomic<bool> peer_stalled{false};
  26238. std::atomic<bool> handler_done{false};
  26239. std::mutex received_mutex;
  26240. std::vector<std::string> received;
  26241. // Bound every wait, so a regression fails the test instead of hanging the
  26242. // suite.
  26243. auto wait_for = [](const std::atomic<bool> &flag) {
  26244. for (int i = 0; i < 500 && !flag; i++) {
  26245. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26246. }
  26247. };
  26248. Server svr;
  26249. svr.set_websocket_ping_interval(0);
  26250. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26251. std::thread reader([&]() {
  26252. std::string msg;
  26253. while (ws.read(msg)) {
  26254. std::lock_guard<std::mutex> guard(received_mutex);
  26255. received.push_back(msg);
  26256. }
  26257. });
  26258. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26259. // inside a frame when close() runs.
  26260. wait_for(peer_stalled);
  26261. ws.close();
  26262. reader.join();
  26263. handler_done = true;
  26264. });
  26265. auto port = svr.bind_to_any_port("127.0.0.1");
  26266. std::thread t([&]() { svr.listen_after_bind(); });
  26267. auto se = detail::scope_exit([&] {
  26268. svr.stop();
  26269. t.join();
  26270. });
  26271. svr.wait_until_ready();
  26272. auto send_bytes = [](socket_t s, const std::string &data) {
  26273. #ifdef _WIN32
  26274. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26275. #else
  26276. auto n = ::send(s, data.data(), data.size(), 0);
  26277. #endif
  26278. return n == static_cast<decltype(n)>(data.size());
  26279. };
  26280. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26281. // Every length used here fits the 7-bit length field.
  26282. auto masked_header = [](uint8_t first_byte, size_t len) {
  26283. std::string h;
  26284. h += static_cast<char>(first_byte);
  26285. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26286. h.append(4, '\0'); // mask key
  26287. return h;
  26288. };
  26289. for (int attempt = 0; attempt < attempts; attempt++) {
  26290. peer_stalled = false;
  26291. handler_done = false;
  26292. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26293. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26294. auto se_sock = detail::scope_exit([&] {
  26295. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26296. });
  26297. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26298. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26299. sockaddr_in addr{};
  26300. addr.sin_family = AF_INET;
  26301. addr.sin_port = htons(static_cast<uint16_t>(port));
  26302. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26303. ASSERT_EQ(
  26304. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26305. << "attempt " << attempt;
  26306. ASSERT_TRUE(send_bytes(sock,
  26307. "GET /ws HTTP/1.1\r\n"
  26308. "Host: 127.0.0.1\r\n"
  26309. "Upgrade: websocket\r\n"
  26310. "Connection: Upgrade\r\n"
  26311. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26312. "Sec-WebSocket-Version: 13\r\n"
  26313. "\r\n"))
  26314. << "attempt " << attempt;
  26315. std::string response;
  26316. while (response.find("\r\n\r\n") == std::string::npos) {
  26317. char buf[512];
  26318. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26319. if (n <= 0) { break; }
  26320. response.append(buf, static_cast<size_t>(n));
  26321. }
  26322. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26323. << "attempt " << attempt;
  26324. // Send the header of a Binary message but only the first prefix_len bytes
  26325. // of its payload, leaving the reader thread stalled inside the payload.
  26326. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26327. expected.substr(0, prefix_len)))
  26328. << "attempt " << attempt;
  26329. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26330. peer_stalled = true;
  26331. // Let close() send its Close frame and park in its own read before the
  26332. // rest of the payload arrives, so both threads are waiting for it.
  26333. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26334. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26335. close_frame += static_cast<char>(0x03); // status 1000
  26336. close_frame += static_cast<char>(0xE8);
  26337. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26338. << "attempt " << attempt;
  26339. // Closing the peer releases the reader thread even on the buggy path,
  26340. // where it waits for bytes another thread already consumed.
  26341. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26342. detail::close_socket(sock);
  26343. sock = INVALID_SOCKET;
  26344. wait_for(handler_done);
  26345. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26346. }
  26347. std::lock_guard<std::mutex> guard(received_mutex);
  26348. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26349. << "a message in flight when close() ran was dropped";
  26350. for (size_t i = 0; i < received.size(); i++) {
  26351. EXPECT_EQ(expected, received[i]) << "message " << i;
  26352. }
  26353. }
  26354. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26355. // returning the socket, or INVALID_SOCKET.
  26356. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26357. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26358. if (sock == INVALID_SOCKET) { return sock; }
  26359. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26360. sockaddr_in addr{};
  26361. addr.sin_family = AF_INET;
  26362. addr.sin_port = htons(static_cast<uint16_t>(port));
  26363. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26364. std::string req = "GET " + path +
  26365. " HTTP/1.1\r\n"
  26366. "Host: 127.0.0.1\r\n"
  26367. "Upgrade: websocket\r\n"
  26368. "Connection: Upgrade\r\n"
  26369. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26370. "Sec-WebSocket-Version: 13\r\n"
  26371. "\r\n";
  26372. std::string res;
  26373. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26374. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26375. static_cast<ssize_t>(req.size())) {
  26376. char c;
  26377. while (res.find("\r\n\r\n") == std::string::npos &&
  26378. ::recv(sock, &c, 1, 0) == 1) {
  26379. res += c;
  26380. }
  26381. }
  26382. if (res.find(" 101 ") == std::string::npos) {
  26383. detail::close_socket(sock);
  26384. return INVALID_SOCKET;
  26385. }
  26386. return sock;
  26387. }
  26388. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26389. // The payload must fit the 7-bit length field.
  26390. static std::string masked_frame(uint8_t first_byte,
  26391. const std::string &payload) {
  26392. std::string f;
  26393. f += static_cast<char>(first_byte);
  26394. f += static_cast<char>(0x80 | payload.size());
  26395. f.append(4, '\0');
  26396. return f + payload;
  26397. }
  26398. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26399. // server sends back, or what came before it closed.
  26400. static std::string raw_websocket_reply(int port, const std::string &frames,
  26401. size_t n) {
  26402. auto sock = connect_raw_websocket(port, "/ws");
  26403. if (sock == INVALID_SOCKET) { return std::string(); }
  26404. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26405. std::string reply;
  26406. char buf[256];
  26407. while (reply.size() < n) {
  26408. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26409. if (got <= 0) { break; }
  26410. reply.append(buf, static_cast<size_t>(got));
  26411. }
  26412. detail::close_socket(sock);
  26413. return reply;
  26414. }
  26415. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26416. std::atomic<bool> done{false};
  26417. std::string received;
  26418. Server svr;
  26419. svr.set_websocket_ping_interval(0);
  26420. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26421. std::string msg;
  26422. if (ws.read(msg) == ws::Binary) { received = msg; }
  26423. done = true;
  26424. });
  26425. auto port = svr.bind_to_any_port("127.0.0.1");
  26426. std::thread t([&]() { svr.listen_after_bind(); });
  26427. auto se = detail::scope_exit([&] {
  26428. svr.stop();
  26429. t.join();
  26430. });
  26431. svr.wait_until_ready();
  26432. auto sock = connect_raw_websocket(port, "/ws");
  26433. ASSERT_NE(INVALID_SOCKET, sock);
  26434. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26435. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26436. masked_frame(0x89, "p") + // FIN + Ping
  26437. masked_frame(0x80, "lo"); // FIN + Continuation
  26438. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26439. for (int i = 0; i < 500 && !done; i++) {
  26440. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26441. }
  26442. ASSERT_TRUE(done);
  26443. EXPECT_EQ("Hello", received);
  26444. // The Ping between the fragments is answered with a Pong.
  26445. char pong[3];
  26446. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26447. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26448. }
  26449. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26450. #ifndef _WIN32
  26451. signal(SIGPIPE, SIG_IGN);
  26452. #endif
  26453. std::atomic<bool> read_ended{false};
  26454. std::atomic<bool> sending{true};
  26455. Server svr;
  26456. svr.set_websocket_ping_interval(0);
  26457. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26458. std::thread reader([&]() {
  26459. std::string msg;
  26460. while (ws.read(msg)) {}
  26461. read_ended = true;
  26462. });
  26463. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26464. ws.close();
  26465. reader.join();
  26466. });
  26467. auto port = svr.bind_to_any_port("127.0.0.1");
  26468. std::thread t([&]() { svr.listen_after_bind(); });
  26469. auto se = detail::scope_exit([&] {
  26470. svr.stop();
  26471. t.join();
  26472. });
  26473. svr.wait_until_ready();
  26474. auto sock = connect_raw_websocket(port, "/ws");
  26475. ASSERT_NE(INVALID_SOCKET, sock);
  26476. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26477. // A Text message whose empty continuation frames never end
  26478. std::thread sender([&]() {
  26479. auto data = masked_frame(0x01, "");
  26480. while (sending) {
  26481. data += masked_frame(0x00, "");
  26482. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26483. return;
  26484. }
  26485. data.clear();
  26486. }
  26487. });
  26488. for (int i = 0; i < 300 && !read_ended; i++) {
  26489. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26490. }
  26491. sending = false;
  26492. sender.join();
  26493. EXPECT_TRUE(read_ended);
  26494. }
  26495. TEST(WebSocketTest, ServerMaxMessageLength) {
  26496. Server svr;
  26497. svr.set_websocket_ping_interval(0);
  26498. svr.set_websocket_max_message_length(100);
  26499. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26500. std::string msg;
  26501. while (ws.read(msg)) {
  26502. ws.send(msg);
  26503. }
  26504. });
  26505. auto port = svr.bind_to_any_port("127.0.0.1");
  26506. std::thread t([&]() { svr.listen_after_bind(); });
  26507. auto se = detail::scope_exit([&] {
  26508. svr.stop();
  26509. t.join();
  26510. });
  26511. svr.wait_until_ready();
  26512. const std::string ping(110, 'p');
  26513. const std::string half(50, 'a');
  26514. const std::string over(60, 'b');
  26515. const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
  26516. // A Ping longer than the limit is answered, since the limit is for
  26517. // messages. A message at the limit is echoed, and one over it is refused
  26518. // although each of its frames is within it.
  26519. EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
  26520. raw_websocket_reply(
  26521. port,
  26522. masked_frame(0x89, ping) + masked_frame(0x01, half) +
  26523. masked_frame(0x80, half) + masked_frame(0x01, over) +
  26524. masked_frame(0x80, over),
  26525. 2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
  26526. // A header that announces more than the limit is refused before its payload
  26527. EXPECT_EQ(too_big, raw_websocket_reply(port,
  26528. std::string("\x82\xfe\x03\xe8", 4) +
  26529. std::string(4, '\0'),
  26530. too_big.size()));
  26531. }
  26532. TEST(WebSocketTest, ClientMaxMessageLength) {
  26533. Server svr;
  26534. svr.set_websocket_ping_interval(0);
  26535. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26536. ws.send(std::string(1024, 'a'));
  26537. ws.send(std::string(2048, 'b'));
  26538. std::string msg;
  26539. while (ws.read(msg)) {}
  26540. });
  26541. auto port = svr.bind_to_any_port(HOST);
  26542. std::thread t([&]() { svr.listen_after_bind(); });
  26543. auto se = detail::scope_exit([&] {
  26544. svr.stop();
  26545. t.join();
  26546. });
  26547. svr.wait_until_ready();
  26548. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26549. client.set_read_timeout(5, 0);
  26550. client.set_websocket_max_message_length(1024);
  26551. ASSERT_TRUE(client.connect());
  26552. std::string msg;
  26553. ASSERT_EQ(ws::Text, client.read(msg));
  26554. EXPECT_EQ(1024u, msg.size());
  26555. EXPECT_EQ(ws::Fail, client.read(msg));
  26556. EXPECT_FALSE(client.is_open());
  26557. // 0 lifts the limit
  26558. client.set_websocket_max_message_length(0);
  26559. ASSERT_TRUE(client.connect());
  26560. EXPECT_EQ(ws::Text, client.read(msg));
  26561. EXPECT_EQ(ws::Text, client.read(msg));
  26562. EXPECT_EQ(2048u, msg.size());
  26563. }
  26564. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26565. Server svr;
  26566. svr.set_websocket_ping_interval(-1);
  26567. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26568. std::string msg;
  26569. while (ws.read(msg)) {}
  26570. });
  26571. auto port = svr.bind_to_any_port("127.0.0.1");
  26572. std::thread t([&]() { svr.listen_after_bind(); });
  26573. auto se = detail::scope_exit([&] {
  26574. svr.stop();
  26575. t.join();
  26576. });
  26577. svr.wait_until_ready();
  26578. auto sock = connect_raw_websocket(port, "/ws");
  26579. ASSERT_NE(INVALID_SOCKET, sock);
  26580. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26581. // Nothing comes while the client stays quiet.
  26582. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26583. char c;
  26584. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26585. }
  26586. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26587. // and that has to end a read() already waiting on the peer, on every platform.
  26588. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26589. // The peer sends no pings, and its handler never calls read(), which is
  26590. // where pongs are written.
  26591. std::mutex mutex;
  26592. std::condition_variable cv;
  26593. auto release = false;
  26594. svr.set_websocket_ping_interval(0);
  26595. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26596. std::unique_lock<std::mutex> lock(mutex);
  26597. cv.wait(lock, [&] { return release; });
  26598. });
  26599. auto port = svr.bind_to_any_port(HOST);
  26600. std::thread t([&]() { svr.listen_after_bind(); });
  26601. auto se = detail::scope_exit([&] {
  26602. {
  26603. std::lock_guard<std::mutex> lock(mutex);
  26604. release = true;
  26605. }
  26606. cv.notify_all();
  26607. svr.stop();
  26608. t.join();
  26609. });
  26610. svr.wait_until_ready();
  26611. ws::WebSocketClient client(std::string(scheme) +
  26612. "://localhost:" + std::to_string(port) + "/ws");
  26613. #ifdef CPPHTTPLIB_SSL_ENABLED
  26614. client.enable_server_certificate_verification(false);
  26615. #endif
  26616. // A ping a second, given up on after two go unanswered: about 3s
  26617. client.set_websocket_ping_interval(1);
  26618. client.set_websocket_max_missed_pongs(2);
  26619. // Well past that, so that a read the timeout ends instead stands out
  26620. client.set_read_timeout(10);
  26621. ASSERT_TRUE(client.connect());
  26622. auto start = std::chrono::steady_clock::now();
  26623. std::string msg;
  26624. EXPECT_EQ(ws::Fail, client.read(msg));
  26625. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26626. std::chrono::steady_clock::now() - start)
  26627. .count(),
  26628. 6000);
  26629. EXPECT_FALSE(client.is_open());
  26630. }
  26631. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26632. Server svr;
  26633. check_pong_timeout_ends_read(svr, "ws");
  26634. }
  26635. #ifdef CPPHTTPLIB_SSL_ENABLED
  26636. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26638. ASSERT_TRUE(svr.is_valid());
  26639. check_pong_timeout_ends_read(svr, "wss");
  26640. }
  26641. #endif
  26642. // listen() returns only after every handler has, so Server::stop() has to end
  26643. // a WebSocket handler's read() waiting on a client that stays connected and
  26644. // quiet, whether or not the handler bounded its reads, and the client's
  26645. // connection ends with it.
  26646. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26647. bool bounded) {
  26648. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26649. if (bounded) { ws.set_read_timeout(0, 50000); }
  26650. std::string msg;
  26651. while (ws.read(msg) != ws::Fail) {}
  26652. });
  26653. auto port = svr.bind_to_any_port(HOST);
  26654. std::thread t([&]() { svr.listen_after_bind(); });
  26655. auto se = detail::scope_exit([&] {
  26656. if (t.joinable()) {
  26657. svr.stop();
  26658. t.join();
  26659. }
  26660. });
  26661. svr.wait_until_ready();
  26662. ws::WebSocketClient client(std::string(scheme) +
  26663. "://localhost:" + std::to_string(port) + "/ws");
  26664. #ifdef CPPHTTPLIB_SSL_ENABLED
  26665. client.enable_server_certificate_verification(false);
  26666. #endif
  26667. client.set_read_timeout(2);
  26668. ASSERT_TRUE(client.connect());
  26669. auto stopped = std::async(std::launch::async, [&] {
  26670. svr.stop();
  26671. t.join();
  26672. });
  26673. std::string msg;
  26674. EXPECT_EQ(ws::Fail, client.read(msg));
  26675. EXPECT_FALSE(client.is_open());
  26676. auto in_time =
  26677. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26678. // A handler the stop did not reach ends when the client leaves
  26679. if (!in_time) { client.close(); }
  26680. stopped.wait();
  26681. EXPECT_TRUE(in_time);
  26682. }
  26683. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26684. Server svr;
  26685. check_stop_ends_websocket_read(svr, "ws", false);
  26686. }
  26687. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26688. Server svr;
  26689. check_stop_ends_websocket_read(svr, "ws", true);
  26690. }
  26691. #ifdef CPPHTTPLIB_SSL_ENABLED
  26692. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26694. ASSERT_TRUE(svr.is_valid());
  26695. check_stop_ends_websocket_read(svr, "wss", false);
  26696. }
  26697. #endif
  26698. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26699. // dropped connection, whether the handler waits for a message or for the rest
  26700. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26701. // time out inside the message as well, and the stop ends them too.
  26702. static void check_stop_closes_with_going_away(const std::string &sent,
  26703. bool bounded = false) {
  26704. Server svr;
  26705. svr.set_websocket_ping_interval(0);
  26706. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26707. if (bounded) { ws.set_read_timeout(0, 10000); }
  26708. std::string msg;
  26709. while (ws.read(msg) != ws::Fail) {}
  26710. });
  26711. auto port = svr.bind_to_any_port("127.0.0.1");
  26712. std::thread t([&]() { svr.listen_after_bind(); });
  26713. auto se = detail::scope_exit([&] {
  26714. svr.stop();
  26715. t.join();
  26716. });
  26717. svr.wait_until_ready();
  26718. // Closed before the join above, which a handler the stop did not reach
  26719. // would otherwise hold up.
  26720. auto sock = connect_raw_websocket(port, "/ws");
  26721. ASSERT_NE(INVALID_SOCKET, sock);
  26722. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26723. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26724. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26725. // Let the handler take what was sent and wait for more
  26726. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26727. svr.stop();
  26728. // FIN + Close, its length, then the code: unmasked, from a server
  26729. std::string head;
  26730. char c;
  26731. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26732. head += c;
  26733. }
  26734. const std::string reason = "server stopping";
  26735. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26736. "\x03\xe9",
  26737. head);
  26738. }
  26739. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26740. check_stop_closes_with_going_away("");
  26741. }
  26742. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26743. // A Text frame without FIN: the first fragment of a message
  26744. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26745. }
  26746. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26747. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26748. /*bounded=*/true);
  26749. }
  26750. // A handler that bounds its reads gets control back within its timeout even
  26751. // while a message arrives in pieces, and the message whole once the last has
  26752. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26753. // sent once read() has timed out twice since the one before was sent, so the
  26754. // second timeout came from a read() that had that piece to take.
  26755. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26756. const std::string &expected) {
  26757. std::atomic<bool> done{false};
  26758. std::atomic<int> timeouts{0};
  26759. std::string received;
  26760. Server svr;
  26761. svr.set_websocket_ping_interval(0);
  26762. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26763. ws.set_read_timeout(0, 10000);
  26764. std::string msg;
  26765. ws::ReadResult r;
  26766. while ((r = ws.read(msg)) == ws::Timeout) {
  26767. timeouts++;
  26768. }
  26769. if (r == ws::Text) { received = msg; }
  26770. done = true;
  26771. });
  26772. auto port = svr.bind_to_any_port("127.0.0.1");
  26773. std::thread t([&]() { svr.listen_after_bind(); });
  26774. auto se = detail::scope_exit([&] {
  26775. svr.stop();
  26776. t.join();
  26777. });
  26778. svr.wait_until_ready();
  26779. auto sock = connect_raw_websocket(port, "/ws");
  26780. ASSERT_NE(INVALID_SOCKET, sock);
  26781. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26782. // Each piece goes out at once, not held back by Nagle's algorithm
  26783. ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  26784. for (size_t i = 0; i < pieces.size(); i++) {
  26785. ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
  26786. detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
  26787. if (i + 1 == pieces.size()) { break; }
  26788. auto before = timeouts.load();
  26789. for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
  26790. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26791. }
  26792. ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
  26793. }
  26794. for (int i = 0; i < 5000 && !done; i++) {
  26795. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26796. }
  26797. ASSERT_TRUE(done);
  26798. EXPECT_EQ(expected, received);
  26799. }
  26800. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26801. // The header's first byte, then its second with half the mask key, then
  26802. // the rest: what a frame written in several writes may look like when
  26803. // Nagle's algorithm holds the later ones back for an ACK.
  26804. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26805. check_bounded_read_resumes(
  26806. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26807. }
  26808. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26809. check_bounded_read_resumes(
  26810. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26811. }
  26812. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26813. Server svr;
  26814. svr.set_websocket_ping_interval(0);
  26815. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26816. std::string msg;
  26817. while (ws.read(msg)) {}
  26818. });
  26819. auto port = svr.bind_to_any_port("127.0.0.1");
  26820. std::thread t([&]() { svr.listen_after_bind(); });
  26821. auto se = detail::scope_exit([&] {
  26822. svr.stop();
  26823. t.join();
  26824. });
  26825. svr.wait_until_ready();
  26826. // Each Close payload and the reply it should get: an echo when valid, 1002
  26827. // otherwise.
  26828. std::vector<std::pair<std::string, std::string>> cases = {
  26829. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26830. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26831. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26832. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26833. };
  26834. // Also between the fragments of a message.
  26835. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26836. for (const auto &c : cases) {
  26837. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26838. c.second,
  26839. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26840. 2 + c.second.size()));
  26841. }
  26842. }
  26843. }
  26844. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26845. Server svr;
  26846. svr.set_websocket_ping_interval(0);
  26847. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26848. std::string msg;
  26849. while (ws.read(msg)) {}
  26850. });
  26851. auto port = svr.bind_to_any_port("127.0.0.1");
  26852. std::thread t([&]() { svr.listen_after_bind(); });
  26853. auto se = detail::scope_exit([&] {
  26854. svr.stop();
  26855. t.join();
  26856. });
  26857. svr.wait_until_ready();
  26858. // A header that announces one byte over the limit, and none of its payload
  26859. std::string too_big = "\x82\xff";
  26860. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26861. for (int shift = 56; shift >= 0; shift -= 8) {
  26862. too_big += static_cast<char>((len >> shift) & 0xff);
  26863. }
  26864. too_big.append(4, '\0');
  26865. const std::string protocol_error("\x03\xea"); // 1002
  26866. const std::string too_big_error("\x03\xf1"); // 1009
  26867. // What the client sends and the status the server closes with
  26868. std::vector<std::pair<std::string, std::string>> cases = {
  26869. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26870. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26871. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26872. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26873. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26874. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26875. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26876. protocol_error}, // a new message inside a fragmented one
  26877. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26878. protocol_error}, // 64-bit length with its top bit set
  26879. {too_big, too_big_error},
  26880. };
  26881. for (const auto &c : cases) {
  26882. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26883. raw_websocket_reply(port, c.first, 4));
  26884. }
  26885. }
  26886. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26887. SilentListener listener;
  26888. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26889. // A peer that completes the handshake, then sends a masked frame, which a
  26890. // server must never do, and keeps what the client sends back.
  26891. std::string reply;
  26892. std::thread peer([&]() {
  26893. auto sock = listener.accept();
  26894. if (sock == INVALID_SOCKET) { return; }
  26895. std::string req;
  26896. char c;
  26897. while (req.find("\r\n\r\n") == std::string::npos &&
  26898. ::recv(sock, &c, 1, 0) == 1) {
  26899. req += c;
  26900. }
  26901. const std::string field = "Sec-WebSocket-Key: ";
  26902. auto pos = req.find(field);
  26903. if (pos != std::string::npos) {
  26904. pos += field.size();
  26905. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26906. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26907. "Upgrade: websocket\r\n"
  26908. "Connection: Upgrade\r\n"
  26909. "Sec-WebSocket-Accept: " +
  26910. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26911. masked_frame(0x81, "a");
  26912. detail::send_socket(sock, res.data(), res.size(), 0);
  26913. // FIN + Close, masked with a length of 2, the mask key, the code
  26914. char buf[256];
  26915. while (reply.size() < 8) {
  26916. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26917. if (n <= 0) { break; }
  26918. reply.append(buf, static_cast<size_t>(n));
  26919. }
  26920. }
  26921. detail::close_socket(sock);
  26922. });
  26923. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26924. "/ws");
  26925. auto connected = static_cast<bool>(client.connect());
  26926. std::string msg;
  26927. auto r = connected ? client.read(msg) : ws::Fail;
  26928. peer.join();
  26929. ASSERT_TRUE(connected);
  26930. EXPECT_EQ(ws::Fail, r);
  26931. detail::BufferStream strm;
  26932. strm.write(reply.data(), reply.size());
  26933. ws::Opcode opcode;
  26934. std::string payload;
  26935. bool fin;
  26936. ASSERT_EQ(
  26937. ws::impl::FrameRead::Ok,
  26938. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26939. EXPECT_EQ(ws::Opcode::Close, opcode);
  26940. EXPECT_EQ(std::string("\x03\xea"), payload);
  26941. }
  26942. // What a handler sees of the peer's close once read() has failed
  26943. TEST(WebSocketTest, HandlerSeesThePeersClose) {
  26944. std::mutex m;
  26945. std::condition_variable cv;
  26946. size_t handled = 0;
  26947. uint16_t seen_status = 0;
  26948. std::string seen_reason;
  26949. Server svr;
  26950. svr.set_websocket_ping_interval(0);
  26951. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26952. std::string msg;
  26953. while (ws.read(msg)) {}
  26954. std::lock_guard<std::mutex> lock(m);
  26955. seen_status = static_cast<uint16_t>(ws.close_status());
  26956. seen_reason = ws.close_reason();
  26957. handled++;
  26958. cv.notify_one();
  26959. });
  26960. auto port = svr.bind_to_any_port("127.0.0.1");
  26961. std::thread t([&]() { svr.listen_after_bind(); });
  26962. auto se = detail::scope_exit([&] {
  26963. svr.stop();
  26964. t.join();
  26965. });
  26966. svr.wait_until_ready();
  26967. auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
  26968. const char *label) {
  26969. std::unique_lock<std::mutex> lock(m);
  26970. ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
  26971. return handled == n;
  26972. })) << label;
  26973. EXPECT_EQ(status, seen_status) << label;
  26974. EXPECT_EQ(reason, seen_reason) << label;
  26975. };
  26976. // What a raw client sends before it drops the connection
  26977. struct Case {
  26978. const char *label;
  26979. std::string sent;
  26980. uint16_t status;
  26981. std::string reason;
  26982. };
  26983. std::vector<Case> cases = {
  26984. {"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
  26985. "logout"},
  26986. {"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
  26987. {"no status", masked_frame(0x88, ""), 1005, ""},
  26988. {"malformed", masked_frame(0x88, "\x03"), 1002, ""},
  26989. {"no Close", masked_frame(0x81, "hi"), 1006, ""},
  26990. };
  26991. for (size_t i = 0; i < cases.size(); i++) {
  26992. auto sock = connect_raw_websocket(port, "/ws");
  26993. ASSERT_NE(INVALID_SOCKET, sock);
  26994. detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
  26995. detail::close_socket(sock);
  26996. expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
  26997. }
  26998. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
  26999. ASSERT_TRUE(client.connect());
  27000. client.close(static_cast<ws::CloseStatus>(4001), "logout");
  27001. expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
  27002. }
  27003. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  27004. class WebSocketSSLIntegrationTest : public ::testing::Test {
  27005. protected:
  27006. void SetUp() override {
  27007. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  27008. SERVER_PRIVATE_KEY_FILE);
  27009. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27010. std::string msg;
  27011. ws::ReadResult ret;
  27012. while ((ret = ws.read(msg))) {
  27013. if (ret == ws::Binary) {
  27014. ws.send(msg.data(), msg.size());
  27015. } else {
  27016. ws.send(msg);
  27017. }
  27018. }
  27019. });
  27020. port_ = server_->bind_to_any_port(HOST);
  27021. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27022. server_->wait_until_ready();
  27023. }
  27024. void TearDown() override {
  27025. server_->stop();
  27026. if (server_thread_.joinable()) { server_thread_.join(); }
  27027. }
  27028. std::unique_ptr<SSLServer> server_;
  27029. std::thread server_thread_;
  27030. int port_ = 0;
  27031. };
  27032. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  27033. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27034. {
  27035. ws::WebSocketClient client(url);
  27036. client.enable_server_certificate_verification(false);
  27037. auto calls = 0;
  27038. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  27039. calls++;
  27040. return false;
  27041. });
  27042. EXPECT_FALSE(client.connect());
  27043. EXPECT_GT(calls, 0);
  27044. }
  27045. {
  27046. ws::WebSocketClient client(url);
  27047. client.enable_server_certificate_verification(false);
  27048. client.set_session_verifier([](tls::session_t) {
  27049. return SSLVerifierResponse::CertificateRejected;
  27050. });
  27051. EXPECT_FALSE(client.connect());
  27052. }
  27053. {
  27054. ws::WebSocketClient client(url);
  27055. client.enable_server_certificate_verification(false);
  27056. client.set_session_verifier([](tls::session_t) {
  27057. return SSLVerifierResponse::CertificateAccepted;
  27058. });
  27059. EXPECT_TRUE(client.connect());
  27060. }
  27061. }
  27062. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  27063. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27064. "/ws-echo");
  27065. client.enable_server_certificate_verification(false);
  27066. ASSERT_TRUE(client.connect());
  27067. ASSERT_TRUE(client.is_open());
  27068. ASSERT_TRUE(client.send("Hello WSS"));
  27069. std::string msg;
  27070. EXPECT_EQ(ws::Text, client.read(msg));
  27071. EXPECT_EQ("Hello WSS", msg);
  27072. client.close();
  27073. }
  27074. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  27075. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  27076. "/ws-echo");
  27077. client.enable_server_certificate_verification(false);
  27078. EXPECT_TRUE(client.connect());
  27079. }
  27080. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  27081. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  27082. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  27083. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  27084. // client (without calling close() first) is the only path that runs
  27085. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  27086. // bug exactly.
  27087. //
  27088. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  27089. // when linked against an instrumented libssl; run under Valgrind to catch it
  27090. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  27091. // suite (the freed session otherwise stalls on the close handshake) — this test
  27092. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  27093. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  27094. {
  27095. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27096. "/ws-echo");
  27097. client.enable_server_certificate_verification(false);
  27098. client.set_read_timeout(2, 0);
  27099. client.set_write_timeout(2, 0);
  27100. ASSERT_TRUE(client.connect());
  27101. ASSERT_TRUE(client.is_open());
  27102. ASSERT_TRUE(client.send("still open"));
  27103. // Intentionally do NOT call client.close(): leaving scope runs
  27104. // shutdown_and_close() with the WebSocket still open, which must send the
  27105. // close frame while the TLS session is still alive.
  27106. }
  27107. }
  27108. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  27109. // shutdown_and_close() at the start of connect(), reproducing the same
  27110. // use-after-free within the test body rather than at scope exit. The second
  27111. // connect must succeed and echo, proving the close handshake ran over a live
  27112. // session. See the note above about memory-tool requirements.
  27113. TEST_F(WebSocketSSLIntegrationTest,
  27114. ReconnectWhileOpenSendsCloseOverLiveSession) {
  27115. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27116. "/ws-echo");
  27117. client.enable_server_certificate_verification(false);
  27118. client.set_read_timeout(2, 0);
  27119. client.set_write_timeout(2, 0);
  27120. ASSERT_TRUE(client.connect());
  27121. ASSERT_TRUE(client.is_open());
  27122. ASSERT_TRUE(client.send("still open"));
  27123. // Reconnect without closing first: connect() calls shutdown_and_close() on
  27124. // the still-open connection, which must not touch a freed TLS session.
  27125. ASSERT_TRUE(client.connect());
  27126. ASSERT_TRUE(client.is_open());
  27127. ASSERT_TRUE(client.send("after reconnect"));
  27128. std::string msg;
  27129. EXPECT_EQ(ws::Text, client.read(msg));
  27130. EXPECT_EQ("after reconnect", msg);
  27131. client.close();
  27132. }
  27133. #endif
  27134. #ifdef CPPHTTPLIB_SSL_ENABLED
  27135. class WebSocketSSLCATest : public ::testing::Test {
  27136. protected:
  27137. void SetUp() override {
  27138. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  27139. SERVER_PRIVATE_KEY_FILE);
  27140. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27141. std::string msg;
  27142. while (ws.read(msg)) {
  27143. ws.send(msg);
  27144. }
  27145. });
  27146. port_ = server_->bind_to_any_port("127.0.0.1");
  27147. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27148. server_->wait_until_ready();
  27149. }
  27150. void TearDown() override {
  27151. server_->stop();
  27152. if (server_thread_.joinable()) { server_thread_.join(); }
  27153. }
  27154. std::string url() const {
  27155. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  27156. }
  27157. std::unique_ptr<SSLServer> server_;
  27158. std::thread server_thread_;
  27159. int port_ = 0;
  27160. };
  27161. // A custom CA loaded as PEM verifies the server with full certificate
  27162. // verification enabled
  27163. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  27164. ws::WebSocketClient client(url());
  27165. std::string cert;
  27166. read_file(SERVER_CERT2_FILE, cert);
  27167. client.load_ca_cert_store(cert.c_str(), cert.size());
  27168. ASSERT_TRUE(client.connect());
  27169. ASSERT_TRUE(client.send("hello"));
  27170. std::string msg;
  27171. EXPECT_EQ(ws::Text, client.read(msg));
  27172. EXPECT_EQ("hello", msg);
  27173. client.close();
  27174. }
  27175. // A custom CA that does not cover the server must fail verification (the
  27176. // custom CA is exclusive; system certs are not loaded alongside it)
  27177. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  27178. ws::WebSocketClient client(url());
  27179. std::string cert;
  27180. read_file(CLIENT_CA_CERT_FILE, cert);
  27181. client.load_ca_cert_store(cert.c_str(), cert.size());
  27182. auto res = client.connect();
  27183. ASSERT_FALSE(res);
  27184. EXPECT_EQ(Error::SSLServerVerification, res.error());
  27185. EXPECT_EQ(-1, res.status());
  27186. EXPECT_NE(0u, res.ssl_backend_error());
  27187. }
  27188. // The same CA as a file path rather than PEM in memory
  27189. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  27190. ws::WebSocketClient client(url());
  27191. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27192. ASSERT_TRUE(client.connect());
  27193. ASSERT_TRUE(client.send("hello"));
  27194. std::string msg;
  27195. EXPECT_EQ(ws::Text, client.read(msg));
  27196. EXPECT_EQ("hello", msg);
  27197. client.close();
  27198. }
  27199. // ...and a CA file that does not cover the server still fails, so it is the
  27200. // path above that decides the outcome
  27201. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  27202. ws::WebSocketClient client(url());
  27203. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27204. ASSERT_FALSE(client.connect());
  27205. }
  27206. // Regression test: reconnecting with a native custom CA store used to reuse
  27207. // a store handle the previous TLS context had already freed (use-after-free
  27208. // under the OpenSSL backend). The context now lives as long as the client.
  27209. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  27210. ws::WebSocketClient client(url());
  27211. std::string cert;
  27212. read_file(SERVER_CERT2_FILE, cert);
  27213. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  27214. ASSERT_TRUE(client.connect());
  27215. client.close();
  27216. ASSERT_TRUE(client.connect());
  27217. ASSERT_TRUE(client.send("again"));
  27218. std::string msg;
  27219. EXPECT_EQ(ws::Text, client.read(msg));
  27220. EXPECT_EQ("again", msg);
  27221. client.close();
  27222. }
  27223. // Regression test: a certificate with a trusted chain but no identity match
  27224. // for the server IP must be rejected. The Mbed TLS backend used to skip
  27225. // verification entirely for IP hosts, so this connection succeeded there.
  27226. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  27227. // chain verification while the identity check must still fail.
  27228. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  27229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  27230. ASSERT_TRUE(svr.is_valid());
  27231. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27232. std::string msg;
  27233. while (ws.read(msg)) {
  27234. ws.send(msg);
  27235. }
  27236. });
  27237. auto port = svr.bind_to_any_port("127.0.0.1");
  27238. auto t = std::thread([&]() { svr.listen_after_bind(); });
  27239. auto se = detail::scope_exit([&] {
  27240. svr.stop();
  27241. t.join();
  27242. });
  27243. svr.wait_until_ready();
  27244. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  27245. "/echo");
  27246. std::string cert;
  27247. read_file(SERVER_CERT_FILE, cert);
  27248. client.load_ca_cert_store(cert.c_str(), cert.size());
  27249. ASSERT_FALSE(client.connect());
  27250. }
  27251. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  27252. // SNI, so nothing binds the host name to the TLS session. These bind the
  27253. // server to "localhost" instead, the only shape that exercises the SNI and
  27254. // hostname-verification path with certificate verification left enabled.
  27255. class WebSocketSSLDnsHostTest : public ::testing::Test {
  27256. protected:
  27257. void Start(const char *cert_file) {
  27258. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  27259. SERVER_PRIVATE_KEY_FILE);
  27260. ASSERT_TRUE(server_->is_valid());
  27261. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27262. std::string msg;
  27263. while (ws.read(msg)) {
  27264. ws.send(msg);
  27265. }
  27266. });
  27267. port_ = server_->bind_to_any_port("localhost");
  27268. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27269. server_->wait_until_ready();
  27270. }
  27271. void TearDown() override {
  27272. if (server_) { server_->stop(); }
  27273. if (server_thread_.joinable()) { server_thread_.join(); }
  27274. }
  27275. std::string url() const {
  27276. return "wss://localhost:" + std::to_string(port_) + "/echo";
  27277. }
  27278. std::unique_ptr<SSLServer> server_;
  27279. std::thread server_thread_;
  27280. int port_ = 0;
  27281. };
  27282. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  27283. // out and the connection is usable
  27284. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  27285. Start(SERVER_CERT2_FILE);
  27286. ws::WebSocketClient client(url());
  27287. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27288. ASSERT_TRUE(client.connect());
  27289. ASSERT_TRUE(client.send("hello"));
  27290. std::string msg;
  27291. EXPECT_EQ(ws::Text, client.read(msg));
  27292. EXPECT_EQ("hello", msg);
  27293. client.close();
  27294. }
  27295. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  27296. // while the identity check must still reject "localhost"
  27297. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  27298. Start(SERVER_CERT_FILE);
  27299. ws::WebSocketClient client(url());
  27300. client.set_ca_cert_path(SERVER_CERT_FILE);
  27301. auto res = client.connect();
  27302. ASSERT_FALSE(res);
  27303. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  27304. EXPECT_EQ(-1, res.status());
  27305. }
  27306. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  27307. // disabled: the chain is still checked, only the identity check is skipped
  27308. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  27309. Start(SERVER_CERT_FILE);
  27310. ws::WebSocketClient client(url());
  27311. client.set_ca_cert_path(SERVER_CERT_FILE);
  27312. client.enable_server_hostname_verification(false);
  27313. ASSERT_TRUE(client.connect());
  27314. ASSERT_TRUE(client.send("hello"));
  27315. std::string msg;
  27316. EXPECT_EQ(ws::Text, client.read(msg));
  27317. EXPECT_EQ("hello", msg);
  27318. client.close();
  27319. }
  27320. // A CA that did not sign the server certificate fails the chain, even though
  27321. // the name would match
  27322. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  27323. Start(SERVER_CERT2_FILE);
  27324. ws::WebSocketClient client(url());
  27325. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27326. ASSERT_FALSE(client.connect());
  27327. }
  27328. // With verification disabled, neither the chain nor the name is checked
  27329. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  27330. Start(SERVER_CERT_FILE);
  27331. ws::WebSocketClient client(url());
  27332. client.enable_server_certificate_verification(false);
  27333. ASSERT_TRUE(client.connect());
  27334. ASSERT_TRUE(client.send("hello"));
  27335. std::string msg;
  27336. EXPECT_EQ(ws::Text, client.read(msg));
  27337. EXPECT_EQ("hello", msg);
  27338. client.close();
  27339. }
  27340. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  27341. protected:
  27342. void SetUp() override {
  27343. server_ = httplib::detail::make_unique<SSLServer>(
  27344. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  27345. ASSERT_TRUE(server_->is_valid());
  27346. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27347. std::string msg;
  27348. while (ws.read(msg)) {
  27349. ws.send(msg);
  27350. }
  27351. });
  27352. port_ = server_->bind_to_any_port("localhost");
  27353. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27354. server_->wait_until_ready();
  27355. }
  27356. void TearDown() override {
  27357. server_->stop();
  27358. if (server_thread_.joinable()) { server_thread_.join(); }
  27359. }
  27360. std::string url() const {
  27361. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27362. }
  27363. void ConnectWithClientCert(const std::string &client_cert_file,
  27364. const std::string &client_private_key_file,
  27365. const char *private_key_password) {
  27366. std::string cert_pem, key_pem;
  27367. read_file(client_cert_file, cert_pem);
  27368. read_file(client_private_key_file, key_pem);
  27369. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27370. key_pem.c_str(), key_pem.size(),
  27371. private_key_password};
  27372. ConnectWithPem(pem);
  27373. }
  27374. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27375. ws::WebSocketClient client(url(), pem);
  27376. ASSERT_TRUE(client.is_valid());
  27377. client.enable_server_certificate_verification(false);
  27378. ASSERT_TRUE(client.connect());
  27379. ASSERT_TRUE(client.send("hello"));
  27380. std::string msg;
  27381. EXPECT_EQ(ws::Text, client.read(msg));
  27382. EXPECT_EQ("hello", msg);
  27383. client.close();
  27384. }
  27385. std::unique_ptr<SSLServer> server_;
  27386. std::thread server_thread_;
  27387. int port_ = 0;
  27388. };
  27389. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27390. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27391. }
  27392. // Control for the tests above: the fixture's server really does require a
  27393. // client certificate, so it is the PEM the constructor installed that decides
  27394. // the outcome.
  27395. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27396. ws::WebSocketClient client(url());
  27397. ASSERT_TRUE(client.is_valid());
  27398. client.enable_server_certificate_verification(false);
  27399. EXPECT_FALSE(client.connect());
  27400. }
  27401. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27402. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27403. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27404. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27405. }
  27406. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27407. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27408. std::string cert_pem, key_pem;
  27409. read_file(CLIENT_CERT_FILE, cert_pem);
  27410. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27411. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27412. std::vector<char> key(key_pem.begin(), key_pem.end());
  27413. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27414. key.size(), nullptr};
  27415. ConnectWithPem(pem);
  27416. }
  27417. #endif
  27418. #if !defined(_WIN32)
  27419. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27420. auto secret_dir = std::string("./symlink_test_secret");
  27421. auto served_dir = std::string("./symlink_test_served");
  27422. auto secret_file = secret_dir + "/secret.txt";
  27423. auto symlink_path = served_dir + "/escape";
  27424. // Setup: create directories and files
  27425. mkdir(secret_dir.c_str(), 0755);
  27426. mkdir(served_dir.c_str(), 0755);
  27427. {
  27428. std::ofstream ofs(secret_file);
  27429. ofs << "SECRET_DATA";
  27430. }
  27431. // Create symlink using absolute path so it resolves correctly
  27432. #ifdef PATH_MAX
  27433. char abs_secret[PATH_MAX];
  27434. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27435. #else
  27436. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27437. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27438. ASSERT_NE(nullptr, abs_secret);
  27439. #endif
  27440. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27441. auto se = detail::scope_exit([&] {
  27442. unlink(symlink_path.c_str());
  27443. unlink(secret_file.c_str());
  27444. rmdir(served_dir.c_str());
  27445. rmdir(secret_dir.c_str());
  27446. });
  27447. Server svr;
  27448. svr.set_mount_point("/", served_dir);
  27449. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27450. auto se2 = detail::scope_exit([&] {
  27451. svr.stop();
  27452. listen_thread.join();
  27453. });
  27454. svr.wait_until_ready();
  27455. Client cli("localhost", PORT);
  27456. // Symlink pointing outside base dir should be blocked
  27457. auto res = cli.Get("/escape/secret.txt");
  27458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27459. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27460. }
  27461. #else
  27462. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27463. auto secret_dir = std::string("junction_test_secret");
  27464. auto served_dir = std::string("junction_test_served");
  27465. auto secret_file = secret_dir + "\\secret.txt";
  27466. auto junction_path = served_dir + "\\escape";
  27467. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27468. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27469. {
  27470. std::ofstream ofs(secret_file);
  27471. ofs << "SECRET_DATA";
  27472. }
  27473. // A junction needs no privilege to create, unlike a symlink
  27474. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27475. ASSERT_EQ(0, std::system(cmd.c_str()));
  27476. auto se = detail::scope_exit([&] {
  27477. ::RemoveDirectoryA(junction_path.c_str());
  27478. std::remove(secret_file.c_str());
  27479. ::RemoveDirectoryA(served_dir.c_str());
  27480. ::RemoveDirectoryA(secret_dir.c_str());
  27481. });
  27482. Server svr;
  27483. svr.set_mount_point("/", served_dir);
  27484. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27485. auto se2 = detail::scope_exit([&] {
  27486. svr.stop();
  27487. listen_thread.join();
  27488. });
  27489. svr.wait_until_ready();
  27490. Client cli("localhost", PORT);
  27491. // Junction pointing outside base dir should be blocked
  27492. auto res = cli.Get("/escape/secret.txt");
  27493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27494. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27495. }
  27496. #endif
  27497. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27498. // "GET /smuggled" request), reads the first response, and only then sends the
  27499. // embedded request as the body. Returns how many times /smuggled ran.
  27500. //
  27501. // The body is sent AFTER receiving the first response (as in the original
  27502. // PoC) so that the stream_line_reader cannot buffer it together with the
  27503. // headers of the first request.
  27504. static int count_smuggled_requests(const std::string &outer_head,
  27505. std::string &first_response) {
  27506. Server svr;
  27507. svr.set_mount_point("/", "./www");
  27508. std::atomic<int> smuggled_count(0);
  27509. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27510. smuggled_count++;
  27511. res.set_content("oops", "text/plain");
  27512. });
  27513. svr.Post("/post", [&](const Request &req, Response &res) {
  27514. res.set_content(req.body, "text/plain");
  27515. });
  27516. auto port = svr.bind_to_any_port("localhost");
  27517. thread t = thread([&] { svr.listen_after_bind(); });
  27518. auto se = detail::scope_exit([&] {
  27519. svr.stop();
  27520. t.join();
  27521. });
  27522. svr.wait_until_ready();
  27523. auto error = Error::Success;
  27524. auto sock = detail::create_client_socket(
  27525. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27526. /*connection_timeout_sec=*/2, 0,
  27527. /*read_timeout_sec=*/2, 0,
  27528. /*write_timeout_sec=*/2, 0, std::string(), error);
  27529. EXPECT_NE(INVALID_SOCKET, sock);
  27530. if (sock == INVALID_SOCKET) { return -1; }
  27531. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27532. // The "smuggled" request will be sent as the body of the outer request
  27533. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27534. "Host: localhost\r\n"
  27535. "Connection: close\r\n"
  27536. "\r\n";
  27537. auto head = outer_head;
  27538. auto len = std::to_string(smuggled.size());
  27539. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27540. pos = head.find("{len}", pos + len.size())) {
  27541. head.replace(pos, 5, len);
  27542. }
  27543. // Step 1: Send only the outer request headers (no body yet)
  27544. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27545. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27546. // Step 2: Read the first response
  27547. char buf[4096];
  27548. for (;;) {
  27549. auto n = recv(sock, buf, sizeof(buf), 0);
  27550. if (n <= 0) break;
  27551. first_response.append(buf, static_cast<size_t>(n));
  27552. // Stop once we have a complete response (headers + body)
  27553. auto hdr_end = first_response.find("\r\n\r\n");
  27554. if (hdr_end != std::string::npos) {
  27555. // Check for Content-Length to know when the body is complete
  27556. auto cl_pos = first_response.find("Content-Length:");
  27557. if (cl_pos != std::string::npos) {
  27558. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27559. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27560. auto cl = std::stoul(
  27561. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27562. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27563. } else {
  27564. break; // No Content-Length, assume headers-only response
  27565. }
  27566. }
  27567. }
  27568. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27569. // vulnerable server the keep-alive loop reads this as a second request. The
  27570. // server may already have closed the connection, so the result is ignored.
  27571. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27572. // Half-close so that a server which drained the body sees EOF and closes,
  27573. // instead of the read below waiting for the read timeout.
  27574. #ifdef _WIN32
  27575. ::shutdown(sock, SD_SEND);
  27576. #else
  27577. ::shutdown(sock, SHUT_WR);
  27578. #endif
  27579. // Step 4: Read until the server closes the connection
  27580. for (;;) {
  27581. auto n = recv(sock, buf, sizeof(buf), 0);
  27582. if (n <= 0) break;
  27583. }
  27584. return smuggled_count.load();
  27585. }
  27586. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27587. // A GET request with Content-Length to a static file handler must have its
  27588. // body drained before the keep-alive connection is reused. Otherwise the
  27589. // unread body bytes are interpreted as the next HTTP request.
  27590. std::string first_response;
  27591. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27592. "Host: localhost\r\n"
  27593. "Content-Length: {len}\r\n"
  27594. "\r\n",
  27595. first_response));
  27596. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27597. }
  27598. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27599. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27600. // be answered with 400 and the connection closed. Treating it as "no body"
  27601. // leaves the body to be parsed as the next request.
  27602. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27603. const char *targets[] = {
  27604. "GET /file", // handler that never reads the body
  27605. "GET /not-found", // no handler matches (404)
  27606. "POST /post", // handler that reads the body
  27607. };
  27608. for (auto target : targets) {
  27609. for (auto value : values) {
  27610. std::string first_response;
  27611. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27612. " HTTP/1.1\r\n"
  27613. "Host: localhost\r\n"
  27614. "Content-Length: " +
  27615. value + "\r\n\r\n",
  27616. first_response))
  27617. << target << " with Content-Length: " << value;
  27618. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27619. << target << " with Content-Length: " << value;
  27620. }
  27621. }
  27622. }
  27623. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27624. // A 400 for an unparseable request line leaves the rest of the message
  27625. // unread, so the connection must be closed rather than reused.
  27626. std::string first_response;
  27627. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27628. "Host: localhost\r\n"
  27629. "Content-Length: {len}\r\n"
  27630. "\r\n",
  27631. first_response));
  27632. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27633. }
  27634. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27635. // Same as above for a header block that fails to parse.
  27636. std::string first_response;
  27637. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27638. "Host: localhost\r\n"
  27639. "Bad Header\r\n"
  27640. "Content-Length: {len}\r\n"
  27641. "\r\n",
  27642. first_response));
  27643. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27644. }
  27645. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27646. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27647. // server must not read another request on that connection, even when the
  27648. // request had no body to drain.
  27649. std::string first_response;
  27650. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27651. "Host: localhost\r\n"
  27652. "\r\n",
  27653. first_response));
  27654. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27655. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27656. }
  27657. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27658. // A content reader that stops early leaves the stream inside the body.
  27659. // Draining the whole Content-Length from there, or reading the body again,
  27660. // reads into the next request, and whatever follows is parsed as a request
  27661. // of its own.
  27662. Server svr;
  27663. std::atomic<int> smuggled_count(0);
  27664. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27665. svr.Post("/upload", [](const Request &req, Response &res,
  27666. const ContentReader &content_reader) {
  27667. // Stop at the last chunk, so the whole body has been read however it
  27668. // arrives.
  27669. auto length = req.get_header_value_u64("Content-Length");
  27670. size_t total = 0;
  27671. auto consumed = content_reader([&](const char *, size_t n) {
  27672. total += n;
  27673. return total < length;
  27674. });
  27675. EXPECT_FALSE(consumed);
  27676. if (req.has_param("retry")) {
  27677. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27678. }
  27679. // Replace the 400 the aborted read set, which would close the connection.
  27680. res.set_redirect("/done");
  27681. });
  27682. auto port = svr.bind_to_any_port(HOST);
  27683. thread t = thread([&] { svr.listen_after_bind(); });
  27684. auto se = detail::scope_exit([&] {
  27685. svr.stop();
  27686. t.join();
  27687. });
  27688. svr.wait_until_ready();
  27689. // A front end sees the second request as a POST whose body is the GET. The
  27690. // first body is as long as the POST's headers, so draining it again reads
  27691. // exactly those and leaves the GET to be parsed next.
  27692. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27693. "Host: localhost\r\n"
  27694. "\r\n";
  27695. std::string second_head = "POST /post HTTP/1.1\r\n"
  27696. "Host: localhost\r\n"
  27697. "Content-Length: " +
  27698. std::to_string(inner.size()) +
  27699. "\r\n"
  27700. "\r\n";
  27701. for (auto target : {"/upload", "/upload?retry"}) {
  27702. smuggled_count = 0;
  27703. std::string request = "POST " + std::string(target) +
  27704. " HTTP/1.1\r\n"
  27705. "Host: localhost\r\n"
  27706. "Content-Length: " +
  27707. std::to_string(second_head.size()) +
  27708. "\r\n"
  27709. "\r\n" +
  27710. std::string(second_head.size(), 'A') + second_head +
  27711. inner;
  27712. std::string response;
  27713. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27714. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27715. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27716. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27717. EXPECT_EQ(0, smuggled_count.load()) << target;
  27718. }
  27719. }
  27720. // An error response closes the connection anyway, so the body is left unread
  27721. // with a redirect, such as one to a login page.
  27722. static void serve_redirects(Server &svr,
  27723. const std::function<void(int)> &client) {
  27724. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27725. res.set_redirect("/login");
  27726. return Server::HandlerResponse::Handled;
  27727. });
  27728. auto port = svr.bind_to_any_port(HOST);
  27729. ASSERT_GT(port, 0);
  27730. thread t = thread([&] { svr.listen_after_bind(); });
  27731. auto se = detail::scope_exit([&] {
  27732. svr.stop();
  27733. t.join();
  27734. ASSERT_FALSE(svr.is_running());
  27735. });
  27736. svr.wait_until_ready();
  27737. client(port);
  27738. }
  27739. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27740. Server svr;
  27741. serve_redirects(svr, [](int port) {
  27742. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27743. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27744. std::to_string(body.size()) + "\r\n\r\n" + body +
  27745. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27746. std::string resp;
  27747. ASSERT_TRUE(send_request(1, req, &resp, port));
  27748. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27749. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27750. });
  27751. }
  27752. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27753. Server svr;
  27754. svr.set_read_timeout(0, 200000);
  27755. serve_redirects(svr, [](int port) {
  27756. // A byte every 100 ms keeps each read within the read timeout, but not the
  27757. // body as a whole, so the server closes and the bytes sent after that fail.
  27758. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27759. "Content-Length: 10\r\n\r\n"};
  27760. parts.resize(11, "x");
  27761. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27762. });
  27763. }
  27764. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27765. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27766. // must be rejected with 400 Bad Request.
  27767. Server svr;
  27768. svr.Post("/test", [&](const Request &, Response &res) {
  27769. res.set_content("ok", "text/plain");
  27770. });
  27771. thread t = thread([&] { svr.listen(HOST, PORT); });
  27772. auto se = detail::scope_exit([&] {
  27773. svr.stop();
  27774. t.join();
  27775. ASSERT_FALSE(svr.is_running());
  27776. });
  27777. svr.wait_until_ready();
  27778. // Exact "chunked"
  27779. {
  27780. auto req = "POST /test HTTP/1.1\r\n"
  27781. "Host: localhost\r\n"
  27782. "Content-Length: 5\r\n"
  27783. "Transfer-Encoding: chunked\r\n"
  27784. "Connection: close\r\n"
  27785. "\r\n"
  27786. "hello";
  27787. std::string response;
  27788. ASSERT_TRUE(send_request(1, req, &response));
  27789. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27790. response.substr(0, response.find("\r\n")));
  27791. }
  27792. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27793. {
  27794. auto req = "POST /test HTTP/1.1\r\n"
  27795. "Host: localhost\r\n"
  27796. "Content-Length: 5\r\n"
  27797. "Transfer-Encoding: gzip, chunked\r\n"
  27798. "Connection: close\r\n"
  27799. "\r\n"
  27800. "hello";
  27801. std::string response;
  27802. ASSERT_TRUE(send_request(1, req, &response));
  27803. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27804. response.substr(0, response.find("\r\n")));
  27805. }
  27806. }
  27807. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27808. Server svr;
  27809. svr.Post("/test", [&](const Request &, Response &res) {
  27810. res.set_content("ok", "text/plain");
  27811. });
  27812. thread t = thread([&] { svr.listen(HOST, PORT); });
  27813. auto se = detail::scope_exit([&] {
  27814. svr.stop();
  27815. t.join();
  27816. ASSERT_FALSE(svr.is_running());
  27817. });
  27818. svr.wait_until_ready();
  27819. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27820. // length cannot be determined, so the server must answer 400 and close
  27821. // rather than treat the request as bodyless and leave the body in the
  27822. // socket for the next request to pick up.
  27823. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27824. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27825. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27826. std::string response;
  27827. ASSERT_TRUE(send_request(1, req, &response));
  27828. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27829. response.substr(0, response.find("\r\n")))
  27830. << transfer_encoding;
  27831. }
  27832. // RFC 9110 5.3: the codings may also be split across several
  27833. // Transfer-Encoding lines, which combine in the order they were received.
  27834. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27835. // just like the single-line "chunked, gzip" above.
  27836. {
  27837. auto req = "POST /test HTTP/1.1\r\n"
  27838. "Host: localhost\r\n"
  27839. "Transfer-Encoding: chunked\r\n"
  27840. "Transfer-Encoding: gzip\r\n"
  27841. "\r\n"
  27842. "0\r\n\r\n";
  27843. std::string response;
  27844. ASSERT_TRUE(send_request(1, req, &response));
  27845. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27846. response.substr(0, response.find("\r\n")));
  27847. }
  27848. }
  27849. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27850. Server svr;
  27851. svr.Post("/test", [&](const Request &, Response &res) {
  27852. res.set_content("ok", "text/plain");
  27853. });
  27854. auto port = svr.bind_to_any_port(HOST);
  27855. ASSERT_GT(port, 0);
  27856. thread t = thread([&] { svr.listen_after_bind(); });
  27857. auto se = detail::scope_exit([&] {
  27858. svr.stop();
  27859. t.join();
  27860. ASSERT_FALSE(svr.is_running());
  27861. });
  27862. svr.wait_until_ready();
  27863. for (auto transfer_encoding :
  27864. {"Transfer-Encoding: gzip, chunked\r\n",
  27865. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27866. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27867. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27868. transfer_encoding + "\r\n0\r\n\r\n";
  27869. std::string response;
  27870. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27871. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27872. response.substr(0, response.find("\r\n")))
  27873. << transfer_encoding;
  27874. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27875. << transfer_encoding;
  27876. }
  27877. }
  27878. // Regression for issue #2450: a DELETE without Content-Length on a
  27879. // keep-alive connection must not let the post-response drain consume the
  27880. // next request's bytes.
  27881. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27882. Server svr;
  27883. std::atomic<int> delete_count(0);
  27884. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27885. delete_count++;
  27886. res.status = StatusCode::NoContent_204;
  27887. });
  27888. auto port = svr.bind_to_any_port(HOST);
  27889. thread t = thread([&] { svr.listen_after_bind(); });
  27890. auto se = detail::scope_exit([&] {
  27891. svr.stop();
  27892. t.join();
  27893. });
  27894. svr.wait_until_ready();
  27895. auto error = Error::Success;
  27896. auto sock = detail::create_client_socket(
  27897. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27898. /*connection_timeout_sec=*/2, 0,
  27899. /*read_timeout_sec=*/2, 0,
  27900. /*write_timeout_sec=*/2, 0, std::string(), error);
  27901. ASSERT_NE(INVALID_SOCKET, sock);
  27902. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27903. auto send_request_and_read_response = [&](const std::string &req,
  27904. std::string &out) -> bool {
  27905. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27906. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27907. char buf[4096];
  27908. for (;;) {
  27909. auto n = recv(sock, buf, sizeof(buf), 0);
  27910. if (n <= 0) { return !out.empty(); }
  27911. out.append(buf, static_cast<size_t>(n));
  27912. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27913. }
  27914. };
  27915. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27916. "Host: localhost\r\n"
  27917. "\r\n";
  27918. std::string resp1;
  27919. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27920. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27921. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27922. "Host: localhost\r\n"
  27923. "Connection: close\r\n"
  27924. "\r\n";
  27925. std::string resp2;
  27926. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27927. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27928. EXPECT_EQ(2, delete_count.load());
  27929. }
  27930. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27931. Server svr;
  27932. svr.Post("/ingest", [&](const Request &, Response &res,
  27933. const ContentReader &content_reader) {
  27934. auto consumed = content_reader([](const char *, size_t) { return false; });
  27935. EXPECT_FALSE(consumed);
  27936. res.status = StatusCode::Conflict_409;
  27937. res.set_header("Connection", "close");
  27938. });
  27939. auto port = svr.bind_to_any_port(HOST);
  27940. thread t = thread([&] { svr.listen_after_bind(); });
  27941. auto se = detail::scope_exit([&] {
  27942. svr.stop();
  27943. t.join();
  27944. });
  27945. svr.wait_until_ready();
  27946. auto error = Error::Success;
  27947. auto sock = detail::create_client_socket(
  27948. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27949. /*connection_timeout_sec=*/2, 0,
  27950. /*read_timeout_sec=*/1, 0,
  27951. /*write_timeout_sec=*/2, 0, std::string(), error);
  27952. ASSERT_NE(INVALID_SOCKET, sock);
  27953. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27954. std::string request = "POST /ingest HTTP/1.1\r\n"
  27955. "Host: localhost\r\n"
  27956. "Transfer-Encoding: chunked\r\n"
  27957. "\r\n"
  27958. "4\r\n"
  27959. "data\r\n";
  27960. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27961. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27962. std::string response;
  27963. ssize_t received = 0;
  27964. do {
  27965. char buf[4096];
  27966. received = recv(sock, buf, sizeof(buf), 0);
  27967. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27968. } while (received > 0);
  27969. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27970. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27971. EXPECT_EQ(0, received);
  27972. }
  27973. namespace no_proxy_test {
  27974. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27975. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27976. // calling listen().
  27977. class ScopedServer {
  27978. public:
  27979. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27980. ~ScopedServer() {
  27981. svr_.stop();
  27982. if (th_.joinable()) { th_.join(); }
  27983. }
  27984. Server &svr() { return svr_; }
  27985. int port() const { return port_; }
  27986. void listen() {
  27987. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27988. svr_.wait_until_ready();
  27989. }
  27990. private:
  27991. Server svr_;
  27992. std::thread th_;
  27993. int port_ = 0;
  27994. };
  27995. class ProxyAndTargetServers {
  27996. public:
  27997. ProxyAndTargetServers() {
  27998. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27999. proxy_hits_++;
  28000. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  28001. res.set_content("via-proxy", "text/plain");
  28002. });
  28003. target_.Get(".*", [this](const Request &req, Response &res) {
  28004. target_hits_++;
  28005. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  28006. res.set_content("direct", "text/plain");
  28007. });
  28008. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  28009. target_port_ = target_.bind_to_any_port("127.0.0.1");
  28010. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  28011. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  28012. proxy_mock_.wait_until_ready();
  28013. target_.wait_until_ready();
  28014. }
  28015. ~ProxyAndTargetServers() {
  28016. proxy_mock_.stop();
  28017. target_.stop();
  28018. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  28019. if (target_thread_.joinable()) { target_thread_.join(); }
  28020. }
  28021. Server &proxy_mock() { return proxy_mock_; }
  28022. Server &target() { return target_; }
  28023. int proxy_port() const { return proxy_port_; }
  28024. int target_port() const { return target_port_; }
  28025. int proxy_hits() const { return proxy_hits_.load(); }
  28026. int target_hits() const { return target_hits_.load(); }
  28027. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  28028. void reset_counters() {
  28029. proxy_hits_ = 0;
  28030. target_hits_ = 0;
  28031. last_had_proxy_authz_ = false;
  28032. }
  28033. private:
  28034. Server proxy_mock_;
  28035. Server target_;
  28036. std::thread proxy_thread_;
  28037. std::thread target_thread_;
  28038. int proxy_port_ = 0;
  28039. int target_port_ = 0;
  28040. std::atomic<int> proxy_hits_{0};
  28041. std::atomic<int> target_hits_{0};
  28042. std::atomic<bool> last_had_proxy_authz_{false};
  28043. };
  28044. inline std::unique_ptr<Client> make_client(const std::string &host,
  28045. ProxyAndTargetServers &s) {
  28046. auto cli = detail::make_unique<Client>(host, s.target_port());
  28047. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  28048. cli->set_proxy("127.0.0.1", s.proxy_port());
  28049. return cli;
  28050. }
  28051. } // namespace no_proxy_test
  28052. using no_proxy_test::make_client;
  28053. using no_proxy_test::ProxyAndTargetServers;
  28054. // A stream request carries the credentials a buffered request does
  28055. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  28056. no_proxy_test::ScopedServer origin;
  28057. origin.svr().Get("/x", [](const Request &req, Response &res) {
  28058. res.set_content(req.get_header_value("Authorization"), "text/plain");
  28059. });
  28060. origin.listen();
  28061. Client cli("127.0.0.1", origin.port());
  28062. cli.set_basic_auth("user", "pass");
  28063. auto handle = cli.open_stream("GET", "/x");
  28064. ASSERT_TRUE(handle.is_valid());
  28065. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  28066. Client bearer("127.0.0.1", origin.port());
  28067. bearer.set_bearer_token_auth("tok");
  28068. auto handle2 = bearer.open_stream("GET", "/x");
  28069. ASSERT_TRUE(handle2.is_valid());
  28070. EXPECT_EQ("Bearer tok", read_all(handle2));
  28071. }
  28072. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  28073. // takes its own credentials, as for a buffered request
  28074. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  28075. std::string target, authz, proxy_authz;
  28076. no_proxy_test::ScopedServer proxy;
  28077. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  28078. target = req.target;
  28079. authz = req.get_header_value("Authorization");
  28080. proxy_authz = req.get_header_value("Proxy-Authorization");
  28081. res.set_content("ok", "text/plain");
  28082. });
  28083. proxy.listen();
  28084. Client cli("origin.example", 8080);
  28085. cli.set_proxy("127.0.0.1", proxy.port());
  28086. cli.set_proxy_basic_auth("puser", "ppass");
  28087. cli.set_basic_auth("user", "pass");
  28088. auto handle = cli.open_stream("GET", "/x");
  28089. ASSERT_TRUE(handle.is_valid());
  28090. EXPECT_EQ("ok", read_all(handle));
  28091. EXPECT_EQ("http://origin.example:8080/x", target);
  28092. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  28093. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  28094. }
  28095. // In absolute-form the path follows the authority, so a path that does not
  28096. // begin with '/' would make the proxy connect to another host
  28097. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  28098. std::vector<std::string> targets;
  28099. no_proxy_test::ScopedServer proxy;
  28100. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  28101. targets.push_back(req.target);
  28102. res.set_content("ok", "text/plain");
  28103. });
  28104. proxy.listen();
  28105. Client cli("origin.example", 8080);
  28106. cli.set_proxy("127.0.0.1", proxy.port());
  28107. cli.set_basic_auth("user", "pass");
  28108. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  28109. auto res = cli.Get(path);
  28110. EXPECT_FALSE(res) << path;
  28111. auto handle = cli.open_stream("GET", path);
  28112. EXPECT_FALSE(handle.is_valid()) << path;
  28113. }
  28114. EXPECT_TRUE(targets.empty());
  28115. auto res = cli.Get("/x");
  28116. ASSERT_TRUE(res);
  28117. ASSERT_EQ(1u, targets.size());
  28118. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  28119. }
  28120. TEST(NoProxyTest, ExactHostnameBypasses) {
  28121. ProxyAndTargetServers s;
  28122. auto cli = make_client("example.com", s);
  28123. cli->set_no_proxy({"example.com"});
  28124. auto res = cli->Get("/");
  28125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28126. EXPECT_EQ(0, s.proxy_hits());
  28127. EXPECT_EQ(1, s.target_hits());
  28128. }
  28129. TEST(NoProxyTest, SubdomainBypasses) {
  28130. ProxyAndTargetServers s;
  28131. auto cli = make_client("foo.example.com", s);
  28132. cli->set_no_proxy({"example.com"});
  28133. auto res = cli->Get("/");
  28134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28135. EXPECT_EQ(0, s.proxy_hits());
  28136. EXPECT_EQ(1, s.target_hits());
  28137. }
  28138. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  28139. // Regression guard: "evilexample.com" must not be considered a subdomain
  28140. // of "example.com". Without the dot-boundary rule, a naive endsWith
  28141. // check would let traffic bypass the proxy and leak credentials direct
  28142. // to the attacker host.
  28143. ProxyAndTargetServers s;
  28144. auto cli = make_client("evilexample.com", s);
  28145. cli->set_no_proxy({"example.com"});
  28146. auto res = cli->Get("/");
  28147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28148. EXPECT_GE(s.proxy_hits(), 1);
  28149. EXPECT_EQ(0, s.target_hits());
  28150. }
  28151. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  28152. ProxyAndTargetServers s;
  28153. auto cli = make_client("example.com.evil.com", s);
  28154. cli->set_no_proxy({"example.com"});
  28155. auto res = cli->Get("/");
  28156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28157. EXPECT_GE(s.proxy_hits(), 1);
  28158. EXPECT_EQ(0, s.target_hits());
  28159. }
  28160. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  28161. ProxyAndTargetServers s;
  28162. auto cli = make_client("example.com", s);
  28163. cli->set_no_proxy({".example.com"});
  28164. auto res = cli->Get("/");
  28165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28166. EXPECT_EQ(0, s.proxy_hits());
  28167. EXPECT_EQ(1, s.target_hits());
  28168. }
  28169. TEST(NoProxyTest, CaseInsensitiveHostname) {
  28170. ProxyAndTargetServers s;
  28171. auto cli = make_client("Example.COM", s);
  28172. cli->set_no_proxy({"EXAMPLE.com"});
  28173. auto res = cli->Get("/");
  28174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28175. EXPECT_EQ(0, s.proxy_hits());
  28176. EXPECT_EQ(1, s.target_hits());
  28177. }
  28178. TEST(NoProxyTest, TrailingDotIsNormalized) {
  28179. ProxyAndTargetServers s;
  28180. auto cli = make_client("example.com.", s);
  28181. cli->set_no_proxy({"example.com"});
  28182. auto res = cli->Get("/");
  28183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28184. EXPECT_EQ(0, s.proxy_hits());
  28185. EXPECT_EQ(1, s.target_hits());
  28186. }
  28187. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  28188. // Trailing dots must be normalized on BOTH sides — host and entry.
  28189. // An implementation that only strips the host-side trailing dot would
  28190. // fail to match host "example.com" against entry "example.com." because
  28191. // a literal substring search would compare 11 chars against 12.
  28192. ProxyAndTargetServers s;
  28193. auto cli = make_client("example.com", s);
  28194. cli->set_no_proxy({"example.com."});
  28195. auto res = cli->Get("/");
  28196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28197. EXPECT_EQ(0, s.proxy_hits());
  28198. EXPECT_EQ(1, s.target_hits());
  28199. }
  28200. TEST(NoProxyTest, WildcardBypassesEverything) {
  28201. ProxyAndTargetServers s;
  28202. auto cli = make_client("anything.invalid.test", s);
  28203. cli->set_no_proxy({"*"});
  28204. auto res = cli->Get("/");
  28205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28206. EXPECT_EQ(0, s.proxy_hits());
  28207. EXPECT_EQ(1, s.target_hits());
  28208. }
  28209. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  28210. ProxyAndTargetServers s;
  28211. Client cli("127.0.0.1", s.target_port());
  28212. cli.set_proxy("127.0.0.1", s.proxy_port());
  28213. cli.set_no_proxy({"127.0.0.1"});
  28214. auto res = cli.Get("/");
  28215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28216. EXPECT_EQ(0, s.proxy_hits());
  28217. EXPECT_EQ(1, s.target_hits());
  28218. }
  28219. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  28220. ProxyAndTargetServers s;
  28221. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  28222. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  28223. cli.set_proxy("127.0.0.1", s.proxy_port());
  28224. cli.set_no_proxy({"::1"});
  28225. auto res = cli.Get("/");
  28226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28227. EXPECT_EQ(0, s.proxy_hits());
  28228. EXPECT_EQ(1, s.target_hits());
  28229. }
  28230. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  28231. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  28232. // must still be recognized as IPv6 for CIDR matching. Implementations
  28233. // that detect IPv6 only when the host begins with '[' would parse the
  28234. // host as a hostname and miss the match.
  28235. ProxyAndTargetServers s;
  28236. Client cli("fe80::1", s.target_port());
  28237. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28238. cli.set_proxy("127.0.0.1", s.proxy_port());
  28239. cli.set_no_proxy({"fe80::/10"});
  28240. auto res = cli.Get("/");
  28241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28242. EXPECT_EQ(0, s.proxy_hits());
  28243. EXPECT_EQ(1, s.target_hits());
  28244. }
  28245. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  28246. ProxyAndTargetServers s;
  28247. Client cli("::1", s.target_port());
  28248. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  28249. cli.set_proxy("127.0.0.1", s.proxy_port());
  28250. cli.set_no_proxy({"[::1]"});
  28251. auto res = cli.Get("/");
  28252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28253. EXPECT_EQ(0, s.proxy_hits());
  28254. EXPECT_EQ(1, s.target_hits());
  28255. }
  28256. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  28257. ProxyAndTargetServers s;
  28258. Client cli("fe80::1", s.target_port());
  28259. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28260. cli.set_proxy("127.0.0.1", s.proxy_port());
  28261. cli.set_no_proxy({"[fe80::]/10"});
  28262. auto res = cli.Get("/");
  28263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28264. EXPECT_EQ(0, s.proxy_hits());
  28265. EXPECT_EQ(1, s.target_hits());
  28266. }
  28267. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  28268. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  28269. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  28270. // tricks via address-family conversion.
  28271. ProxyAndTargetServers s;
  28272. Client cli("::ffff:127.0.0.1", s.target_port());
  28273. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  28274. cli.set_proxy("127.0.0.1", s.proxy_port());
  28275. cli.set_no_proxy({"127.0.0.1"});
  28276. auto res = cli.Get("/");
  28277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28278. EXPECT_GE(s.proxy_hits(), 1);
  28279. EXPECT_EQ(0, s.target_hits());
  28280. }
  28281. TEST(NoProxyTest, IPv4CidrMatch) {
  28282. ProxyAndTargetServers s;
  28283. Client cli("127.0.0.1", s.target_port());
  28284. cli.set_proxy("127.0.0.1", s.proxy_port());
  28285. cli.set_no_proxy({"127.0.0.0/8"});
  28286. auto res = cli.Get("/");
  28287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28288. EXPECT_EQ(0, s.proxy_hits());
  28289. EXPECT_EQ(1, s.target_hits());
  28290. }
  28291. TEST(NoProxyTest, IPv4CidrNonMatch) {
  28292. ProxyAndTargetServers s;
  28293. Client cli("127.0.0.1", s.target_port());
  28294. cli.set_proxy("127.0.0.1", s.proxy_port());
  28295. cli.set_no_proxy({"10.0.0.0/8"});
  28296. auto res = cli.Get("/");
  28297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28298. EXPECT_GE(s.proxy_hits(), 1);
  28299. EXPECT_EQ(0, s.target_hits());
  28300. }
  28301. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  28302. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  28303. // IPv4 target matches.
  28304. ProxyAndTargetServers s;
  28305. Client cli("127.0.0.1", s.target_port());
  28306. cli.set_proxy("127.0.0.1", s.proxy_port());
  28307. cli.set_no_proxy({"0.0.0.0/0"});
  28308. auto res = cli.Get("/");
  28309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28310. EXPECT_EQ(0, s.proxy_hits());
  28311. EXPECT_EQ(1, s.target_hits());
  28312. }
  28313. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  28314. ProxyAndTargetServers s;
  28315. Client cli("127.0.0.1", s.target_port());
  28316. cli.set_proxy("127.0.0.1", s.proxy_port());
  28317. cli.set_no_proxy({"127.0.0.1"});
  28318. auto res = cli.Get("/");
  28319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28320. EXPECT_EQ(0, s.proxy_hits());
  28321. EXPECT_EQ(1, s.target_hits());
  28322. }
  28323. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  28324. ProxyAndTargetServers s;
  28325. Client cli("127.0.0.1", s.target_port());
  28326. cli.set_proxy("127.0.0.1", s.proxy_port());
  28327. cli.set_no_proxy({"127.0.0.0/33"});
  28328. auto res = cli.Get("/");
  28329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28330. EXPECT_GE(s.proxy_hits(), 1);
  28331. EXPECT_EQ(0, s.target_hits());
  28332. }
  28333. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  28334. // Empty prefix after the slash must be rejected, not silently treated as /32.
  28335. ProxyAndTargetServers s;
  28336. Client cli("127.0.0.1", s.target_port());
  28337. cli.set_proxy("127.0.0.1", s.proxy_port());
  28338. cli.set_no_proxy({"127.0.0.1/"});
  28339. auto res = cli.Get("/");
  28340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28341. EXPECT_GE(s.proxy_hits(), 1);
  28342. EXPECT_EQ(0, s.target_hits());
  28343. }
  28344. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  28345. ProxyAndTargetServers s;
  28346. auto cli = make_client("internal.corp", s);
  28347. cli->set_proxy_basic_auth("u", "p");
  28348. cli->set_no_proxy({"internal.corp"});
  28349. auto res = cli->Get("/");
  28350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28351. EXPECT_EQ(1, s.target_hits());
  28352. EXPECT_EQ(0, s.proxy_hits());
  28353. EXPECT_FALSE(s.last_had_proxy_authz())
  28354. << "Proxy-Authorization must not be sent direct to the target";
  28355. }
  28356. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  28357. ProxyAndTargetServers s;
  28358. auto cli = make_client("public.example", s);
  28359. cli->set_proxy_basic_auth("u", "p");
  28360. cli->set_no_proxy({"internal.corp"}); // does not match
  28361. auto res = cli->Get("/");
  28362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28363. EXPECT_GE(s.proxy_hits(), 1);
  28364. EXPECT_TRUE(s.last_had_proxy_authz());
  28365. }
  28366. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28367. std::atomic<int> hits{0};
  28368. std::atomic<int> hits_with_authz{0};
  28369. no_proxy_test::ScopedServer proxy_mock;
  28370. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28371. hits++;
  28372. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28373. if (req.target.find("/redir") != std::string::npos) {
  28374. res.set_redirect("http://other.example/landed");
  28375. } else {
  28376. res.set_content("via-proxy", "text/plain");
  28377. }
  28378. });
  28379. proxy_mock.listen();
  28380. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28381. hits = 0;
  28382. hits_with_authz = 0;
  28383. Client cli("public.example", 80);
  28384. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28385. cli.set_proxy_basic_auth(c.first, c.second);
  28386. cli.set_follow_location(true);
  28387. // The redirect to another host goes through the proxy as well
  28388. auto res = cli.Get("/redir");
  28389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28390. EXPECT_EQ(2, hits.load());
  28391. EXPECT_EQ(2, hits_with_authz.load());
  28392. }
  28393. }
  28394. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28395. ProxyAndTargetServers s;
  28396. auto cli = make_client("anything.test", s);
  28397. auto res = cli->Get("/");
  28398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28399. EXPECT_GE(s.proxy_hits(), 1);
  28400. EXPECT_EQ(0, s.target_hits());
  28401. }
  28402. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28403. ProxyAndTargetServers s;
  28404. auto cli = make_client("example.com", s);
  28405. cli->set_no_proxy({"example.com:8080"});
  28406. auto res = cli->Get("/");
  28407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28408. EXPECT_GE(s.proxy_hits(), 1);
  28409. EXPECT_EQ(0, s.target_hits());
  28410. }
  28411. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28412. ProxyAndTargetServers s;
  28413. auto cli = make_client("anything.test", s);
  28414. cli->set_no_proxy({"", " ", "\t"});
  28415. auto res = cli->Get("/");
  28416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28417. EXPECT_GE(s.proxy_hits(), 1);
  28418. EXPECT_EQ(0, s.target_hits());
  28419. }
  28420. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28421. // An entry with leading/trailing whitespace must still match — env-style
  28422. // values are commonly pasted with stray spaces and an implementation
  28423. // that feeds the raw token directly to inet_pton would fail to match
  28424. // valid CIDRs because of the spaces.
  28425. ProxyAndTargetServers s;
  28426. Client cli("127.0.0.1", s.target_port());
  28427. cli.set_proxy("127.0.0.1", s.proxy_port());
  28428. cli.set_no_proxy({" 127.0.0.0/8 "});
  28429. auto res = cli.Get("/");
  28430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28431. EXPECT_EQ(0, s.proxy_hits());
  28432. EXPECT_EQ(1, s.target_hits());
  28433. }
  28434. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28435. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28436. // go direct and must NOT carry Proxy-Authorization.
  28437. std::atomic<int> proxy_hits{0};
  28438. std::atomic<int> target_hits{0};
  28439. std::atomic<bool> target_saw_authz{false};
  28440. no_proxy_test::ScopedServer proxy_mock, target;
  28441. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28442. proxy_hits++;
  28443. res.status = 302;
  28444. res.set_header("Location", "http://127.0.0.1:" +
  28445. std::to_string(target.port()) + "/landed");
  28446. });
  28447. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28448. target_hits++;
  28449. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28450. res.set_content("direct", "text/plain");
  28451. });
  28452. proxy_mock.listen();
  28453. target.listen();
  28454. Client cli("public.example", target.port());
  28455. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28456. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28457. cli.set_proxy_basic_auth("u", "p");
  28458. cli.set_no_proxy({"127.0.0.1"});
  28459. cli.set_follow_location(true);
  28460. auto res = cli.Get("/redir");
  28461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28462. EXPECT_GE(proxy_hits.load(), 1);
  28463. EXPECT_GE(target_hits.load(), 1);
  28464. EXPECT_FALSE(target_saw_authz.load());
  28465. }
  28466. #ifdef CPPHTTPLIB_SSL_ENABLED
  28467. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28468. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28469. // proxy creds would be sent to the (possibly hostile) origin.
  28470. std::atomic<int> target_hits{0};
  28471. std::atomic<bool> target_saw_proxy_authz{false};
  28472. no_proxy_test::ScopedServer target;
  28473. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28474. target_hits++;
  28475. if (req.has_header("Proxy-Authorization")) {
  28476. target_saw_proxy_authz = true;
  28477. }
  28478. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28479. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28480. "nonce=\"abc\", algorithm=MD5");
  28481. });
  28482. target.listen();
  28483. // The proxy address is set to the target's port: the bypass MUST kick in;
  28484. // if it doesn't, the test still routes "via proxy" to the same server and
  28485. // the Proxy-Authorization assertion below catches the leak.
  28486. Client cli("evil.example", target.port());
  28487. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28488. cli.set_proxy("127.0.0.1", target.port());
  28489. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28490. cli.set_no_proxy({"evil.example"});
  28491. auto res = cli.Get("/x");
  28492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28493. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28494. EXPECT_EQ(1, target_hits.load());
  28495. EXPECT_FALSE(target_saw_proxy_authz.load());
  28496. }
  28497. #endif
  28498. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28499. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28500. std::atomic<int> proxy_hits{0};
  28501. std::atomic<int> bypass_hits{0};
  28502. std::atomic<bool> proxy_saw_c_url{false};
  28503. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28504. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28505. proxy_hits++;
  28506. if (req.path.find("/start") != std::string::npos) {
  28507. res.status = 302;
  28508. res.set_header("Location", "http://127.0.0.1:" +
  28509. std::to_string(bypass_server.port()) +
  28510. "/middle");
  28511. return;
  28512. }
  28513. if (req.path.find("/end") != std::string::npos) {
  28514. proxy_saw_c_url = true;
  28515. res.set_content("c-via-proxy", "text/plain");
  28516. return;
  28517. }
  28518. res.set_content("unexpected", "text/plain");
  28519. });
  28520. // public.example's "advertised" port is arbitrary (the request never lands
  28521. // there — it goes through the proxy), but use a dynamic value to stay
  28522. // friendly with sharded parallel runs.
  28523. int public_port = bypass_server.port();
  28524. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28525. bypass_hits++;
  28526. res.status = 302;
  28527. res.set_header("Location", "http://public.example:" +
  28528. std::to_string(public_port) + "/end");
  28529. });
  28530. proxy_mock.listen();
  28531. bypass_server.listen();
  28532. Client cli("public.example", public_port);
  28533. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28534. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28535. cli.set_no_proxy({"127.0.0.1"});
  28536. cli.set_follow_location(true);
  28537. auto res = cli.Get("/start");
  28538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28539. EXPECT_EQ(StatusCode::OK_200, res->status);
  28540. EXPECT_EQ("c-via-proxy", res->body);
  28541. EXPECT_GE(proxy_hits.load(), 2);
  28542. EXPECT_GE(bypass_hits.load(), 1);
  28543. EXPECT_TRUE(proxy_saw_c_url.load());
  28544. }
  28545. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28546. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28547. // request reconnects to the correct endpoint.
  28548. std::atomic<int> proxy_hits{0};
  28549. std::atomic<int> target_hits{0};
  28550. no_proxy_test::ScopedServer proxy_mock, target;
  28551. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28552. proxy_hits++;
  28553. res.set_content("via-proxy", "text/plain");
  28554. });
  28555. target.svr().Get(".*", [&](const Request &, Response &res) {
  28556. target_hits++;
  28557. res.set_content("direct", "text/plain");
  28558. });
  28559. proxy_mock.listen();
  28560. target.listen();
  28561. Client cli("public.example", target.port());
  28562. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28563. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28564. cli.set_keep_alive(true);
  28565. auto res1 = cli.Get("/a");
  28566. ASSERT_TRUE(res1);
  28567. EXPECT_EQ("via-proxy", res1->body);
  28568. EXPECT_EQ(1, proxy_hits.load());
  28569. EXPECT_EQ(0, target_hits.load());
  28570. cli.set_no_proxy({"public.example"});
  28571. auto res2 = cli.Get("/b");
  28572. ASSERT_TRUE(res2);
  28573. EXPECT_EQ("direct", res2->body);
  28574. EXPECT_EQ(1, proxy_hits.load());
  28575. EXPECT_EQ(1, target_hits.load());
  28576. }
  28577. // Forward declarations (see the base64_encode note).
  28578. namespace httplib {
  28579. namespace detail {
  28580. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28581. int shutdown_socket(socket_t sock) noexcept;
  28582. } // namespace detail
  28583. } // namespace httplib
  28584. namespace proxy_tunnel_test {
  28585. const char *const kTunnelEstablished =
  28586. "HTTP/1.1 200 Connection established\r\n\r\n";
  28587. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28588. using ConnectReply = std::function<std::string(const std::string &head)>;
  28589. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28590. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28591. class ScopedConnectProxy {
  28592. public:
  28593. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28594. : forward_port_(forward_port), reply_(std::move(reply)) {
  28595. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28596. if (listen_sock_ == INVALID_SOCKET) { return; }
  28597. auto a = loopback(0);
  28598. auto addr = reinterpret_cast<sockaddr *>(&a);
  28599. socklen_t alen = sizeof(a);
  28600. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28601. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28602. ::listen(listen_sock_, 4) != 0) {
  28603. return;
  28604. }
  28605. port_ = ntohs(a.sin_port);
  28606. th_ = std::thread([this] { run(); });
  28607. }
  28608. ~ScopedConnectProxy() {
  28609. if (th_.joinable()) {
  28610. stop_ = true;
  28611. auto wake = connect_to(port_);
  28612. th_.join();
  28613. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28614. }
  28615. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28616. }
  28617. int port() const { return port_; }
  28618. int connect_hits() const { return connect_hits_.load(); }
  28619. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28620. std::string connect_request() const {
  28621. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28622. return connect_request_;
  28623. }
  28624. private:
  28625. static sockaddr_in loopback(int port) {
  28626. sockaddr_in a{};
  28627. a.sin_family = AF_INET;
  28628. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28629. a.sin_port = htons(static_cast<unsigned short>(port));
  28630. return a;
  28631. }
  28632. static socket_t connect_to(int port) {
  28633. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28634. if (sock == INVALID_SOCKET) { return sock; }
  28635. auto a = loopback(port);
  28636. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28637. detail::close_socket(sock);
  28638. return INVALID_SOCKET;
  28639. }
  28640. return sock;
  28641. }
  28642. static bool send_all(socket_t sock, const char *data, size_t size) {
  28643. while (size > 0) {
  28644. auto n = detail::send_socket(sock, data, size, 0);
  28645. if (n <= 0) { return false; }
  28646. data += n;
  28647. size -= static_cast<size_t>(n);
  28648. }
  28649. return true;
  28650. }
  28651. void run() {
  28652. for (;;) {
  28653. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28654. if (stop_) {
  28655. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28656. return;
  28657. }
  28658. if (client == INVALID_SOCKET) { continue; }
  28659. serve(client);
  28660. detail::close_socket(client);
  28661. }
  28662. }
  28663. void serve(socket_t client) {
  28664. std::string head;
  28665. char buf[2048];
  28666. while (head.find("\r\n\r\n") == std::string::npos) {
  28667. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28668. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28669. if (n <= 0) { return; }
  28670. head.append(buf, static_cast<size_t>(n));
  28671. }
  28672. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28673. connect_hits_++;
  28674. {
  28675. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28676. connect_request_ = head;
  28677. }
  28678. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28679. if (!send_all(client, res.data(), res.size()) ||
  28680. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28681. return;
  28682. }
  28683. auto origin = connect_to(forward_port_);
  28684. if (origin == INVALID_SOCKET) { return; }
  28685. // When either side stops, shut both down so the other pump returns too.
  28686. auto pump = [&](socket_t from, socket_t to) {
  28687. char b[8192];
  28688. for (;;) {
  28689. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28690. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28691. }
  28692. detail::shutdown_socket(client);
  28693. detail::shutdown_socket(origin);
  28694. };
  28695. std::thread up([&] { pump(client, origin); });
  28696. pump(origin, client);
  28697. up.join();
  28698. detail::close_socket(origin);
  28699. }
  28700. int forward_port_;
  28701. ConnectReply reply_;
  28702. socket_t listen_sock_ = INVALID_SOCKET;
  28703. int port_ = 0;
  28704. std::thread th_;
  28705. std::atomic<bool> stop_{false};
  28706. std::atomic<int> connect_hits_{0};
  28707. mutable std::mutex connect_request_mutex_;
  28708. std::string connect_request_;
  28709. };
  28710. } // namespace proxy_tunnel_test
  28711. #ifdef CPPHTTPLIB_SSL_ENABLED
  28712. namespace proxy_tunnel_test {
  28713. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28714. class ScopedSSLServer {
  28715. public:
  28716. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28717. port_ = svr_.bind_to_any_port("127.0.0.1");
  28718. }
  28719. ~ScopedSSLServer() {
  28720. svr_.stop();
  28721. if (th_.joinable()) { th_.join(); }
  28722. }
  28723. SSLServer &svr() { return svr_; }
  28724. int port() const { return port_; }
  28725. void listen() {
  28726. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28727. svr_.wait_until_ready();
  28728. }
  28729. private:
  28730. SSLServer svr_;
  28731. std::thread th_;
  28732. int port_ = 0;
  28733. };
  28734. // Sends one request through the CONNECT proxy to the TLS origin with a
  28735. // credential configured for each hop, and checks that each credential reaches
  28736. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28737. // origin's (every header in origin_headers) on the tunnelled request.
  28738. void CredentialsStayWithTheirHop(
  28739. const std::function<void(SSLClient &)> &set_credentials,
  28740. const std::string &scheme,
  28741. const std::vector<std::string> &origin_headers = {"Authorization"},
  28742. bool stream = false) {
  28743. std::atomic<int> origin_hits{0};
  28744. std::atomic<bool> origin_saw_proxy_authz{false};
  28745. std::atomic<bool> origin_saw_headers{false};
  28746. ScopedSSLServer origin;
  28747. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28748. origin_hits++;
  28749. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28750. origin_saw_headers =
  28751. std::all_of(origin_headers.begin(), origin_headers.end(),
  28752. [&](const std::string &h) { return req.has_header(h); });
  28753. res.set_content("ok", "text/plain");
  28754. });
  28755. origin.listen();
  28756. ScopedConnectProxy proxy(origin.port());
  28757. ASSERT_NE(0, proxy.port());
  28758. // Pinned to 127.0.0.1 for the same reason as the test below.
  28759. SSLClient cli("127.0.0.1", origin.port());
  28760. cli.enable_server_certificate_verification(false);
  28761. cli.set_proxy("127.0.0.1", proxy.port());
  28762. set_credentials(cli);
  28763. if (stream) {
  28764. auto handle = cli.open_stream("GET", "/x");
  28765. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28766. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28767. } else {
  28768. auto res = cli.Get("/x");
  28769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28770. EXPECT_EQ(StatusCode::OK_200, res->status);
  28771. }
  28772. EXPECT_EQ(1, origin_hits.load());
  28773. EXPECT_EQ(1, proxy.connect_hits());
  28774. EXPECT_TRUE(origin_saw_headers.load());
  28775. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28776. << "Proxy-Authorization must not be sent inside the tunnel";
  28777. auto connect_req = proxy.connect_request();
  28778. EXPECT_NE(std::string::npos,
  28779. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28780. for (const auto &h : origin_headers) {
  28781. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28782. << h << " must not be sent to the proxy on CONNECT";
  28783. }
  28784. }
  28785. } // namespace proxy_tunnel_test
  28786. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28787. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28788. [](SSLClient &cli) {
  28789. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28790. cli.set_basic_auth("origin-user", "origin-pass");
  28791. },
  28792. "Basic");
  28793. }
  28794. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28795. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28796. [](SSLClient &cli) {
  28797. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28798. cli.set_basic_auth("origin-user", "origin-pass");
  28799. },
  28800. "Basic", {"Authorization"}, true);
  28801. }
  28802. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28803. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28804. [](SSLClient &cli) {
  28805. cli.set_proxy_bearer_token_auth("proxy-token");
  28806. cli.set_bearer_token_auth("origin-token");
  28807. },
  28808. "Bearer");
  28809. }
  28810. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28811. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28812. [](SSLClient &cli) {
  28813. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28814. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28815. {"Cookie", "sid=origin-session"},
  28816. {"X-Api-Key", "origin-key"}});
  28817. },
  28818. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28819. }
  28820. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28821. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28822. // retry; otherwise proxy creds would be sent to the origin.
  28823. std::atomic<int> origin_hits{0};
  28824. std::atomic<bool> origin_saw_proxy_authz{false};
  28825. proxy_tunnel_test::ScopedSSLServer origin;
  28826. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28827. origin_hits++;
  28828. if (req.has_header("Proxy-Authorization")) {
  28829. origin_saw_proxy_authz = true;
  28830. }
  28831. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28832. res.set_header("Proxy-Authenticate",
  28833. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28834. "algorithm=MD5");
  28835. });
  28836. origin.listen();
  28837. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28838. ASSERT_NE(0, proxy.port());
  28839. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28840. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28841. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28842. // and answer with its own status, making this test flaky.
  28843. SSLClient cli("127.0.0.1", origin.port());
  28844. cli.enable_server_certificate_verification(false);
  28845. cli.set_proxy("127.0.0.1", proxy.port());
  28846. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28847. auto res = cli.Get("/x");
  28848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28849. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28850. EXPECT_EQ(1, origin_hits.load());
  28851. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28852. EXPECT_EQ(1, proxy.connect_hits());
  28853. }
  28854. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28855. std::string origin_sni;
  28856. std::string origin_host;
  28857. proxy_tunnel_test::ScopedSSLServer origin;
  28858. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28859. origin_sni = req.sni();
  28860. origin_host = req.get_header_value("Host");
  28861. res.set_content("ok", "text/plain");
  28862. });
  28863. origin.listen();
  28864. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28865. ASSERT_NE(0, proxy.port());
  28866. SSLClient cli("origin.example", origin.port());
  28867. cli.enable_server_certificate_verification(false);
  28868. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28869. cli.set_proxy("127.0.0.1", proxy.port());
  28870. auto res = cli.Get("/x");
  28871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28872. EXPECT_EQ(StatusCode::OK_200, res->status);
  28873. auto port = std::to_string(origin.port());
  28874. auto target = "127.0.0.1:" + port;
  28875. auto connect_req = proxy.connect_request();
  28876. EXPECT_EQ(1, proxy.connect_hits());
  28877. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28878. EXPECT_NE(std::string::npos,
  28879. connect_req.find("\r\nHost: " + target + "\r\n"));
  28880. EXPECT_EQ("origin.example", origin_sni);
  28881. EXPECT_EQ("origin.example:" + port, origin_host);
  28882. }
  28883. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28884. proxy_tunnel_test::ScopedSSLServer origin;
  28885. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28886. res.set_content("ok", "text/plain");
  28887. });
  28888. origin.listen();
  28889. proxy_tunnel_test::ScopedConnectProxy proxy(
  28890. origin.port(), [](const std::string &head) -> std::string {
  28891. if (head.find(
  28892. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28893. std::string::npos) {
  28894. return proxy_tunnel_test::kTunnelEstablished;
  28895. }
  28896. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28897. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28898. "nonce=\"abc\", algorithm=MD5\r\n"
  28899. "Content-Length: 0\r\n\r\n";
  28900. });
  28901. ASSERT_NE(0, proxy.port());
  28902. SSLClient cli("origin.example", origin.port());
  28903. cli.enable_server_certificate_verification(false);
  28904. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28905. cli.set_proxy("127.0.0.1", proxy.port());
  28906. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28907. auto res = cli.Get("/x");
  28908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28909. EXPECT_EQ(StatusCode::OK_200, res->status);
  28910. // The retried CONNECT is the one the proxy saw last.
  28911. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28912. auto connect_req = proxy.connect_request();
  28913. EXPECT_EQ(2, proxy.connect_hits());
  28914. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28915. EXPECT_NE(std::string::npos,
  28916. connect_req.find("\r\nHost: " + target + "\r\n"));
  28917. }
  28918. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28919. proxy_tunnel_test::ScopedSSLServer origin;
  28920. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28921. res.set_content("ok", "text/plain");
  28922. });
  28923. origin.listen();
  28924. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28925. ASSERT_NE(0, proxy.port());
  28926. SSLClient cli("origin.example", origin.port());
  28927. cli.enable_server_certificate_verification(false);
  28928. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28929. cli.set_proxy("127.0.0.1", proxy.port());
  28930. auto res = cli.Get("/x");
  28931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28932. EXPECT_EQ(StatusCode::OK_200, res->status);
  28933. auto target = "origin.example:" + std::to_string(origin.port());
  28934. auto connect_req = proxy.connect_request();
  28935. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28936. EXPECT_NE(std::string::npos,
  28937. connect_req.find("\r\nHost: " + target + "\r\n"));
  28938. }
  28939. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28940. proxy_tunnel_test::ScopedSSLServer origin;
  28941. auto port = std::to_string(origin.port());
  28942. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28943. res.set_redirect("https://next.example:" + port + "/y");
  28944. });
  28945. origin.svr().Get("/y", [](const Request &, Response &res) {
  28946. res.set_content("ok", "text/plain");
  28947. });
  28948. origin.listen();
  28949. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28950. ASSERT_NE(0, proxy.port());
  28951. SSLClient cli("origin.example", origin.port());
  28952. cli.enable_server_certificate_verification(false);
  28953. cli.set_tunnel_hostname_addr_map(
  28954. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28955. cli.set_proxy("127.0.0.1", proxy.port());
  28956. cli.set_follow_location(true);
  28957. auto res = cli.Get("/x");
  28958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28959. EXPECT_EQ("ok", res->body);
  28960. // The last CONNECT is the redirect client's.
  28961. ASSERT_EQ(2, proxy.connect_hits());
  28962. auto target = "127.0.0.1:" + port;
  28963. auto connect_req = proxy.connect_request();
  28964. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28965. EXPECT_NE(std::string::npos,
  28966. connect_req.find("\r\nHost: " + target + "\r\n"));
  28967. }
  28968. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28969. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28970. std::atomic<int> origin_hits{0};
  28971. proxy_tunnel_test::ScopedSSLServer origin;
  28972. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28973. origin_hits++;
  28974. res.set_content("ok", "text/plain");
  28975. });
  28976. origin.listen();
  28977. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28978. ASSERT_NE(0, proxy.port());
  28979. SSLClient cli("127.0.0.1", origin.port());
  28980. cli.enable_server_certificate_verification(false);
  28981. cli.set_proxy("127.0.0.1", proxy.port());
  28982. cli.set_keep_alive(true);
  28983. cli.set_session_verifier(
  28984. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28985. auto res = cli.Get("/x");
  28986. EXPECT_FALSE(res);
  28987. ASSERT_FALSE(cli.is_socket_open());
  28988. res = cli.Get("/x");
  28989. EXPECT_FALSE(res);
  28990. EXPECT_EQ(2, proxy.connect_hits());
  28991. auto handle = cli.open_stream("GET", "/x");
  28992. EXPECT_FALSE(handle.is_valid());
  28993. EXPECT_EQ(3, proxy.connect_hits());
  28994. EXPECT_EQ(0, origin_hits.load());
  28995. }
  28996. #endif
  28997. namespace proxy_tunnel_test {
  28998. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28999. // anything else gets a 407 with `challenge`.
  29000. ConnectReply require_proxy_auth(const std::string &expected,
  29001. const std::string &challenge) {
  29002. return [=](const std::string &head) -> std::string {
  29003. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  29004. std::string::npos) {
  29005. return kTunnelEstablished;
  29006. }
  29007. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29008. "Proxy-Authenticate: " +
  29009. challenge + "\r\nContent-Length: 0\r\n\r\n";
  29010. };
  29011. }
  29012. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  29013. // request, then echoes.
  29014. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  29015. ws.send(
  29016. "authorization:" + req.get_header_value("Authorization") +
  29017. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  29018. std::string msg;
  29019. while (ws.read(msg)) {
  29020. ws.send(msg);
  29021. }
  29022. }
  29023. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  29024. class ScopedWebSocketOrigin {
  29025. public:
  29026. ScopedWebSocketOrigin() {
  29027. server_.svr().WebSocket("/ws", report_auth_then_echo);
  29028. server_.listen();
  29029. }
  29030. int port() const { return server_.port(); }
  29031. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  29032. std::string url() const {
  29033. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  29034. }
  29035. private:
  29036. no_proxy_test::ScopedServer server_;
  29037. };
  29038. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  29039. // passed as a constructor header, and checks that each reaches only its hop.
  29040. void WebSocketCredentialsStayWithTheirHop(
  29041. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  29042. const std::string &proxy_authz, const std::string &origin_authz) {
  29043. ScopedWebSocketOrigin origin;
  29044. ScopedConnectProxy proxy(
  29045. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  29046. ASSERT_NE(0, proxy.port());
  29047. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  29048. client.set_proxy("127.0.0.1", proxy.port());
  29049. set_proxy_credentials(client);
  29050. auto res = client.connect();
  29051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29052. std::string msg;
  29053. ASSERT_TRUE(client.read(msg));
  29054. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  29055. client.close();
  29056. EXPECT_EQ(1, proxy.connect_hits());
  29057. EXPECT_EQ(std::string::npos,
  29058. proxy.connect_request().find("\r\nAuthorization: "))
  29059. << "origin credentials must not be sent to the proxy";
  29060. }
  29061. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  29062. void WebSocketSetterCredentialsStayWithTheirHop(
  29063. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  29064. const std::string &proxy_authz, const std::string &origin_authz) {
  29065. ScopedWebSocketOrigin origin;
  29066. ScopedConnectProxy proxy(
  29067. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  29068. ASSERT_NE(0, proxy.port());
  29069. ws::WebSocketClient client(origin.url());
  29070. client.set_proxy("127.0.0.1", proxy.port());
  29071. set_credentials(client);
  29072. auto res = client.connect();
  29073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29074. std::string msg;
  29075. ASSERT_TRUE(client.read(msg));
  29076. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  29077. client.close();
  29078. EXPECT_EQ(1, proxy.connect_hits());
  29079. EXPECT_EQ(std::string::npos,
  29080. proxy.connect_request().find("\r\nAuthorization: "))
  29081. << "origin credentials must not be sent to the proxy";
  29082. }
  29083. } // namespace proxy_tunnel_test
  29084. namespace {
  29085. // Connects `client` and returns the Authorization header its upgrade
  29086. // request carried, or "<failed>" when the connection could not be opened.
  29087. std::string websocket_authorization(ws::WebSocketClient &client) {
  29088. if (!client.connect()) { return "<failed>"; }
  29089. std::string msg;
  29090. if (!client.read(msg)) { return "<failed>"; }
  29091. client.close();
  29092. auto prefix = std::string("authorization:");
  29093. auto end = msg.find("|proxy-authorization:");
  29094. return msg.substr(prefix.size(), end - prefix.size());
  29095. }
  29096. } // namespace
  29097. TEST(WebSocketClientAuthTest, BasicAuth) {
  29098. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29099. ws::WebSocketClient client(origin.url());
  29100. client.set_basic_auth("user", "pass");
  29101. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  29102. websocket_authorization(client));
  29103. }
  29104. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  29105. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29106. ws::WebSocketClient client(origin.url());
  29107. client.set_basic_auth("user", "");
  29108. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  29109. websocket_authorization(client));
  29110. }
  29111. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  29112. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29113. ws::WebSocketClient client(origin.url());
  29114. client.set_bearer_token_auth("token123");
  29115. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  29116. }
  29117. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  29118. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29119. ws::WebSocketClient client(origin.url());
  29120. client.set_bearer_token_auth("token123");
  29121. client.set_basic_auth("user", "pass");
  29122. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  29123. websocket_authorization(client));
  29124. }
  29125. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  29126. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29127. ws::WebSocketClient client(origin.url(),
  29128. {{"Authorization", "Bearer from-header"}});
  29129. client.set_bearer_token_auth("from-setter");
  29130. client.set_basic_auth("user", "pass");
  29131. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  29132. }
  29133. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  29134. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29135. ws::WebSocketClient client(origin.url());
  29136. EXPECT_EQ("", websocket_authorization(client));
  29137. client.set_bearer_token_auth("first");
  29138. EXPECT_EQ("Bearer first", websocket_authorization(client));
  29139. client.set_bearer_token_auth("second");
  29140. EXPECT_EQ("Bearer second", websocket_authorization(client));
  29141. client.set_bearer_token_auth("");
  29142. EXPECT_EQ("", websocket_authorization(client));
  29143. }
  29144. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  29145. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29146. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29147. ASSERT_NE(0, proxy.port());
  29148. ws::WebSocketClient client(origin.url());
  29149. client.set_proxy("127.0.0.1", proxy.port());
  29150. auto res = client.connect();
  29151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29152. std::string msg;
  29153. ASSERT_TRUE(client.read(msg));
  29154. ASSERT_TRUE(client.send("hello"));
  29155. ASSERT_TRUE(client.read(msg));
  29156. EXPECT_EQ("hello", msg);
  29157. client.close();
  29158. EXPECT_EQ(1, proxy.connect_hits());
  29159. auto target = "127.0.0.1:" + std::to_string(origin.port());
  29160. auto connect_req = proxy.connect_request();
  29161. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29162. EXPECT_NE(std::string::npos,
  29163. connect_req.find("\r\nHost: " + target + "\r\n"));
  29164. }
  29165. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  29166. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  29167. [](ws::WebSocketClient &cli) {
  29168. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29169. },
  29170. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  29171. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  29172. }
  29173. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  29174. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  29175. [](ws::WebSocketClient &cli) {
  29176. cli.set_proxy_bearer_token_auth("proxy-token");
  29177. },
  29178. "Bearer proxy-token", "Bearer origin-token");
  29179. }
  29180. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  29181. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29182. [](ws::WebSocketClient &cli) {
  29183. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29184. cli.set_basic_auth("origin-user", "origin-pass");
  29185. },
  29186. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  29187. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  29188. }
  29189. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  29190. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29191. [](ws::WebSocketClient &cli) {
  29192. cli.set_proxy_bearer_token_auth("proxy-token");
  29193. cli.set_bearer_token_auth("origin-token");
  29194. },
  29195. "Bearer proxy-token", "Bearer origin-token");
  29196. }
  29197. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  29198. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29199. proxy_tunnel_test::ScopedConnectProxy proxy(
  29200. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29201. "Basic " + detail::base64_encode("proxy-user:"),
  29202. "Basic realm=\"proxy\""));
  29203. ASSERT_NE(0, proxy.port());
  29204. ws::WebSocketClient client(origin.url());
  29205. client.set_proxy("127.0.0.1", proxy.port());
  29206. client.set_proxy_basic_auth("proxy-user", "");
  29207. auto res = client.connect();
  29208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29209. client.close();
  29210. EXPECT_EQ(1, proxy.connect_hits());
  29211. }
  29212. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  29213. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29214. proxy_tunnel_test::ScopedConnectProxy proxy(
  29215. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29216. "Bearer proxy-token", "Basic realm=\"proxy\""));
  29217. ASSERT_NE(0, proxy.port());
  29218. ws::WebSocketClient client(origin.url());
  29219. client.set_proxy("127.0.0.1", proxy.port());
  29220. auto res = client.connect();
  29221. EXPECT_FALSE(res);
  29222. EXPECT_EQ(Error::ProxyConnection, res.error());
  29223. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  29224. EXPECT_EQ("Basic realm=\"proxy\"",
  29225. res.get_header_value("Proxy-Authenticate"));
  29226. EXPECT_FALSE(client.is_open());
  29227. }
  29228. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  29229. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29230. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29231. ASSERT_NE(0, proxy.port());
  29232. ws::WebSocketClient client(origin.url());
  29233. client.set_proxy("127.0.0.1", proxy.port());
  29234. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29235. client.set_no_proxy({"127.0.0.1"});
  29236. auto res = client.connect();
  29237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29238. std::string msg;
  29239. ASSERT_TRUE(client.read(msg));
  29240. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29241. << "proxy credentials must not reach a bypassed origin";
  29242. client.close();
  29243. EXPECT_EQ(0, proxy.connect_hits());
  29244. }
  29245. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  29246. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29247. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29248. ASSERT_NE(0, proxy.port());
  29249. ws::WebSocketClient client(origin.url());
  29250. client.set_proxy("127.0.0.1", proxy.port());
  29251. ASSERT_TRUE(client.connect());
  29252. ASSERT_TRUE(client.connect());
  29253. client.close();
  29254. EXPECT_EQ(2, proxy.connect_hits());
  29255. }
  29256. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  29257. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29258. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29259. ASSERT_NE(0, proxy.port());
  29260. auto port = std::to_string(origin.port());
  29261. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29262. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29263. client.set_proxy("127.0.0.1", proxy.port());
  29264. auto res = client.connect();
  29265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29266. std::string msg;
  29267. ASSERT_TRUE(client.read(msg));
  29268. client.close();
  29269. EXPECT_EQ(1, proxy.connect_hits());
  29270. auto target = "127.0.0.1:" + port;
  29271. auto connect_req = proxy.connect_request();
  29272. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29273. EXPECT_NE(std::string::npos,
  29274. connect_req.find("\r\nHost: " + target + "\r\n"));
  29275. }
  29276. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  29277. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29278. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29279. ASSERT_NE(0, proxy.port());
  29280. auto port = std::to_string(origin.port());
  29281. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29282. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29283. client.set_proxy("127.0.0.1", proxy.port());
  29284. auto res = client.connect();
  29285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29286. client.close();
  29287. auto target = "origin.example:" + port;
  29288. auto connect_req = proxy.connect_request();
  29289. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29290. EXPECT_NE(std::string::npos,
  29291. connect_req.find("\r\nHost: " + target + "\r\n"));
  29292. }
  29293. #ifdef CPPHTTPLIB_SSL_ENABLED
  29294. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  29295. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29296. proxy_tunnel_test::ScopedConnectProxy proxy(
  29297. origin.port(), [](const std::string &head) -> std::string {
  29298. if (head.find(
  29299. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  29300. std::string::npos) {
  29301. return proxy_tunnel_test::kTunnelEstablished;
  29302. }
  29303. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29304. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  29305. "nonce=\"abc\", algorithm=MD5\r\n"
  29306. "Content-Length: 0\r\n\r\n";
  29307. });
  29308. ASSERT_NE(0, proxy.port());
  29309. ws::WebSocketClient client(origin.url());
  29310. client.set_proxy("127.0.0.1", proxy.port());
  29311. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  29312. auto res = client.connect();
  29313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29314. std::string msg;
  29315. ASSERT_TRUE(client.read(msg));
  29316. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  29317. client.close();
  29318. EXPECT_EQ(2, proxy.connect_hits());
  29319. }
  29320. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  29321. proxy_tunnel_test::ScopedSSLServer origin;
  29322. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  29323. origin.listen();
  29324. proxy_tunnel_test::ScopedConnectProxy proxy(
  29325. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29326. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  29327. ASSERT_NE(0, proxy.port());
  29328. ws::WebSocketClient client(
  29329. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  29330. client.enable_server_certificate_verification(false);
  29331. client.set_proxy("127.0.0.1", proxy.port());
  29332. client.set_proxy_bearer_token_auth("proxy-token");
  29333. auto res = client.connect();
  29334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29335. std::string msg;
  29336. ASSERT_TRUE(client.read(msg));
  29337. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29338. << "Proxy-Authorization must not be sent inside the tunnel";
  29339. client.close();
  29340. EXPECT_EQ(1, proxy.connect_hits());
  29341. }
  29342. #endif
  29343. // ---------------------------------------------------------------------------
  29344. // Poller
  29345. // ---------------------------------------------------------------------------
  29346. namespace poller_test {
  29347. struct PollerBackend {
  29348. const char *name;
  29349. std::unique_ptr<detail::Poller> (*create)();
  29350. };
  29351. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  29352. *os << backend.name;
  29353. }
  29354. // Every backend runs the same contract tests. A new one is added here only.
  29355. std::vector<PollerBackend> poller_backends() {
  29356. return {
  29357. {"poll", &detail::PollPoller::create},
  29358. #ifdef __linux__
  29359. {"epoll", &detail::EpollPoller::create},
  29360. #endif
  29361. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29362. {"kqueue", &detail::KqueuePoller::create},
  29363. #endif
  29364. };
  29365. }
  29366. // A descriptor whose readability the test controls.
  29367. struct TestSocketPair {
  29368. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29369. TestSocketPair() { detail::create_socket_pair(fd); }
  29370. ~TestSocketPair() {
  29371. for (auto s : fd) {
  29372. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29373. }
  29374. }
  29375. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29376. socket_t reader() const { return fd[0]; }
  29377. void make_readable() {
  29378. const char c = 1;
  29379. detail::send_socket(fd[1], &c, 1, 0);
  29380. }
  29381. void close_writer() {
  29382. detail::close_socket(fd[1]);
  29383. fd[1] = INVALID_SOCKET;
  29384. }
  29385. };
  29386. using Tokens = std::vector<detail::Poller::Token>;
  29387. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29388. protected:
  29389. void SetUp() override {
  29390. poller_ = GetParam().create();
  29391. ASSERT_TRUE(poller_ != nullptr);
  29392. }
  29393. Tokens wait_for(int timeout_ms) {
  29394. Tokens ready;
  29395. poller_->wait(timeout_ms, ready);
  29396. std::sort(ready.begin(), ready.end());
  29397. return ready;
  29398. }
  29399. std::unique_ptr<detail::Poller> poller_;
  29400. };
  29401. } // namespace poller_test
  29402. using poller_test::PollerTest;
  29403. using poller_test::TestSocketPair;
  29404. using poller_test::Tokens;
  29405. INSTANTIATE_TEST_SUITE_P(
  29406. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29407. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29408. return std::string(p.param.name);
  29409. });
  29410. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29411. TestSocketPair sp;
  29412. ASSERT_TRUE(sp.ok());
  29413. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29414. EXPECT_EQ(Tokens{}, wait_for(0));
  29415. sp.make_readable();
  29416. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29417. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29418. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29419. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29420. }
  29421. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29422. TestSocketPair sp;
  29423. ASSERT_TRUE(sp.ok());
  29424. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29425. poller_->disarm(sp.reader());
  29426. poller_->disarm(sp.reader()); // disarming twice is harmless
  29427. sp.make_readable();
  29428. EXPECT_EQ(Tokens{}, wait_for(0));
  29429. }
  29430. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29431. TestSocketPair sp;
  29432. ASSERT_TRUE(sp.ok());
  29433. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29434. auto start = std::chrono::steady_clock::now();
  29435. EXPECT_EQ(Tokens{}, wait_for(30));
  29436. auto elapsed = std::chrono::steady_clock::now() - start;
  29437. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29438. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29439. }
  29440. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29441. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29442. for (detail::Poller::Token i = 0; i < 8; i++) {
  29443. sps.emplace_back(new TestSocketPair());
  29444. ASSERT_TRUE(sps.back()->ok());
  29445. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29446. }
  29447. sps[0]->make_readable();
  29448. sps[3]->make_readable();
  29449. sps[7]->make_readable();
  29450. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29451. // The others are still armed, the delivered ones are not.
  29452. sps[1]->make_readable();
  29453. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29454. EXPECT_EQ(Tokens{}, wait_for(0));
  29455. }
  29456. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29457. TestSocketPair s0, s1, s2;
  29458. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29459. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29460. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29461. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29462. // A delivery may move another entry inside the poller.
  29463. s0.make_readable();
  29464. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29465. // The entries left must still be found by descriptor.
  29466. poller_->disarm(s2.reader());
  29467. s1.make_readable();
  29468. s2.make_readable();
  29469. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29470. }
  29471. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29472. TestSocketPair sp;
  29473. ASSERT_TRUE(sp.ok());
  29474. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29475. sp.close_writer();
  29476. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29477. char c;
  29478. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29479. }
  29480. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29481. std::thread waker([&] {
  29482. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29483. poller_->wake();
  29484. });
  29485. Tokens ready;
  29486. auto start = std::chrono::steady_clock::now();
  29487. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29488. waker.join();
  29489. EXPECT_TRUE(ready.empty());
  29490. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29491. }
  29492. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29493. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29494. Tokens ready;
  29495. EXPECT_TRUE(poller_->wait(1000, ready));
  29496. }
  29497. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29498. for (int i = 0; i < 1000; i++) {
  29499. poller_->wake();
  29500. }
  29501. Tokens ready;
  29502. EXPECT_TRUE(poller_->wait(0, ready));
  29503. EXPECT_FALSE(poller_->wait(0, ready));
  29504. poller_->wake();
  29505. EXPECT_TRUE(poller_->wait(0, ready));
  29506. }
  29507. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29508. // Two threads publish changes and wake() after each, as a reactor's workers
  29509. // do. Every change must be seen without a wait() timing out. A lost wake()
  29510. // needs an unlucky interleaving, hence the rounds.
  29511. for (int round = 0; round < 5; round++) {
  29512. SCOPED_TRACE(round);
  29513. const int per_thread = 20000;
  29514. std::atomic<int> posted{0};
  29515. auto post = [&] {
  29516. for (int i = 0; i < per_thread; i++) {
  29517. posted++;
  29518. poller_->wake();
  29519. }
  29520. };
  29521. std::thread t1(post), t2(post);
  29522. auto lost = false;
  29523. Tokens ready;
  29524. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29525. if (!poller_->wait(1000, ready)) {
  29526. lost = true;
  29527. break;
  29528. }
  29529. }
  29530. t1.join();
  29531. t2.join();
  29532. ASSERT_FALSE(lost);
  29533. }
  29534. }
  29535. TEST(PollerFactoryTest, MakePollerWorks) {
  29536. auto poller = detail::make_poller();
  29537. ASSERT_TRUE(poller != nullptr);
  29538. poller->wake();
  29539. std::vector<detail::Poller::Token> ready;
  29540. EXPECT_TRUE(poller->wait(1000, ready));
  29541. }
  29542. // ---------------------------------------------------------------------------
  29543. // Keep-alive parking
  29544. // ---------------------------------------------------------------------------
  29545. namespace parking_test {
  29546. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29547. // runs once the port is bound and listening, before the server accepts.
  29548. struct RunningServer {
  29549. explicit RunningServer(
  29550. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29551. : svr_(svr) {
  29552. port = svr_.bind_to_any_port("127.0.0.1");
  29553. if (before_listen) { before_listen(port); }
  29554. thread = std::thread([this] { svr_.listen_after_bind(); });
  29555. svr_.wait_until_ready();
  29556. }
  29557. ~RunningServer() {
  29558. svr_.stop();
  29559. if (thread.joinable()) { thread.join(); }
  29560. }
  29561. Server &svr_;
  29562. int port = 0;
  29563. std::thread thread;
  29564. };
  29565. struct Sockets {
  29566. std::vector<socket_t> socks;
  29567. ~Sockets() {
  29568. for (auto s : socks) {
  29569. detail::close_socket(s);
  29570. }
  29571. }
  29572. socket_t connect(int port) {
  29573. auto error = Error::Success;
  29574. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29575. false, false, nullptr, 2, 0, 2, 0, 2,
  29576. 0, std::string(), error);
  29577. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29578. return s;
  29579. }
  29580. };
  29581. std::chrono::steady_clock::time_point in_ms(int ms) {
  29582. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29583. }
  29584. bool readable_by(socket_t sock,
  29585. std::chrono::steady_clock::time_point deadline) {
  29586. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29587. deadline - std::chrono::steady_clock::now())
  29588. .count();
  29589. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29590. }
  29591. bool send_get(socket_t sock, const std::string &path = "/") {
  29592. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29593. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29594. static_cast<ssize_t>(req.size());
  29595. }
  29596. // Reads one response whose body is "ok".
  29597. bool receives_ok(socket_t sock, int timeout_ms) {
  29598. auto deadline = in_ms(timeout_ms);
  29599. std::string buf;
  29600. while (readable_by(sock, deadline)) {
  29601. char tmp[1024];
  29602. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29603. if (n <= 0) { return false; }
  29604. buf.append(tmp, static_cast<size_t>(n));
  29605. auto end = buf.find("\r\n\r\n");
  29606. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29607. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29608. buf.compare(end + 4, 2, "ok") == 0;
  29609. }
  29610. }
  29611. return false;
  29612. }
  29613. bool get_ok(socket_t sock, int timeout_ms) {
  29614. return send_get(sock) && receives_ok(sock, timeout_ms);
  29615. }
  29616. // Whether the server closes `sock` by `deadline`.
  29617. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29618. char c;
  29619. return readable_by(sock, deadline) &&
  29620. detail::read_socket(sock, &c, 1, 0) <= 0;
  29621. }
  29622. // Whether the server closes `sock` without answering a request.
  29623. bool get_refused(socket_t sock, int timeout_ms) {
  29624. return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
  29625. }
  29626. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29627. auto deadline = in_ms(timeout_ms);
  29628. while (!cond()) {
  29629. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29630. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29631. }
  29632. return true;
  29633. }
  29634. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29635. svr.new_task_queue = std::move(new_task_queue);
  29636. svr.set_keep_alive_parking(true);
  29637. svr.Get("/", [](const Request &, Response &res) {
  29638. res.set_content("ok", "text/plain");
  29639. });
  29640. }
  29641. std::function<TaskQueue *(void)> threads(size_t n) {
  29642. return [n] { return new ThreadPool(n); };
  29643. }
  29644. // Counts what the event loop managed to queue, so that a test can wait for it.
  29645. class CountingTaskQueue final : public TaskQueue {
  29646. public:
  29647. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29648. std::atomic<int> &full)
  29649. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29650. bool enqueue(std::function<void()> fn) override {
  29651. auto queued = pool_.enqueue([this, fn]() {
  29652. fn();
  29653. // Holds the worker back from taking the next job.
  29654. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29655. });
  29656. (queued ? ok_ : full_)++;
  29657. return queued;
  29658. }
  29659. void shutdown() override { pool_.shutdown(); }
  29660. std::atomic<int> pause_after_ms{0};
  29661. private:
  29662. ThreadPool pool_;
  29663. std::atomic<int> &ok_;
  29664. std::atomic<int> &full_;
  29665. };
  29666. // Holds handlers until it opens, or for 3 seconds at most.
  29667. class Gate {
  29668. public:
  29669. void wait() {
  29670. std::unique_lock<std::mutex> lock(m_);
  29671. entered_++;
  29672. cv_.notify_all();
  29673. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29674. }
  29675. void open() {
  29676. std::lock_guard<std::mutex> guard(m_);
  29677. open_ = true;
  29678. cv_.notify_all();
  29679. }
  29680. int entered() {
  29681. std::lock_guard<std::mutex> guard(m_);
  29682. return entered_;
  29683. }
  29684. private:
  29685. std::mutex m_;
  29686. std::condition_variable cv_;
  29687. bool open_ = false;
  29688. int entered_ = 0;
  29689. };
  29690. } // namespace parking_test
  29691. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29692. using namespace parking_test;
  29693. Server svr;
  29694. serve_ok(svr, threads(1));
  29695. RunningServer running(svr);
  29696. Sockets socks;
  29697. // One kept-alive connection that has been served, and many that have not
  29698. // sent anything yet. None of them may keep the only worker.
  29699. auto served = socks.connect(running.port);
  29700. ASSERT_TRUE(get_ok(served, 2000));
  29701. for (int i = 0; i < 49; i++) {
  29702. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29703. }
  29704. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29705. EXPECT_TRUE(get_ok(served, 1000));
  29706. }
  29707. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29708. using namespace parking_test;
  29709. Server svr;
  29710. serve_ok(svr, threads(1));
  29711. svr.set_keep_alive_timeout(1);
  29712. RunningServer running(svr);
  29713. Sockets socks;
  29714. for (int i = 0; i < 3; i++) {
  29715. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29716. }
  29717. // One worker waiting on each in turn would take about 3 seconds.
  29718. auto deadline = in_ms(2000);
  29719. for (auto s : socks.socks) {
  29720. EXPECT_TRUE(sees_eof(s, deadline));
  29721. }
  29722. }
  29723. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29724. using namespace parking_test;
  29725. std::atomic<int> queued{0}, full{0};
  29726. Server svr;
  29727. // One worker and room for one queued task.
  29728. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29729. Gate gate;
  29730. svr.Get("/block", [&](const Request &, Response &res) {
  29731. gate.wait();
  29732. res.set_content("ok", "text/plain");
  29733. });
  29734. RunningServer running(svr);
  29735. // Before the server stops, so that a failed run does not wait for the
  29736. // handler's timeout.
  29737. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29738. Sockets socks;
  29739. auto a = socks.connect(running.port);
  29740. ASSERT_TRUE(get_ok(a, 2000));
  29741. // B keeps the only worker busy.
  29742. auto b = socks.connect(running.port);
  29743. ASSERT_TRUE(send_get(b, "/block"));
  29744. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29745. // A new connection C fills the queue.
  29746. auto c = socks.connect(running.port);
  29747. ASSERT_TRUE(send_get(c));
  29748. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29749. // A's next request finds the queue full, but A has been served before, so it
  29750. // waits instead of being cut off.
  29751. ASSERT_TRUE(send_get(a));
  29752. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29753. gate.open();
  29754. EXPECT_TRUE(receives_ok(b, 2000));
  29755. EXPECT_TRUE(receives_ok(c, 2000));
  29756. EXPECT_TRUE(receives_ok(a, 2000));
  29757. }
  29758. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29759. using namespace parking_test;
  29760. std::atomic<int> queued{0}, full{0};
  29761. CountingTaskQueue *queue = nullptr;
  29762. Server svr;
  29763. // Two workers and room for one queued task.
  29764. serve_ok(svr,
  29765. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29766. Gate first, second;
  29767. svr.Get("/first", [&](const Request &, Response &res) {
  29768. first.wait();
  29769. res.set_content("ok", "text/plain");
  29770. });
  29771. svr.Get("/second", [&](const Request &, Response &res) {
  29772. second.wait();
  29773. res.set_content("ok", "text/plain");
  29774. });
  29775. RunningServer running(svr);
  29776. auto open_gates = detail::scope_exit([&] {
  29777. first.open();
  29778. second.open();
  29779. });
  29780. Sockets socks;
  29781. auto a = socks.connect(running.port);
  29782. ASSERT_TRUE(get_ok(a, 2000));
  29783. // B and D take both workers, and C fills the queue. One at a time: the
  29784. // queue has room for one job only until a worker takes it.
  29785. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29786. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29787. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29788. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29789. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29790. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29791. // A's next request waits in the backlog.
  29792. ASSERT_TRUE(send_get(a));
  29793. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29794. // B's worker finishes, then takes C off the queue only later, which makes
  29795. // room for A.
  29796. queue->pause_after_ms = 200;
  29797. first.open();
  29798. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29799. queue->pause_after_ms = 0;
  29800. second.open();
  29801. EXPECT_TRUE(receives_ok(a, 2000));
  29802. }
  29803. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29804. using namespace parking_test;
  29805. Server svr;
  29806. serve_ok(svr, threads(1));
  29807. svr.set_keep_alive_timeout(0);
  29808. // The request is on the socket before the server accepts the connection,
  29809. // so it does not race the 10 ms floor. Without the floor the connection is
  29810. // closed unread.
  29811. Sockets socks;
  29812. auto sock = INVALID_SOCKET;
  29813. RunningServer running(svr, [&](int port) {
  29814. sock = socks.connect(port);
  29815. send_get(sock);
  29816. });
  29817. EXPECT_TRUE(receives_ok(sock, 1000));
  29818. }
  29819. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29820. using namespace parking_test;
  29821. for (int round = 0; round < 5; round++) {
  29822. SCOPED_TRACE(round);
  29823. Server svr;
  29824. serve_ok(svr, threads(2));
  29825. RunningServer running(svr);
  29826. Sockets socks;
  29827. for (int i = 0; i < 20; i++) {
  29828. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29829. }
  29830. auto start = std::chrono::steady_clock::now();
  29831. svr.stop();
  29832. running.thread.join();
  29833. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29834. std::chrono::milliseconds(500));
  29835. auto deadline = in_ms(1000);
  29836. for (auto s : socks.socks) {
  29837. EXPECT_TRUE(sees_eof(s, deadline));
  29838. }
  29839. }
  29840. }
  29841. #ifdef CPPHTTPLIB_SSL_ENABLED
  29842. namespace parking_test {
  29843. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29844. // that has opened a connection ahead of time. Freeing the session sends no
  29845. // close_notify, so the connection stays quiet.
  29846. bool handshake_only(socket_t sock) {
  29847. auto ctx = tls::create_client_context();
  29848. tls::set_verify_client(ctx, false);
  29849. auto session = tls::create_session(ctx, sock);
  29850. auto se = detail::scope_exit([&] {
  29851. tls::free_session(session);
  29852. tls::free_context(ctx);
  29853. });
  29854. tls::TlsError err;
  29855. return session &&
  29856. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29857. }
  29858. Client tls_client(int port) {
  29859. Client cli("https://127.0.0.1:" + std::to_string(port));
  29860. cli.enable_server_certificate_verification(false);
  29861. cli.set_keep_alive(true);
  29862. cli.set_connection_timeout(1);
  29863. cli.set_read_timeout(1);
  29864. return cli;
  29865. }
  29866. bool tls_get_ok(Client &cli) {
  29867. auto res = cli.Get("/");
  29868. return res && res->body == "ok";
  29869. }
  29870. } // namespace parking_test
  29871. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29872. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29873. struct {
  29874. unsigned long version;
  29875. bool safe;
  29876. } cases[] = {
  29877. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29878. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29879. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29880. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29881. };
  29882. for (const auto &c : cases) {
  29883. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29884. << std::hex << c.version;
  29885. }
  29886. }
  29887. #endif
  29888. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29889. using namespace parking_test;
  29890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29891. ASSERT_TRUE(svr.is_valid());
  29892. serve_ok(svr, threads(1));
  29893. svr.set_read_timeout(1); // so that a failing run does not take long
  29894. RunningServer running(svr);
  29895. Sockets socks;
  29896. // One served connection, some that have not started their handshake, and
  29897. // one that has finished it and gone quiet. None may keep the only worker.
  29898. auto served = tls_client(running.port);
  29899. ASSERT_TRUE(tls_get_ok(served));
  29900. for (int i = 0; i < 10; i++) {
  29901. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29902. }
  29903. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29904. auto other = tls_client(running.port);
  29905. EXPECT_TRUE(tls_get_ok(other));
  29906. EXPECT_TRUE(tls_get_ok(served));
  29907. }
  29908. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29909. using namespace parking_test;
  29910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29911. ASSERT_TRUE(svr.is_valid());
  29912. serve_ok(svr, threads(1));
  29913. RunningServer running(svr);
  29914. Sockets socks;
  29915. auto plain = socks.connect(running.port);
  29916. ASSERT_TRUE(send_get(plain));
  29917. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29918. EXPECT_NE(0, svr.ssl_last_error());
  29919. }
  29920. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29921. using namespace parking_test;
  29922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29923. ASSERT_TRUE(svr.is_valid());
  29924. serve_ok(svr, threads(2));
  29925. RunningServer running(svr);
  29926. std::vector<Client> clients;
  29927. for (int i = 0; i < 5; i++) {
  29928. clients.push_back(tls_client(running.port));
  29929. ASSERT_TRUE(tls_get_ok(clients.back()));
  29930. }
  29931. auto start = std::chrono::steady_clock::now();
  29932. svr.stop();
  29933. running.thread.join();
  29934. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29935. std::chrono::milliseconds(500));
  29936. }
  29937. #endif
  29938. TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
  29939. using namespace parking_test;
  29940. for (auto parking : {false, true}) {
  29941. SCOPED_TRACE(parking);
  29942. Server svr;
  29943. serve_ok(svr, threads(2));
  29944. svr.set_keep_alive_parking(parking);
  29945. std::atomic<int> served{0};
  29946. svr.set_pre_routing_handler([&](const Request &, Response &) {
  29947. served++;
  29948. return Server::HandlerResponse::Unhandled;
  29949. });
  29950. std::atomic<bool> allow{false};
  29951. std::atomic<bool> peer_seen{false};
  29952. svr.set_accept_handler([&](socket_t sock) {
  29953. sockaddr_in addr{};
  29954. socklen_t len = sizeof(addr);
  29955. peer_seen =
  29956. getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
  29957. addr.sin_family == AF_INET &&
  29958. ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
  29959. return allow.load();
  29960. });
  29961. RunningServer running(svr);
  29962. Sockets socks;
  29963. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29964. EXPECT_TRUE(peer_seen);
  29965. EXPECT_EQ(0, served);
  29966. allow = true;
  29967. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29968. EXPECT_EQ(1, served);
  29969. }
  29970. }
  29971. TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
  29972. using namespace parking_test;
  29973. Server svr;
  29974. serve_ok(svr, threads(1));
  29975. svr.set_read_timeout(std::chrono::milliseconds(50));
  29976. std::atomic<bool> timed_out{false};
  29977. svr.set_accept_handler([&](socket_t sock) {
  29978. char c;
  29979. timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
  29980. return true;
  29981. });
  29982. RunningServer running(svr);
  29983. Sockets socks;
  29984. auto sock = socks.connect(running.port);
  29985. EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
  29986. EXPECT_TRUE(get_ok(sock, 1000));
  29987. }
  29988. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  29989. TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
  29990. using namespace parking_test;
  29991. Server svr;
  29992. serve_ok(svr, threads(1));
  29993. std::atomic<bool> throws{true};
  29994. svr.set_accept_handler([&](socket_t) -> bool {
  29995. if (throws) { throw std::runtime_error("refused"); }
  29996. return true;
  29997. });
  29998. std::atomic<int> logged{0};
  29999. svr.set_error_logger([&](const Error &err, const Request *) {
  30000. if (err == Error::UserCallbackException) { logged++; }
  30001. });
  30002. RunningServer running(svr);
  30003. Sockets socks;
  30004. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  30005. EXPECT_EQ(1, logged);
  30006. throws = false;
  30007. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  30008. }
  30009. #endif
  30010. #ifdef CPPHTTPLIB_SSL_ENABLED
  30011. TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
  30012. using namespace parking_test;
  30013. for (auto parking : {false, true}) {
  30014. SCOPED_TRACE(parking);
  30015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  30016. ASSERT_TRUE(svr.is_valid());
  30017. serve_ok(svr, threads(1));
  30018. svr.set_keep_alive_parking(parking);
  30019. svr.set_accept_handler([](socket_t) { return false; });
  30020. RunningServer running(svr);
  30021. Sockets socks;
  30022. // A handshake on a plain request would fail and set ssl_last_error().
  30023. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  30024. EXPECT_EQ(0, svr.ssl_last_error());
  30025. }
  30026. }
  30027. #endif