test.cc 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err);
  83. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  84. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  85. void shutdown(session_t session, bool graceful);
  86. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  87. namespace impl {
  88. SecTrustSettingsResult
  89. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  90. } // namespace impl
  91. #endif
  92. } // namespace tls
  93. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  94. namespace detail {
  95. bool ssl_free_buffers_is_safe(unsigned long version);
  96. } // namespace detail
  97. #endif
  98. } // namespace httplib
  99. #endif
  100. using namespace std;
  101. using namespace httplib;
  102. const char *HOST = "localhost";
  103. static int get_base_port() {
  104. const char *shard = getenv("GTEST_SHARD_INDEX");
  105. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  106. }
  107. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  108. // New standalone tests MUST use svr.bind_to_any_port() instead.
  109. const int PORT = get_base_port();
  110. const string LONG_QUERY_VALUE = string(25000, '@');
  111. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  112. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  113. const string TOO_LONG_QUERY_URL =
  114. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  115. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  116. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  117. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  118. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  119. return file.name == key;
  120. });
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return *it;
  123. #else
  124. if (it != items.end()) { return *it; }
  125. throw std::runtime_error("invalid multipart form data name error");
  126. #endif
  127. }
  128. static void read_file(const std::string &path, std::string &out) {
  129. std::ifstream fs(path, std::ios_base::binary);
  130. if (!fs) {
  131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  132. return;
  133. #else
  134. throw std::runtime_error("File not found: " + path);
  135. #endif
  136. }
  137. fs.seekg(0, std::ios_base::end);
  138. auto size = fs.tellg();
  139. fs.seekg(0);
  140. out.resize(static_cast<size_t>(size));
  141. fs.read(&out[0], static_cast<std::streamsize>(size));
  142. }
  143. class UnixSocketTest : public ::testing::Test {
  144. protected:
  145. void TearDown() override { std::remove(pathname_.c_str()); }
  146. void client_GET(const std::string &addr) {
  147. httplib::Client cli{addr};
  148. cli.set_address_family(AF_UNIX);
  149. ASSERT_TRUE(cli.is_valid());
  150. const auto &result = cli.Get(pattern_);
  151. ASSERT_TRUE(result) << "error: " << result.error();
  152. const auto &resp = result.value();
  153. EXPECT_EQ(resp.status, StatusCode::OK_200);
  154. EXPECT_EQ(resp.body, content_);
  155. }
  156. static std::string make_sock_path() {
  157. const char *shard = getenv("GTEST_SHARD_INDEX");
  158. return shard ? std::string("./httplib-server-") + shard + ".sock"
  159. : "./httplib-server.sock";
  160. }
  161. const std::string pathname_{make_sock_path()};
  162. const std::string pattern_{"/hi"};
  163. const std::string content_{"Hello World!"};
  164. };
  165. TEST_F(UnixSocketTest, pathname) {
  166. httplib::Server svr;
  167. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  168. res.set_content(content_, "text/plain");
  169. });
  170. std::thread t{[&] {
  171. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  172. }};
  173. auto se = detail::scope_exit([&] {
  174. svr.stop();
  175. t.join();
  176. ASSERT_FALSE(svr.is_running());
  177. });
  178. svr.wait_until_ready();
  179. ASSERT_TRUE(svr.is_running());
  180. client_GET(pathname_);
  181. // ".//x.sock", which is not taken for a URL
  182. client_GET("./" + pathname_.substr(1));
  183. }
  184. #if defined(__linux__) || \
  185. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  186. TEST_F(UnixSocketTest, PeerPid) {
  187. httplib::Server svr;
  188. std::string remote_port_val;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. res.set_content(content_, "text/plain");
  191. remote_port_val = std::to_string(req.remote_port);
  192. });
  193. std::thread t{[&] {
  194. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  195. }};
  196. auto se = detail::scope_exit([&] {
  197. svr.stop();
  198. t.join();
  199. ASSERT_FALSE(svr.is_running());
  200. });
  201. svr.wait_until_ready();
  202. ASSERT_TRUE(svr.is_running());
  203. client_GET(pathname_);
  204. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  205. }
  206. #endif
  207. #ifdef __linux__
  208. TEST_F(UnixSocketTest, abstract) {
  209. constexpr char svr_path[]{"\x00httplib-server.sock"};
  210. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  211. httplib::Server svr;
  212. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  213. res.set_content(content_, "text/plain");
  214. });
  215. std::thread t{[&] {
  216. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  217. }};
  218. auto se = detail::scope_exit([&] {
  219. svr.stop();
  220. t.join();
  221. ASSERT_FALSE(svr.is_running());
  222. });
  223. svr.wait_until_ready();
  224. ASSERT_TRUE(svr.is_running());
  225. client_GET(abstract_addr);
  226. }
  227. #endif
  228. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  229. httplib::Server svr;
  230. std::string received_host_header;
  231. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  232. // Capture the Host header sent by the client
  233. auto host_iter = req.headers.find("Host");
  234. if (host_iter != req.headers.end()) {
  235. received_host_header = host_iter->second;
  236. }
  237. res.set_content(content_, "text/plain");
  238. });
  239. std::thread t{[&] {
  240. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  241. }};
  242. auto se = detail::scope_exit([&] {
  243. svr.stop();
  244. t.join();
  245. ASSERT_FALSE(svr.is_running());
  246. });
  247. svr.wait_until_ready();
  248. ASSERT_TRUE(svr.is_running());
  249. // Test that Host header is automatically set to "localhost" for Unix socket
  250. // connections
  251. httplib::Client cli{pathname_};
  252. cli.set_address_family(AF_UNIX);
  253. ASSERT_TRUE(cli.is_valid());
  254. const auto &result = cli.Get(pattern_);
  255. ASSERT_TRUE(result) << "error: " << result.error();
  256. const auto &resp = result.value();
  257. EXPECT_EQ(resp.status, StatusCode::OK_200);
  258. EXPECT_EQ(resp.body, content_);
  259. // Verify that Host header was automatically set to "localhost"
  260. EXPECT_EQ(received_host_header, "localhost");
  261. }
  262. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  263. // Another socket in the working directory, which a Location can name as
  264. // its host
  265. const auto other_path = "other-" + pathname_.substr(2);
  266. httplib::Server svr;
  267. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  268. // An absolute Location naming the Host this client sends
  269. res.set_redirect("http://localhost" + pattern_);
  270. });
  271. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  272. res.set_redirect("http://" + other_path + pattern_);
  273. });
  274. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  275. res.set_redirect("http://mapped.test" + pattern_);
  276. });
  277. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  278. res.set_header("X-Auth", req.get_header_value("Authorization"));
  279. res.set_content(content_, "text/plain");
  280. });
  281. httplib::Server other;
  282. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  283. res.set_content("other", "text/plain");
  284. });
  285. std::thread t{[&] {
  286. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  287. }};
  288. std::thread t2{[&] {
  289. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  290. }};
  291. auto se = detail::scope_exit([&] {
  292. svr.stop();
  293. other.stop();
  294. t.join();
  295. t2.join();
  296. std::remove(other_path.c_str());
  297. });
  298. svr.wait_until_ready();
  299. other.wait_until_ready();
  300. httplib::Client cli{pathname_};
  301. cli.set_address_family(AF_UNIX);
  302. cli.set_follow_location(true);
  303. cli.set_bearer_token_auth("token");
  304. // Another host: the same socket, without the credentials
  305. auto res = cli.Get("/cross");
  306. ASSERT_TRUE(res) << "error: " << res.error();
  307. EXPECT_EQ(StatusCode::OK_200, res->status);
  308. EXPECT_EQ(content_, res->body);
  309. EXPECT_EQ("", res->get_header_value("X-Auth"));
  310. // localhost is this client's own host
  311. res = cli.Get("/redirect");
  312. ASSERT_TRUE(res) << "error: " << res.error();
  313. EXPECT_EQ(StatusCode::OK_200, res->status);
  314. EXPECT_EQ(content_, res->body);
  315. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  316. // A host the caller mapped to a socket goes there
  317. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  318. res = cli.Get("/mapped");
  319. ASSERT_TRUE(res) << "error: " << res.error();
  320. EXPECT_EQ(StatusCode::OK_200, res->status);
  321. EXPECT_EQ("other", res->body);
  322. }
  323. #ifndef _WIN32
  324. TEST(SocketStream, wait_writable_UNIX) {
  325. int fds[2];
  326. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  327. const auto asSocketStream = [&](socket_t fd,
  328. std::function<bool(Stream &)> func) {
  329. return detail::process_client_socket(
  330. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  331. };
  332. asSocketStream(fds[0], [&](Stream &s0) {
  333. EXPECT_EQ(s0.socket(), fds[0]);
  334. EXPECT_TRUE(s0.wait_writable());
  335. EXPECT_TRUE(s0.is_peer_alive());
  336. EXPECT_EQ(0, close(fds[1]));
  337. EXPECT_FALSE(s0.is_peer_alive());
  338. return true;
  339. });
  340. EXPECT_EQ(0, close(fds[0]));
  341. }
  342. TEST(SocketStream, wait_writable_INET) {
  343. sockaddr_in addr;
  344. memset(&addr, 0, sizeof(addr));
  345. addr.sin_family = AF_INET;
  346. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  347. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  348. int disconnected_svr_sock = -1;
  349. std::thread svr{[&] {
  350. const int s = socket(AF_INET, SOCK_STREAM, 0);
  351. ASSERT_LE(0, s);
  352. // PORT + 1 is shared with the SSL redirect tests and with
  353. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  354. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  355. // because that happens on a worker thread the ASSERT does not stop the
  356. // test: it runs on and fails at the disconnected_svr_sock check instead.
  357. default_socket_options(s);
  358. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  359. ASSERT_EQ(0, listen(s, 1));
  360. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  361. ASSERT_EQ(0, close(s));
  362. }};
  363. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  364. std::thread cli{[&] {
  365. const int s = socket(AF_INET, SOCK_STREAM, 0);
  366. ASSERT_LE(0, s);
  367. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  368. ASSERT_EQ(0, close(s));
  369. }};
  370. cli.join();
  371. svr.join();
  372. ASSERT_NE(disconnected_svr_sock, -1);
  373. const auto asSocketStream = [&](socket_t fd,
  374. std::function<bool(Stream &)> func) {
  375. return detail::process_client_socket(
  376. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  377. };
  378. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  379. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  380. // wait_writable() returns true because select_write() only checks if the
  381. // send buffer has space. Peer disconnection is detected later by send().
  382. EXPECT_TRUE(ss.wait_writable());
  383. return true;
  384. });
  385. ASSERT_EQ(0, close(disconnected_svr_sock));
  386. }
  387. #endif // #ifndef _WIN32
  388. TEST(SetSocketOptTest, TcpNoDelay) {
  389. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  390. ASSERT_NE(sock, INVALID_SOCKET);
  391. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  392. int val = 0;
  393. socklen_t len = sizeof(val);
  394. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  395. reinterpret_cast<char *>(&val), &len));
  396. EXPECT_NE(val, 0);
  397. detail::close_socket(sock);
  398. }
  399. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  400. // accept() reports failures through WSAGetLastError() on Windows and through
  401. // errno everywhere else. Asking the wrong one is what made the accept loop
  402. // treat every recoverable failure as fatal on Windows.
  403. struct Classification {
  404. bool resource;
  405. bool transient;
  406. };
  407. auto classify = [](int err) {
  408. #ifdef _WIN32
  409. WSASetLastError(err);
  410. #else
  411. errno = err;
  412. #endif
  413. // Read both before asserting: an assertion may clobber the error slot.
  414. Classification c;
  415. c.resource = detail::is_accept_resource_error();
  416. c.transient = detail::is_accept_transient_error();
  417. return c;
  418. };
  419. #ifdef _WIN32
  420. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  421. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  422. WSAECONNRESET, WSAECONNABORTED};
  423. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  424. #else
  425. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  426. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  427. ECONNABORTED};
  428. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  429. #endif
  430. for (auto err : resource_errors) {
  431. const auto c = classify(err);
  432. EXPECT_TRUE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. for (auto err : transient_errors) {
  436. const auto c = classify(err);
  437. EXPECT_TRUE(c.transient) << "error " << err;
  438. EXPECT_FALSE(c.resource) << "error " << err;
  439. }
  440. for (auto err : fatal_errors) {
  441. const auto c = classify(err);
  442. EXPECT_FALSE(c.resource) << "error " << err;
  443. EXPECT_FALSE(c.transient) << "error " << err;
  444. }
  445. #ifdef _WIN32
  446. WSASetLastError(0);
  447. #else
  448. errno = 0;
  449. #endif
  450. }
  451. TEST(ClientTest, MoveConstructible) {
  452. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  453. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  454. }
  455. TEST(ClientTest, MoveAssignable) {
  456. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  457. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  458. }
  459. #ifdef _WIN32
  460. TEST(StartupTest, WSAStartup) {
  461. WSADATA wsaData;
  462. int ret = WSAStartup(0x0002, &wsaData);
  463. ASSERT_EQ(0, ret);
  464. }
  465. #endif
  466. TEST(DecodePathTest, PercentCharacter) {
  467. EXPECT_EQ(
  468. decode_path_component(
  469. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  470. U8("descrip=Gastos áéíóúñÑ 6"));
  471. }
  472. TEST(DecodePathTest, PercentCharacterNUL) {
  473. string expected;
  474. expected.push_back('x');
  475. expected.push_back('\0');
  476. expected.push_back('x');
  477. EXPECT_EQ(decode_path_component("x%00x"), expected);
  478. }
  479. TEST(DecodePathTest, UnicodeEncoding) {
  480. // %u0041 = 'A' (1-byte UTF-8)
  481. EXPECT_EQ("A", decode_path_component("%u0041"));
  482. // %u00E9 = 'é' (2-byte UTF-8)
  483. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  484. // %u3042 = 'あ' (3-byte UTF-8)
  485. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  486. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  487. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  488. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  489. // neighbours)
  490. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  491. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  492. }
  493. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  494. // A sign or whitespace inside the two-character escape window must not be
  495. // accepted as a valid percent-encoding; the sequence is passed through
  496. // literally, matching decode_uri_component / decode_path_component.
  497. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  498. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  499. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  500. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  501. // Well-formed escapes still decode.
  502. EXPECT_EQ("-", decode_query_component("%2D", false));
  503. EXPECT_EQ("A", decode_query_component("%41", false));
  504. }
  505. TEST(SanitizeFilenameTest, VariousPatterns) {
  506. // Path traversal
  507. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  508. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  509. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  510. // Normal and edge cases
  511. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  512. EXPECT_EQ("filename.txt",
  513. httplib::sanitize_filename("/path/to/filename.txt"));
  514. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  515. EXPECT_EQ("", httplib::sanitize_filename(".."));
  516. EXPECT_EQ("", httplib::sanitize_filename(""));
  517. // Null bytes stripped
  518. EXPECT_EQ("safe.txt",
  519. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  520. // Whitespace-only rejected
  521. EXPECT_EQ("", httplib::sanitize_filename(" "));
  522. }
  523. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  524. // before it is dropped; anywhere else it is an ordinary file name character.
  525. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  526. #ifdef _WIN32
  527. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  528. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  529. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  530. #else
  531. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  532. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  533. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  534. #endif
  535. }
  536. // Forward declaration (see the base64_encode note below): split builds move the
  537. // definition into httplib.cc, so re-declaring it here lets the test link.
  538. namespace httplib {
  539. namespace detail {
  540. bool is_chunked_transfer_encoding(const Headers &headers);
  541. } // namespace detail
  542. } // namespace httplib
  543. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  544. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  545. auto make = [](std::initializer_list<const char *> lines) {
  546. Headers h;
  547. for (auto te : lines) {
  548. if (te) { h.emplace("Transfer-Encoding", te); }
  549. }
  550. return h;
  551. };
  552. // Sole coding, matched case-insensitively.
  553. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  554. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  555. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  556. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  557. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  558. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  560. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  562. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  563. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  564. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  565. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  566. // were received, into one list. Headers preserves that order, so the answer
  567. // is decided by the last coding of the last line and the order the lines
  568. // arrived in is significant.
  569. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  570. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  571. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  572. // The split can fall anywhere in the list.
  573. EXPECT_TRUE(
  574. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  575. EXPECT_FALSE(
  576. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  577. // A trailing line naming no coding leaves the list ending in nothing, so it
  578. // must not inherit the chunked from the line before it.
  579. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  580. }
  581. // Forward declarations (see the base64_encode note below).
  582. namespace httplib {
  583. namespace detail {
  584. bool parse_status_line(const char *line, std::string &version, int &status,
  585. std::string &reason);
  586. std::string file_extension(const std::string &path);
  587. std::string
  588. find_content_type(const std::string &path,
  589. const std::map<std::string, std::string> &user_data,
  590. const std::string &default_content_type);
  591. bool can_compress_content_type(const std::string &content_type);
  592. bool is_prohibited_header_name(const std::string &name);
  593. bool is_valid_path(const std::string &path);
  594. #ifdef CPPHTTPLIB_SSL_ENABLED
  595. bool match_hostname(const std::string &pattern, const std::string &hostname);
  596. #endif
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  600. struct {
  601. const char *line;
  602. const char *version;
  603. int status;
  604. const char *reason;
  605. } cases[] = {
  606. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  607. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  608. // The reason phrase may be empty, or left out along with its space.
  609. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  610. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  611. };
  612. for (const auto &c : cases) {
  613. std::string version;
  614. int status = 0;
  615. std::string reason = "unset";
  616. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  617. << c.line;
  618. EXPECT_EQ(c.version, version);
  619. EXPECT_EQ(c.status, status);
  620. EXPECT_EQ(c.reason, reason);
  621. }
  622. }
  623. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  624. const char *lines[] = {
  625. "HTTP/2 200 OK\r\n",
  626. "HTTP/1.2 200 OK\r\n",
  627. "HTTP/1.1 20 OK\r\n",
  628. "HTTP/1.1 2000 OK\r\n",
  629. "HTTP/1.1 2x0 OK\r\n",
  630. "HTTP/1.1 200 OK\r\n",
  631. "HTTP/1.1 200OK\r\n",
  632. "HTTP/1.1 200 O\rK\r\n",
  633. "HTTP/1.1 200 OK",
  634. "HTTP/1.1 200 OK\r\nX",
  635. "",
  636. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  637. "HTTP/1.1 200 OK\n",
  638. #endif
  639. };
  640. for (auto line : lines) {
  641. std::string version;
  642. int status = 0;
  643. std::string reason;
  644. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  645. << line;
  646. }
  647. }
  648. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  649. // Long enough to overflow the stack when matched with std::regex.
  650. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  651. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  652. std::string version;
  653. int status = 0;
  654. std::string reason;
  655. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  656. EXPECT_EQ(200, status);
  657. EXPECT_EQ(long_reason, reason);
  658. }
  659. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  660. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  661. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  662. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  663. EXPECT_EQ("", detail::file_extension("noext"));
  664. EXPECT_EQ("", detail::file_extension("a."));
  665. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  666. EXPECT_EQ("", detail::file_extension("a.b-c"));
  667. // Long enough to overflow the stack when matched with std::regex.
  668. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  669. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  670. }
  671. #ifdef CPPHTTPLIB_SSL_ENABLED
  672. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  673. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  674. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  675. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  676. // A wildcard needs two labels after it, in the leftmost label only
  677. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  678. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  679. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  680. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  681. EXPECT_FALSE(
  682. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  683. // No name may have an empty label
  684. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  685. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  686. }
  687. #endif
  688. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  689. detail::case_ignore::hash hash;
  690. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  691. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  692. // Long enough to overflow the stack if hashed one call per character.
  693. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  694. }
  695. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  696. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  697. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  698. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  699. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  700. // Same 26-bit hash as html, svg and js.
  701. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  702. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  703. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  704. }
  705. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  706. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  707. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  708. }
  709. }
  710. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  711. // name anywhere else.
  712. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  713. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  714. #ifdef _WIN32
  715. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  716. #else
  717. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  718. #endif
  719. }
  720. }
  721. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  722. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  723. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  724. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  725. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  726. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  727. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  728. // Same 26-bit hash as application/json.
  729. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  730. }
  731. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  732. Request req;
  733. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  734. EXPECT_TRUE(req.is_multipart_form_data());
  735. std::string boundary;
  736. EXPECT_TRUE(detail::parse_multipart_boundary(
  737. req.get_header_value("Content-Type"), boundary));
  738. EXPECT_EQ("x", boundary);
  739. }
  740. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  741. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  742. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  743. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  744. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  745. // Same 26-bit hash as REMOTE_ADDR.
  746. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  747. }
  748. // Forward declaration: in split builds split.py strips `inline` and moves the
  749. // definition into httplib.cc, so detail::base64_encode is not visible from the
  750. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  751. // in both header-only and split builds.
  752. namespace httplib {
  753. namespace detail {
  754. std::string base64_encode(const std::string &in);
  755. } // namespace detail
  756. } // namespace httplib
  757. TEST(Base64EncodeTest, KnownAnswers) {
  758. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  759. // where the accumulator's top bit is already set before the next shift.
  760. EXPECT_EQ("", detail::base64_encode(""));
  761. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  762. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  763. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  764. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  765. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  766. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  767. // High bytes keep the top bit set across several rounds.
  768. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  769. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  770. }
  771. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  772. string unescapedCharacters = "-_.!~*'()";
  773. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  774. }
  775. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  776. string reservedCharacters = ";,/?:@&=+$";
  777. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  778. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  779. }
  780. TEST(ClientQueryOrder, PreserveOrder) {
  781. // This test reproduces Issue #2259: client may reorder query parameters
  782. // when sending a GET request. The expected behavior is that the client
  783. // preserves the original query string order when the caller supplied it
  784. // as part of the path.
  785. Server svr;
  786. svr.Get("/", [&](const Request &req, Response &res) {
  787. // Echo back the raw target so the test can assert ordering
  788. res.set_content(req.target, "text/plain");
  789. });
  790. std::thread t{[&] { svr.listen(HOST, PORT); }};
  791. auto se = detail::scope_exit([&] {
  792. svr.stop();
  793. t.join();
  794. ASSERT_FALSE(svr.is_running());
  795. });
  796. svr.wait_until_ready();
  797. Client cli(HOST, PORT);
  798. ASSERT_TRUE(cli.is_valid());
  799. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  800. auto res = cli.Get(original);
  801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  802. // Expect the echoed target to exactly match the original path (order
  803. // preserved)
  804. EXPECT_EQ(res->body, original);
  805. }
  806. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  807. string chineseCharacters = U8("中国語");
  808. string russianCharacters = U8("дом");
  809. string brazilianCharacters = U8("óculos");
  810. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  811. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  812. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  813. "%D0%B4%D0%BE%D0%BC");
  814. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  815. }
  816. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  817. string unescapedCharacters = "-_.!~*'()";
  818. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  819. }
  820. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  821. string reservedCharacters = ";,/?:@&=+$";
  822. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  823. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  824. }
  825. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  826. string chineseCharacters = U8("中国語");
  827. string russianCharacters = U8("дом");
  828. string brazilianCharacters = U8("óculos");
  829. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  830. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  831. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  832. "%D0%B4%D0%BE%D0%BC");
  833. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  834. }
  835. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  836. // Issue #2082 use case: encoding path component with ampersand
  837. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  838. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  839. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  840. }
  841. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  842. string unescapedCharacters = "-_.!~*'()";
  843. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  844. }
  845. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  846. string reservedCharacters = ";,/?:@&=+$#";
  847. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  848. }
  849. TEST(EncodeUriTest, TestUTF8Characters) {
  850. string chineseCharacters = U8("中国語");
  851. string russianCharacters = U8("дом");
  852. string brazilianCharacters = U8("óculos");
  853. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  854. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  855. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  856. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  857. }
  858. TEST(EncodeUriTest, TestCompleteUri) {
  859. string uri =
  860. "https://example.com/path/to/resource?query=value&param=test#fragment";
  861. EXPECT_EQ(
  862. httplib::encode_uri(uri),
  863. "https://example.com/path/to/resource?query=value&param=test#fragment");
  864. }
  865. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  866. string uri =
  867. "https://example.com/path with spaces/file name.html?q=hello world";
  868. EXPECT_EQ(httplib::encode_uri(uri),
  869. "https://example.com/path%20with%20spaces/"
  870. "file%20name.html?q=hello%20world");
  871. }
  872. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  873. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  875. }
  876. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  877. string unescapedCharacters = "-_.!~*'()";
  878. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  879. }
  880. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  881. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  882. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  883. string encodedBrazilian = "%C3%B3culos";
  884. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  885. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  886. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  887. }
  888. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  889. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  890. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  891. "Piri Tommy Villiers - on & on");
  892. }
  893. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  894. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  895. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  896. }
  897. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  898. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  899. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  900. }
  901. TEST(DecodeUriTest, TestUTF8Characters) {
  902. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  903. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  904. string encodedBrazilian = "%C3%B3culos";
  905. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  906. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  907. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  908. }
  909. TEST(DecodeUriTest, TestCompleteUri) {
  910. string encodedUri = "https://example.com/path%20with%20spaces/"
  911. "file%20name.html?q=hello%20world";
  912. EXPECT_EQ(
  913. httplib::decode_uri(encodedUri),
  914. "https://example.com/path with spaces/file name.html?q=hello world");
  915. }
  916. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  917. string original =
  918. "https://example.com/path with spaces/file name.html?q=hello world";
  919. string encoded = httplib::encode_uri(original);
  920. string decoded = httplib::decode_uri(encoded);
  921. EXPECT_EQ(decoded, original);
  922. }
  923. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  924. // decode_uri is the inverse of encode_uri: an escaped reserved character
  925. // stays encoded so it is not promoted into a real delimiter, while
  926. // non-reserved escapes still decode (like JS decodeURI).
  927. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  928. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  929. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  930. "%3F%3A%40%26%3D%2B%24%2C%3B");
  931. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  932. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  933. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  934. "http://example.com/a%2Fb");
  935. // decode_uri_component still decodes the reserved character.
  936. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  937. }
  938. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  939. string original = "Piri Tommy Villiers - on & on";
  940. string encoded = httplib::encode_uri_component(original);
  941. string decoded = httplib::decode_uri_component(encoded);
  942. EXPECT_EQ(decoded, original);
  943. }
  944. TEST(TrimTests, TrimStringTests) {
  945. EXPECT_EQ("abc", detail::trim_copy("abc"));
  946. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  947. EXPECT_TRUE(detail::trim_copy("").empty());
  948. }
  949. TEST(AsciiTest, LocaleIndependentClassification) {
  950. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  951. // which consult the global C locale: std::isalnum(0xC5) can return true
  952. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  953. // helpers must classify every byte by the ASCII grammar alone.
  954. for (int i = 0; i < 256; i++) {
  955. auto c = static_cast<char>(i);
  956. auto is_digit = i >= '0' && i <= '9';
  957. auto is_upper = i >= 'A' && i <= 'Z';
  958. auto is_lower = i >= 'a' && i <= 'z';
  959. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  960. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  961. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  962. << "byte " << i;
  963. }
  964. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  965. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  966. // Non-ASCII bytes must be percent-encoded, never passed through as
  967. // alphanumeric.
  968. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  969. }
  970. TEST(FromCharsTest, Double) {
  971. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  972. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  973. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  974. auto parse = [](const std::string &s, double &v) {
  975. return detail::from_chars(s.data(), s.data() + s.size(), v);
  976. };
  977. double v = -1.0;
  978. // Representative quality values.
  979. EXPECT_EQ(parse("0", v).ec, std::errc{});
  980. EXPECT_DOUBLE_EQ(v, 0.0);
  981. EXPECT_EQ(parse("1", v).ec, std::errc{});
  982. EXPECT_DOUBLE_EQ(v, 1.0);
  983. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  984. EXPECT_DOUBLE_EQ(v, 0.8);
  985. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 0.001);
  987. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  988. EXPECT_DOUBLE_EQ(v, 1.0);
  989. // A missing integer or fractional part is tolerated.
  990. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.5);
  992. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  993. EXPECT_DOUBLE_EQ(v, 5.0);
  994. // Values outside [0, 1] still parse; the caller range-checks them.
  995. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  996. EXPECT_DOUBLE_EQ(v, 123.456);
  997. // Stops at the first byte that is not part of the number and reports where.
  998. std::string trailing = "0.9, text/html";
  999. auto r = parse(trailing, v);
  1000. EXPECT_EQ(r.ec, std::errc{});
  1001. EXPECT_DOUBLE_EQ(v, 0.9);
  1002. EXPECT_EQ(*r.ptr, ',');
  1003. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1004. // outright, and an 'e'/'E' simply ends the number.
  1005. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1007. std::string exp_input = "1.5e3";
  1008. r = parse(exp_input, v);
  1009. EXPECT_EQ(r.ec, std::errc{});
  1010. EXPECT_DOUBLE_EQ(v, 1.5);
  1011. EXPECT_EQ(*r.ptr, 'e');
  1012. // Invalid inputs.
  1013. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1014. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1015. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1016. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1017. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1018. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1019. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1020. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1021. std::errc{});
  1022. EXPECT_DOUBLE_EQ(v, 0.0);
  1023. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1024. std::errc{});
  1025. EXPECT_GE(v, 0.0);
  1026. EXPECT_LE(v, 1.0);
  1027. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1028. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1029. }
  1030. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1031. // Simple case without quality values
  1032. std::vector<std::string> result1;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html,application/json,text/plain", result1));
  1035. EXPECT_EQ(result1.size(), 3U);
  1036. EXPECT_EQ(result1[0], "text/html");
  1037. EXPECT_EQ(result1[1], "application/json");
  1038. EXPECT_EQ(result1[2], "text/plain");
  1039. // With quality values
  1040. std::vector<std::string> result2;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1043. EXPECT_EQ(result2.size(), 3U);
  1044. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1045. EXPECT_EQ(result2[1], "text/html");
  1046. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1047. }
  1048. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1049. // Mixed with and without quality values
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(
  1052. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1053. EXPECT_EQ(result.size(), 3U);
  1054. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1055. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1056. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1057. }
  1058. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1059. // Empty header
  1060. std::vector<std::string> empty_result;
  1061. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1062. EXPECT_TRUE(empty_result.empty());
  1063. // Single type
  1064. std::vector<std::string> single_result;
  1065. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1066. EXPECT_EQ(single_result.size(), 1U);
  1067. EXPECT_EQ(single_result[0], "application/json");
  1068. // Wildcard types
  1069. std::vector<std::string> wildcard_result;
  1070. EXPECT_TRUE(detail::parse_accept_header(
  1071. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1072. EXPECT_EQ(wildcard_result.size(), 3U);
  1073. EXPECT_EQ(wildcard_result[0], "application/json");
  1074. EXPECT_EQ(wildcard_result[1], "text/*");
  1075. EXPECT_EQ(wildcard_result[2], "*/*");
  1076. }
  1077. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1078. // Common browser Accept header
  1079. std::vector<std::string> browser_result;
  1080. EXPECT_TRUE(
  1081. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1082. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1083. browser_result));
  1084. EXPECT_EQ(browser_result.size(), 6U);
  1085. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1086. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1087. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1088. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1089. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1090. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1091. // API client header
  1092. std::vector<std::string> api_result;
  1093. EXPECT_TRUE(detail::parse_accept_header(
  1094. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1095. api_result));
  1096. EXPECT_EQ(api_result.size(), 3U);
  1097. EXPECT_EQ(api_result[0], "application/json");
  1098. EXPECT_EQ(api_result[1], "application/xml");
  1099. EXPECT_EQ(api_result[2], "text/plain");
  1100. }
  1101. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1102. // Quality value with 3 decimal places
  1103. std::vector<std::string> decimal_result;
  1104. EXPECT_TRUE(detail::parse_accept_header(
  1105. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1106. EXPECT_EQ(decimal_result.size(), 2U);
  1107. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1108. EXPECT_EQ(decimal_result[1], "text/html");
  1109. // Zero quality (should still be included but with lowest priority)
  1110. std::vector<std::string> zero_q_result;
  1111. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1112. zero_q_result));
  1113. EXPECT_EQ(zero_q_result.size(), 2U);
  1114. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1115. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1116. // No spaces around commas
  1117. std::vector<std::string> no_space_result;
  1118. EXPECT_TRUE(detail::parse_accept_header(
  1119. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1120. no_space_result));
  1121. EXPECT_EQ(no_space_result.size(), 3U);
  1122. EXPECT_EQ(no_space_result[0], "text/html");
  1123. EXPECT_EQ(no_space_result[1], "application/json");
  1124. EXPECT_EQ(no_space_result[2], "text/plain");
  1125. }
  1126. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1127. // Quality values always use '.' as the decimal separator, so parsing must
  1128. // not depend on the process locale. An embedding application may have
  1129. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1130. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1131. std::string saved = cur ? cur : "C";
  1132. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1133. "fr_FR.UTF-8"};
  1134. bool switched = false;
  1135. for (const auto loc : comma_locales) {
  1136. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1137. std::localeconv()->decimal_point[0] == ',') {
  1138. switched = true;
  1139. break;
  1140. }
  1141. }
  1142. if (!switched) {
  1143. std::setlocale(LC_NUMERIC, saved.c_str());
  1144. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1145. }
  1146. // The higher-weighted type appears later in the list, so a correct parse
  1147. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1148. // sensitive parse reads both weights as 0 and leaves the original order.
  1149. std::vector<std::string> result;
  1150. EXPECT_TRUE(detail::parse_accept_header(
  1151. "application/json;q=0.1,text/html;q=0.9", result));
  1152. ASSERT_EQ(result.size(), 2U);
  1153. EXPECT_EQ(result[0], "text/html");
  1154. EXPECT_EQ(result[1], "application/json");
  1155. std::setlocale(LC_NUMERIC, saved.c_str());
  1156. }
  1157. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1158. std::vector<std::string> result;
  1159. // Invalid quality value (> 1.0)
  1160. EXPECT_FALSE(
  1161. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1162. // Invalid quality value (< 0.0)
  1163. EXPECT_FALSE(
  1164. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1165. // Invalid quality value (not a number)
  1166. EXPECT_FALSE(detail::parse_accept_header(
  1167. "text/html;q=invalid,application/json", result));
  1168. // A valid numeric prefix does not make the entire quality value valid.
  1169. EXPECT_FALSE(detail::parse_accept_header(
  1170. "text/html;q=0.5junk,application/json", result));
  1171. // Empty quality value
  1172. EXPECT_FALSE(
  1173. detail::parse_accept_header("text/html;q=,application/json", result));
  1174. // Invalid media type format (no slash and not wildcard)
  1175. EXPECT_FALSE(
  1176. detail::parse_accept_header("invalidtype,application/json", result));
  1177. // Valid cases should still work
  1178. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1179. EXPECT_EQ(result.size(), 1U);
  1180. EXPECT_EQ(result[0], "*/*");
  1181. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1182. EXPECT_EQ(result.size(), 1U);
  1183. EXPECT_EQ(result[0], "*");
  1184. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1185. EXPECT_EQ(result.size(), 1U);
  1186. EXPECT_EQ(result[0], "text/*");
  1187. }
  1188. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1189. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1190. // and must not be answered with 400 Bad Request.
  1191. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1192. struct {
  1193. const char *value;
  1194. std::vector<std::string> expected;
  1195. } cases[] = {
  1196. {",application/json", {"application/json"}},
  1197. {"text/html,", {"text/html"}},
  1198. {"text/html,,*/*", {"text/html", "*/*"}},
  1199. // An empty element may be spelled with whitespace in it
  1200. {"text/html, , application/json", {"text/html", "application/json"}},
  1201. // Nothing but empty elements is an empty list, which means the same
  1202. // thing as no Accept header at all
  1203. {",,,", {}},
  1204. // Quality values still apply across ignored empty elements
  1205. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1206. };
  1207. for (const auto &c : cases) {
  1208. std::vector<std::string> result;
  1209. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1210. << "value: " << c.value;
  1211. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1212. }
  1213. // An invalid entry is still rejected when empty elements surround it
  1214. std::vector<std::string> result;
  1215. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1216. }
  1217. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1218. // or ';' inside one does not end the list element or the parameter. Section
  1219. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1220. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1221. struct {
  1222. const char *value;
  1223. std::vector<std::string> expected;
  1224. } cases[] = {
  1225. {"text/html;profile=\"a,b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // A "q=" inside a quoted value is not the weight
  1228. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1229. {"text/html", "application/json"}},
  1230. // The weight after a quoted value still applies
  1231. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1232. {"application/json", "text/html"}},
  1233. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1234. {"application/json", "text/html"}},
  1235. {"text/html;profile=\"a\\\"b\",application/json",
  1236. {"text/html", "application/json"}},
  1237. // An escaped backslash does not escape the '"' after it
  1238. {"text/html;profile=\"a\\\\\",application/json",
  1239. {"text/html", "application/json"}},
  1240. };
  1241. for (const auto &c : cases) {
  1242. std::vector<std::string> result;
  1243. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1244. << "value: " << c.value;
  1245. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1246. }
  1247. }
  1248. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1249. Server svr;
  1250. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1251. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1252. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1253. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1254. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1255. res.set_content("ok", "text/plain");
  1256. });
  1257. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1258. EXPECT_TRUE(false);
  1259. res.set_content("bad request", "text/plain");
  1260. });
  1261. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1262. auto se = detail::scope_exit([&] {
  1263. svr.stop();
  1264. listen_thread.join();
  1265. ASSERT_FALSE(svr.is_running());
  1266. });
  1267. svr.wait_until_ready();
  1268. Client cli("localhost", PORT);
  1269. {
  1270. auto res = cli.Get(
  1271. "/accept_ok",
  1272. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1274. EXPECT_EQ(StatusCode::OK_200, res->status);
  1275. }
  1276. {
  1277. auto res = cli.Get("/accept_bad_request",
  1278. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1281. }
  1282. }
  1283. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1284. Server svr;
  1285. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1286. res.set_content("ok", "text/plain");
  1287. });
  1288. std::atomic<int> start_count{0};
  1289. std::atomic<bool> running_when_called{false};
  1290. svr.set_start_handler([&]() {
  1291. running_when_called = svr.is_running();
  1292. start_count++;
  1293. });
  1294. auto port = svr.bind_to_any_port(HOST);
  1295. std::thread t([&]() { svr.listen_after_bind(); });
  1296. auto se = detail::scope_exit([&] {
  1297. svr.stop();
  1298. t.join();
  1299. ASSERT_FALSE(svr.is_running());
  1300. });
  1301. svr.wait_until_ready();
  1302. // A successful request proves the accept loop is running, which the start
  1303. // handler precedes; so by now the handler must have run exactly once.
  1304. Client cli(HOST, port);
  1305. cli.set_connection_timeout(std::chrono::seconds(5));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1308. EXPECT_EQ(StatusCode::OK_200, res->status);
  1309. EXPECT_EQ(1, start_count.load());
  1310. EXPECT_TRUE(running_when_called.load());
  1311. }
  1312. TEST(DivideTest, DivideStringTests) {
  1313. auto divide = [](const std::string &str, char d) {
  1314. std::string lhs;
  1315. std::string rhs;
  1316. detail::divide(str, d,
  1317. [&](const char *lhs_data, std::size_t lhs_size,
  1318. const char *rhs_data, std::size_t rhs_size) {
  1319. lhs.assign(lhs_data, lhs_size);
  1320. rhs.assign(rhs_data, rhs_size);
  1321. });
  1322. return std::make_pair(std::move(lhs), std::move(rhs));
  1323. };
  1324. {
  1325. const auto res = divide("", '=');
  1326. EXPECT_EQ(res.first, "");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("=", '=');
  1331. EXPECT_EQ(res.first, "");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide(" ", '=');
  1336. EXPECT_EQ(res.first, " ");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("a", '=');
  1341. EXPECT_EQ(res.first, "a");
  1342. EXPECT_EQ(res.second, "");
  1343. }
  1344. {
  1345. const auto res = divide("a=", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "");
  1348. }
  1349. {
  1350. const auto res = divide("=b", '=');
  1351. EXPECT_EQ(res.first, "");
  1352. EXPECT_EQ(res.second, "b");
  1353. }
  1354. {
  1355. const auto res = divide("a=b", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b");
  1358. }
  1359. {
  1360. const auto res = divide("a=b=", '=');
  1361. EXPECT_EQ(res.first, "a");
  1362. EXPECT_EQ(res.second, "b=");
  1363. }
  1364. {
  1365. const auto res = divide("a=b=c", '=');
  1366. EXPECT_EQ(res.first, "a");
  1367. EXPECT_EQ(res.second, "b=c");
  1368. }
  1369. }
  1370. TEST(SplitTest, ParseQueryString) {
  1371. string s = "key1=val1&key2=val2&key3=val3";
  1372. Params dic;
  1373. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1374. [&](const char *b, const char *e) {
  1375. string key, val;
  1376. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1377. if (key.empty()) {
  1378. key.assign(b2, e2);
  1379. } else {
  1380. val.assign(b2, e2);
  1381. }
  1382. });
  1383. dic.emplace(key, val);
  1384. });
  1385. EXPECT_EQ("val1", dic.find("key1")->second);
  1386. EXPECT_EQ("val2", dic.find("key2")->second);
  1387. EXPECT_EQ("val3", dic.find("key3")->second);
  1388. }
  1389. TEST(SplitTest, ParseInvalidQueryTests) {
  1390. {
  1391. string s = " ";
  1392. Params dict;
  1393. detail::parse_query_text(s, dict);
  1394. EXPECT_TRUE(dict.empty());
  1395. }
  1396. {
  1397. string s = " = =";
  1398. Params dict;
  1399. detail::parse_query_text(s, dict);
  1400. EXPECT_TRUE(dict.empty());
  1401. }
  1402. }
  1403. TEST(ParseQueryTest, ParseQueryString) {
  1404. {
  1405. std::string s = "key1=val1&key2=val2&key3=val3";
  1406. Params dic;
  1407. detail::parse_query_text(s, dic);
  1408. EXPECT_EQ("val1", dic.find("key1")->second);
  1409. EXPECT_EQ("val2", dic.find("key2")->second);
  1410. EXPECT_EQ("val3", dic.find("key3")->second);
  1411. }
  1412. {
  1413. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1414. Params dic;
  1415. detail::parse_query_text(s, dic);
  1416. EXPECT_EQ("", dic.find("key1")->second);
  1417. EXPECT_EQ("val1", dic.find("key2")->second);
  1418. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1419. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1420. }
  1421. }
  1422. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1423. Params dic;
  1424. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1425. dic.emplace("key1", "val1");
  1426. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1427. dic.emplace("key2", "val2");
  1428. dic.emplace("key3", "val3");
  1429. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1430. }
  1431. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1432. Params params;
  1433. params.emplace("a", "1");
  1434. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1435. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1436. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1437. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1438. // Long enough to overflow the stack when matched with std::regex.
  1439. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1440. EXPECT_EQ("/p?" + long_query + "&a=1",
  1441. append_query_params("/p?" + long_query, params));
  1442. }
  1443. // Joins every entry of a Headers or Params into "key=value " so a whole
  1444. // traversal can be compared in one assertion. Both are instantiations of the
  1445. // same insertion-ordered container, so one helper serves both.
  1446. template <typename Map> static std::string entries_to_string(const Map &m) {
  1447. std::string s;
  1448. for (const auto &entry : m) {
  1449. s += entry.first + "=" + entry.second + " ";
  1450. }
  1451. return s;
  1452. }
  1453. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1454. // Params used to be a std::multimap, which sorted by name and handed the
  1455. // caller's query back alphabetised. A client signing its query string could
  1456. // not reproduce the order it asked for.
  1457. Params dic;
  1458. dic.emplace("zulu", "1");
  1459. dic.emplace("alpha", "2");
  1460. dic.emplace("mike", "3");
  1461. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1462. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1463. }
  1464. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1465. Params dic;
  1466. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1467. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1468. }
  1469. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1470. Request req;
  1471. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1472. req.params);
  1473. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1474. EXPECT_EQ("first", req.get_param_value("tag"));
  1475. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1476. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1477. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1478. EXPECT_EQ("", req.get_param_value("tag", 3));
  1479. }
  1480. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1481. // Params shares its container with Headers, which matches field names
  1482. // case-insensitively. Parameter names must not pick that up.
  1483. Params dic;
  1484. dic.emplace("Key", "upper");
  1485. dic.emplace("key", "lower");
  1486. EXPECT_EQ(2U, dic.size());
  1487. EXPECT_EQ(1U, dic.count("Key"));
  1488. EXPECT_EQ(1U, dic.count("key"));
  1489. EXPECT_EQ("upper", dic.find("Key")->second);
  1490. EXPECT_EQ("lower", dic.find("key")->second);
  1491. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1492. }
  1493. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1494. Server svr;
  1495. std::string order;
  1496. svr.Get("/order", [&](const Request &req, Response &res) {
  1497. order = entries_to_string(req.params);
  1498. res.set_content("ok", "text/plain");
  1499. });
  1500. auto port = svr.bind_to_any_port(HOST);
  1501. thread t = thread([&] { svr.listen_after_bind(); });
  1502. auto se = detail::scope_exit([&] {
  1503. svr.stop();
  1504. t.join();
  1505. ASSERT_FALSE(svr.is_running());
  1506. });
  1507. svr.wait_until_ready();
  1508. Client cli(HOST, port);
  1509. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1510. ASSERT_TRUE(res);
  1511. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1512. }
  1513. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1514. Server svr;
  1515. std::string field_order, file_order;
  1516. svr.Post("/order", [&](const Request &req, Response &res) {
  1517. for (const auto &field : req.form.fields) {
  1518. field_order += field.first + "=" + field.second.content + " ";
  1519. }
  1520. for (const auto &file : req.form.files) {
  1521. file_order += file.first + "=" + file.second.filename + " ";
  1522. }
  1523. res.set_content("ok", "text/plain");
  1524. });
  1525. auto port = svr.bind_to_any_port(HOST);
  1526. thread t = thread([&] { svr.listen_after_bind(); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. t.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. UploadFormDataItems items = {
  1534. {"zulu", "1", "", ""},
  1535. {"alpha", "2", "", ""},
  1536. {"mike", "3", "", ""},
  1537. {"zebra", "z", "z.txt", "text/plain"},
  1538. {"apple", "a", "a.txt", "text/plain"},
  1539. };
  1540. Client cli(HOST, port);
  1541. auto res = cli.Post("/order", items);
  1542. ASSERT_TRUE(res);
  1543. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1544. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1545. }
  1546. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1547. Server svr;
  1548. std::vector<std::string> values;
  1549. std::string first, second, out_of_range, order;
  1550. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1551. values = req.form.get_fields("tag");
  1552. first = req.form.get_field("tag", 0);
  1553. second = req.form.get_field("tag", 1);
  1554. out_of_range = req.form.get_field("tag", 2);
  1555. for (const auto &field : req.form.fields) {
  1556. order += field.first + "=" + field.second.content + " ";
  1557. }
  1558. res.set_content("ok", "text/plain");
  1559. });
  1560. auto port = svr.bind_to_any_port(HOST);
  1561. thread t = thread([&] { svr.listen_after_bind(); });
  1562. auto se = detail::scope_exit([&] {
  1563. svr.stop();
  1564. t.join();
  1565. ASSERT_FALSE(svr.is_running());
  1566. });
  1567. svr.wait_until_ready();
  1568. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1569. // not adjacent in the container.
  1570. UploadFormDataItems items = {
  1571. {"tag", "first", "", ""},
  1572. {"other", "x", "", ""},
  1573. {"tag", "second", "", ""},
  1574. };
  1575. Client cli(HOST, port);
  1576. auto res = cli.Post("/repeated", items);
  1577. ASSERT_TRUE(res);
  1578. ASSERT_EQ(2U, values.size());
  1579. EXPECT_EQ("first", values[0]);
  1580. EXPECT_EQ("second", values[1]);
  1581. EXPECT_EQ("first", first);
  1582. EXPECT_EQ("second", second);
  1583. // std::multimap already kept entries sharing a name in insertion order, so
  1584. // everything above passes without this change too. The whole traversal is
  1585. // what tells the two apart: sorting by name would hoist "other" to the front
  1586. // and the two "tag" parts would end up adjacent.
  1587. EXPECT_EQ("tag=first other=x tag=second ", order);
  1588. // Advancing past the last entry of a name used to run off the container;
  1589. // the container's saturating increment makes it return the default instead.
  1590. EXPECT_EQ("", out_of_range);
  1591. }
  1592. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1593. Server svr;
  1594. std::string file_names;
  1595. svr.Post("/upload", [&](const Request &req, Response &res) {
  1596. for (const auto &file : req.form.files) {
  1597. file_names += file.first + "|" + file.second.filename + " ";
  1598. }
  1599. res.set_content("ok", "text/plain");
  1600. });
  1601. auto port = svr.bind_to_any_port(HOST);
  1602. thread t = thread([&] { svr.listen_after_bind(); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. t.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. // A trailing backslash would otherwise escape the closing quote.
  1610. UploadFormDataItems items = {
  1611. {"dir\\", "x", "a.txt", "text/plain"},
  1612. {"b", "y", "a\\\\b.txt", "text/plain"},
  1613. };
  1614. Client cli(HOST, port);
  1615. auto res = cli.Post("/upload", items);
  1616. ASSERT_TRUE(res);
  1617. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1618. }
  1619. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1620. // Server::read_content() keeps a FormFields::iterator alive across the
  1621. // content callbacks that fill the part it points at. The container is
  1622. // vector-backed, so a later emplace can reallocate and invalidate an older
  1623. // iterator; 64 parts grow the vector through seven reallocations, which
  1624. // checks that every part's content still lands in its own entry.
  1625. const size_t part_count = 64;
  1626. // One formula for both the parts sent and the values expected back, so the
  1627. // two cannot drift apart.
  1628. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1629. auto content_of = [](size_t i) {
  1630. return std::string(64, static_cast<char>('a' + (i % 26)));
  1631. };
  1632. Server svr;
  1633. std::vector<std::pair<std::string, std::string>> received;
  1634. svr.Post("/many", [&](const Request &req, Response &res) {
  1635. for (const auto &field : req.form.fields) {
  1636. received.emplace_back(field.first, field.second.content);
  1637. }
  1638. res.set_content("ok", "text/plain");
  1639. });
  1640. auto port = svr.bind_to_any_port(HOST);
  1641. thread t = thread([&] { svr.listen_after_bind(); });
  1642. auto se = detail::scope_exit([&] {
  1643. svr.stop();
  1644. t.join();
  1645. ASSERT_FALSE(svr.is_running());
  1646. });
  1647. svr.wait_until_ready();
  1648. UploadFormDataItems items;
  1649. for (size_t i = 0; i < part_count; i++) {
  1650. items.push_back({name_of(i), content_of(i), "", ""});
  1651. }
  1652. Client cli(HOST, port);
  1653. auto res = cli.Post("/many", items);
  1654. ASSERT_TRUE(res);
  1655. ASSERT_EQ(part_count, received.size());
  1656. for (size_t i = 0; i < part_count; i++) {
  1657. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1658. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1659. }
  1660. }
  1661. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1662. string content_type = "multipart/form-data; boundary=something";
  1663. string boundary;
  1664. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(boundary, "something");
  1667. }
  1668. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1669. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1670. string boundary;
  1671. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1672. EXPECT_TRUE(ret);
  1673. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1674. }
  1675. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1676. string content_type =
  1677. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1678. string boundary;
  1679. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1680. EXPECT_TRUE(ret);
  1681. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1682. }
  1683. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1684. string content_type =
  1685. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1686. string boundary;
  1687. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1688. EXPECT_TRUE(ret);
  1689. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1690. }
  1691. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1692. const string boundary(70, 'a');
  1693. string content_type = "multipart/form-data; boundary=" + boundary;
  1694. string parsed;
  1695. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1696. EXPECT_TRUE(ret);
  1697. EXPECT_EQ(parsed, boundary);
  1698. }
  1699. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1700. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1701. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1702. string parsed;
  1703. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1704. EXPECT_FALSE(ret);
  1705. }
  1706. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1707. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1708. // is 72 characters on the wire and still valid.
  1709. const string boundary(70, 'a');
  1710. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1711. string parsed;
  1712. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1713. EXPECT_EQ(parsed, boundary);
  1714. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1715. parsed.clear();
  1716. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1719. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1720. // The parameter parser must not treat that '=' as the key/value separator.
  1721. string content_type =
  1722. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1723. "charset=UTF-8";
  1724. string parsed;
  1725. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1726. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1727. }
  1728. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1729. // A ';' inside the quoted-string is part of the value, not a parameter
  1730. // separator, so it must not truncate the boundary.
  1731. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1732. string parsed;
  1733. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1734. EXPECT_EQ(parsed, "a;b");
  1735. }
  1736. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1737. string parsed;
  1738. EXPECT_TRUE(detail::parse_multipart_boundary(
  1739. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1740. EXPECT_EQ("a\\b", parsed);
  1741. EXPECT_TRUE(detail::parse_multipart_boundary(
  1742. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1743. EXPECT_EQ("a\"b", parsed);
  1744. }
  1745. TEST(ParseDispositionParamsTest, QuotedValues) {
  1746. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1747. // ';' and '=' are ordinary characters inside one.
  1748. struct {
  1749. const char *value;
  1750. std::vector<std::pair<const char *, const char *>> expected;
  1751. } cases[] = {
  1752. {"name=\"file1\"; filename=\"a.txt\"",
  1753. {{"name", "file1"}, {"filename", "a.txt"}}},
  1754. // Whitespace around '=' and ';' is still trimmed
  1755. {"name=\"file2\" ;filename = \"a.html\"",
  1756. {{"name", "file2"}, {"filename", "a.html"}}},
  1757. // '=' inside the value used to leave only the text after the last one
  1758. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1759. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1760. {"name=\"x=y\"", {{"name", "x=y"}}},
  1761. // ';' inside the value used to truncate the pair and leave a bogus one
  1762. {"name=\"file3\"; filename=\"a;b.txt\"",
  1763. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1764. // An unquoted value keeps working, and so does filename*
  1765. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1766. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1767. // A parameter with no key is dropped rather than turned into one whose
  1768. // key is the value
  1769. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1770. // An escaped quote does not end the value
  1771. {"name=\"a\\\"; filename=evil.php\"",
  1772. {{"name", "a\"; filename=evil.php"}}},
  1773. // Other backslashes, as in a Windows path, are kept
  1774. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1775. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1776. };
  1777. for (const auto &c : cases) {
  1778. Params params;
  1779. detail::parse_disposition_params(c.value, params);
  1780. for (const auto &kv : c.expected) {
  1781. auto it = params.find(kv.first);
  1782. ASSERT_NE(it, params.end())
  1783. << "value: " << c.value << ", key: " << kv.first;
  1784. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1785. }
  1786. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1787. }
  1788. }
  1789. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1790. Server svr;
  1791. std::string filename;
  1792. std::string content;
  1793. svr.Post("/upload", [&](const Request &req, Response &) {
  1794. const auto &file = req.form.get_file("file");
  1795. filename = file.filename;
  1796. content = file.content;
  1797. });
  1798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1799. auto se = detail::scope_exit([&] {
  1800. svr.stop();
  1801. thread.join();
  1802. ASSERT_FALSE(svr.is_running());
  1803. });
  1804. svr.wait_until_ready();
  1805. std::string body = "--B\r\n"
  1806. "Content-Disposition: form-data; name=\"file\"; "
  1807. "filename=\"a.txt\"\r\n"
  1808. "Content-Type: text/plain\r\n"
  1809. "\r\n"
  1810. "hello\r\n"
  1811. "--B--\r\n";
  1812. Client cli(HOST, PORT);
  1813. auto res = cli.Post(
  1814. "/upload",
  1815. [&](size_t offset, DataSink &sink) {
  1816. if (offset < body.size()) {
  1817. sink.write(&body[offset], 1);
  1818. } else {
  1819. sink.done();
  1820. }
  1821. return true;
  1822. },
  1823. "multipart/form-data; boundary=B");
  1824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1825. EXPECT_EQ(StatusCode::OK_200, res->status);
  1826. EXPECT_EQ("a.txt", filename);
  1827. EXPECT_EQ("hello", content);
  1828. }
  1829. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1830. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1831. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1832. Server svr;
  1833. std::string field_value, file_name, file_filename;
  1834. bool has_field = false, has_file = false;
  1835. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1836. has_field = req.form.has_field("x=y");
  1837. field_value = req.form.get_field("x=y");
  1838. has_file = req.form.has_file("file1");
  1839. const auto &file = req.form.get_file("file1");
  1840. file_name = file.name;
  1841. file_filename = file.filename;
  1842. res.set_content("ok", "text/plain");
  1843. });
  1844. auto port = svr.bind_to_any_port(HOST);
  1845. thread t = thread([&] { svr.listen_after_bind(); });
  1846. auto se = detail::scope_exit([&] {
  1847. svr.stop();
  1848. t.join();
  1849. ASSERT_FALSE(svr.is_running());
  1850. });
  1851. svr.wait_until_ready();
  1852. UploadFormDataItems items = {
  1853. {"x=y", "field-value", "", ""},
  1854. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1855. };
  1856. Client cli(HOST, port);
  1857. auto res = cli.Post("/quoted", items);
  1858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1859. ASSERT_EQ(StatusCode::OK_200, res->status);
  1860. EXPECT_TRUE(has_field);
  1861. EXPECT_EQ("field-value", field_value);
  1862. EXPECT_TRUE(has_file);
  1863. EXPECT_EQ("file1", file_name);
  1864. EXPECT_EQ("a;b=report.pdf", file_filename);
  1865. }
  1866. TEST(GetHeaderValueTest, DefaultValue) {
  1867. Headers headers = {{"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/plain", val);
  1870. }
  1871. TEST(GetHeaderValueTest, DefaultValueInt) {
  1872. Headers headers = {{"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1874. EXPECT_EQ(100ull, val);
  1875. }
  1876. TEST(GetHeaderValueTest, RegularValue) {
  1877. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1878. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1879. EXPECT_STREQ("text/html", val);
  1880. }
  1881. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1882. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1883. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1884. EXPECT_STREQ("text/html", val);
  1885. }
  1886. TEST(GetHeaderValueTest, SetContent) {
  1887. Response res;
  1888. res.set_content("html", "text/html");
  1889. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1890. res.set_content("text", "text/plain");
  1891. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1892. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1893. }
  1894. TEST(GetHeaderValueTest, RegularValueInt) {
  1895. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1896. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1897. EXPECT_EQ(100ull, val);
  1898. }
  1899. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1900. Headers headers = {{"Content-Length", "x"}};
  1901. auto is_invalid_value = false;
  1902. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1903. is_invalid_value);
  1904. EXPECT_EQ(0ull, val);
  1905. EXPECT_TRUE(is_invalid_value);
  1906. }
  1907. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1908. // An all-digit value that overflows size_t must be reported as invalid, not
  1909. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1910. // a large length to a small one on 32-bit builds, leaving the framing length
  1911. // wrong while is_invalid_value stayed false.
  1912. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1913. auto is_invalid_value = false;
  1914. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1915. is_invalid_value);
  1916. EXPECT_TRUE(is_invalid_value);
  1917. // A well-formed length is unaffected.
  1918. Headers ok = {{"Content-Length", "1234"}};
  1919. is_invalid_value = false;
  1920. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1921. is_invalid_value);
  1922. EXPECT_EQ(1234ull, val);
  1923. EXPECT_FALSE(is_invalid_value);
  1924. }
  1925. TEST(GetHeaderValueTest, Range) {
  1926. {
  1927. Headers headers = {make_range_header({{1, -1}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{-1, 1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=-1", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=1-10, 100-", val);
  1945. }
  1946. {
  1947. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1948. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1949. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1950. }
  1951. {
  1952. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1953. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1954. EXPECT_STREQ("bytes=0-0, -1", val);
  1955. }
  1956. }
  1957. TEST(BearerTokenAuthTest, SchemeValidation) {
  1958. // A value shorter than "Bearer " must not throw from the fixed-length
  1959. // substr, and a non-Bearer scheme must not be reported as a token.
  1960. struct {
  1961. const char *value;
  1962. const char *expected;
  1963. } cases[] = {
  1964. {"x", ""},
  1965. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1966. {"Bearer abc123", "abc123"},
  1967. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1968. };
  1969. for (const auto &c : cases) {
  1970. Request req;
  1971. req.set_header("Authorization", c.value);
  1972. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1973. }
  1974. }
  1975. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1976. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1977. // to depend on the standard library (libstdc++ handed back duplicates in
  1978. // reverse insertion order, libc++ in insertion order).
  1979. Request req;
  1980. req.set_header("Accept-Encoding", "gzip");
  1981. req.set_header("Accept-Encoding", "deflate");
  1982. req.set_header("Accept-Encoding", "br");
  1983. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1984. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1985. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1986. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1987. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1988. }
  1989. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1990. Request req;
  1991. req.set_header("X-Test", "only");
  1992. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1993. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1994. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1995. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1996. }
  1997. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1998. Request req;
  1999. req.set_header("X-First", "1");
  2000. req.set_header("X-Test", "2");
  2001. req.params.emplace("first", "1");
  2002. req.params.emplace("test", "2");
  2003. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2004. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2005. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2006. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2007. // The second one is negative when read as a signed value
  2008. const auto max_id = (std::numeric_limits<size_t>::max)();
  2009. for (auto id : {max_id / 2, max_id}) {
  2010. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2011. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2012. EXPECT_EQ("", req.get_param_value("test", id));
  2013. EXPECT_EQ("", req.form.get_field("test", id));
  2014. EXPECT_EQ("", req.form.get_file("test", id).content);
  2015. }
  2016. }
  2017. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2018. Headers headers;
  2019. headers.emplace("Host", "example.com");
  2020. headers.emplace("Accept-Encoding", "gzip");
  2021. headers.emplace("User-Agent", "test");
  2022. headers.emplace("Accept-Encoding", "deflate");
  2023. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2024. "Accept-Encoding=deflate ",
  2025. entries_to_string(headers));
  2026. }
  2027. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2028. Headers headers = {{"Content-Type", "text/html"},
  2029. {"CONTENT-TYPE", "text/xml"}};
  2030. EXPECT_EQ(2U, headers.count("content-type"));
  2031. auto it = headers.find("content-type");
  2032. ASSERT_TRUE(it != headers.end());
  2033. EXPECT_EQ("text/html", it->second);
  2034. }
  2035. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2036. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2037. // drop only those fields and leave everything positioned between them.
  2038. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2039. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2040. auto rng = headers.equal_range("a");
  2041. headers.erase(rng.first, rng.second);
  2042. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2043. }
  2044. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2045. Headers headers = {
  2046. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2047. EXPECT_EQ(3U, headers.erase("A"));
  2048. EXPECT_EQ(0U, headers.count("A"));
  2049. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2050. }
  2051. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2052. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2053. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2054. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2055. }
  2056. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2057. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2058. headers.emplace_front("Host", "example.com");
  2059. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2060. entries_to_string(headers));
  2061. }
  2062. TEST(ParseHeaderValueTest, Range) {
  2063. {
  2064. Ranges ranges;
  2065. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2066. EXPECT_TRUE(ret);
  2067. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2068. }
  2069. {
  2070. Ranges ranges;
  2071. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2072. EXPECT_TRUE(ret);
  2073. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2074. }
  2075. {
  2076. Ranges ranges;
  2077. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2078. EXPECT_TRUE(ret);
  2079. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2080. }
  2081. {
  2082. Ranges ranges;
  2083. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2084. EXPECT_FALSE(ret);
  2085. }
  2086. {
  2087. Ranges ranges;
  2088. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2089. EXPECT_TRUE(ret);
  2090. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2091. }
  2092. {
  2093. Ranges ranges;
  2094. auto ret =
  2095. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2096. EXPECT_TRUE(ret);
  2097. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2098. }
  2099. {
  2100. Ranges ranges;
  2101. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2102. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2103. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2104. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2105. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2106. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2107. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2108. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2109. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2110. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2111. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2112. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2113. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2114. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2115. EXPECT_FALSE(
  2116. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2117. EXPECT_TRUE(ranges.empty());
  2118. }
  2119. {
  2120. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2121. // remainder of the representation, so it stays accepted.
  2122. Ranges ranges;
  2123. auto ret =
  2124. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2125. EXPECT_TRUE(ret);
  2126. ASSERT_EQ(1u, ranges.size());
  2127. EXPECT_EQ(0, ranges[0].first);
  2128. EXPECT_EQ(-1, ranges[0].second);
  2129. }
  2130. // RFC 9110 14.1: range unit names are case-insensitive.
  2131. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2132. Ranges ranges;
  2133. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2134. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2135. }
  2136. }
  2137. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2138. Request req;
  2139. req.set_header("Accept-Encoding", "gzip");
  2140. Response res;
  2141. res.set_header("Content-Type", "text/plain");
  2142. auto ret = detail::encoding_type(req, res);
  2143. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2144. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2145. #else
  2146. EXPECT_TRUE(ret == detail::EncodingType::None);
  2147. #endif
  2148. }
  2149. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2150. Request req;
  2151. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2152. Response res;
  2153. res.set_header("Content-Type", "text/plain");
  2154. auto ret = detail::encoding_type(req, res);
  2155. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2156. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2157. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2158. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2159. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2160. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2161. #else
  2162. EXPECT_TRUE(ret == detail::EncodingType::None);
  2163. #endif
  2164. }
  2165. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2166. Request req;
  2167. req.set_header("Accept-Encoding",
  2168. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2169. Response res;
  2170. res.set_header("Content-Type", "text/plain");
  2171. auto ret = detail::encoding_type(req, res);
  2172. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2173. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2174. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2175. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2176. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2177. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2178. #else
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. #endif
  2181. }
  2182. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2183. // All supported encodings rejected with q=0 should return None
  2184. Request req;
  2185. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2186. Response res;
  2187. res.set_header("Content-Type", "text/plain");
  2188. auto ret = detail::encoding_type(req, res);
  2189. EXPECT_TRUE(ret == detail::EncodingType::None);
  2190. }
  2191. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2192. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2193. Request req;
  2194. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2195. Response res;
  2196. res.set_header("Content-Type", "text/plain");
  2197. auto ret = detail::encoding_type(req, res);
  2198. EXPECT_TRUE(ret == detail::EncodingType::None);
  2199. }
  2200. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2201. Request req;
  2202. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2203. Response res;
  2204. res.set_header("Content-Type", "text/plain");
  2205. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2206. }
  2207. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2208. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2209. Request req;
  2210. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2211. Response res;
  2212. res.set_header("Content-Type", "text/plain");
  2213. auto ret = detail::encoding_type(req, res);
  2214. EXPECT_TRUE(ret == detail::EncodingType::None);
  2215. }
  2216. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2217. // RFC 7231: Accept-Encoding values are case-insensitive
  2218. Request req;
  2219. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2220. Response res;
  2221. res.set_header("Content-Type", "text/plain");
  2222. auto ret = detail::encoding_type(req, res);
  2223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2224. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2225. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2226. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2227. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2228. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2229. #else
  2230. EXPECT_TRUE(ret == detail::EncodingType::None);
  2231. #endif
  2232. }
  2233. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2234. // q value should determine priority, not hardcoded order
  2235. Request req;
  2236. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2237. Response res;
  2238. res.set_header("Content-Type", "text/plain");
  2239. auto ret = detail::encoding_type(req, res);
  2240. // gzip has highest q=1.0, so it should be selected even though
  2241. // br and zstd are also supported
  2242. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2243. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2244. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2245. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2246. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2247. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2248. #else
  2249. EXPECT_TRUE(ret == detail::EncodingType::None);
  2250. #endif
  2251. }
  2252. TEST(BufferStreamTest, read) {
  2253. detail::BufferStream strm1;
  2254. Stream &strm = strm1;
  2255. EXPECT_EQ(5, strm.write("hello"));
  2256. char buf[512];
  2257. EXPECT_EQ(2, strm.read(buf, 2));
  2258. EXPECT_EQ('h', buf[0]);
  2259. EXPECT_EQ('e', buf[1]);
  2260. EXPECT_EQ(2, strm.read(buf, 2));
  2261. EXPECT_EQ('l', buf[0]);
  2262. EXPECT_EQ('l', buf[1]);
  2263. EXPECT_EQ(1, strm.read(buf, 1));
  2264. EXPECT_EQ('o', buf[0]);
  2265. EXPECT_EQ(0, strm.read(buf, 1));
  2266. }
  2267. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2268. auto host = "www.httpwatch.com";
  2269. auto ip = hosted_at(host);
  2270. EXPECT_EQ("23.96.13.243", ip);
  2271. std::vector<std::string> addrs;
  2272. hosted_at(host, addrs);
  2273. EXPECT_EQ(1u, addrs.size());
  2274. }
  2275. #if 0 // It depends on each test environment...
  2276. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2277. auto host = "www.youtube.com";
  2278. std::vector<std::string> addrs;
  2279. hosted_at(host, addrs);
  2280. EXPECT_EQ(20u, addrs.size());
  2281. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2282. EXPECT_TRUE(it != addrs.end());
  2283. }
  2284. #endif
  2285. class ChunkedEncodingTest : public ::testing::Test {
  2286. protected:
  2287. ChunkedEncodingTest()
  2288. : cli_(HOST, PORT)
  2289. #ifdef CPPHTTPLIB_SSL_ENABLED
  2290. ,
  2291. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2292. #endif
  2293. {
  2294. cli_.set_connection_timeout(2);
  2295. #ifdef CPPHTTPLIB_SSL_ENABLED
  2296. cli_.enable_server_certificate_verification(false);
  2297. #endif
  2298. }
  2299. virtual void SetUp() {
  2300. read_file("./image.jpg", image_data_);
  2301. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2302. res.set_content("Hello World!", "text/plain");
  2303. });
  2304. svr_.Get(
  2305. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2306. res.set_chunked_content_provider(
  2307. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2308. size_t remaining = image_data_.size() - offset;
  2309. if (remaining == 0) {
  2310. sink.done();
  2311. } else {
  2312. constexpr size_t CHUNK_SIZE = 1024;
  2313. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2314. sink.write(&image_data_[offset], send_size);
  2315. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2316. }
  2317. return true;
  2318. });
  2319. });
  2320. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2321. svr_.wait_until_ready();
  2322. }
  2323. virtual void TearDown() {
  2324. svr_.stop();
  2325. if (!request_threads_.empty()) {
  2326. std::this_thread::sleep_for(std::chrono::seconds(1));
  2327. for (auto &t : request_threads_) {
  2328. t.join();
  2329. }
  2330. }
  2331. t_.join();
  2332. }
  2333. #ifdef CPPHTTPLIB_SSL_ENABLED
  2334. SSLClient cli_;
  2335. SSLServer svr_;
  2336. #else
  2337. Client cli_;
  2338. Server svr_;
  2339. #endif
  2340. thread t_;
  2341. std::vector<thread> request_threads_;
  2342. std::string image_data_;
  2343. };
  2344. TEST_F(ChunkedEncodingTest, NormalGet) {
  2345. auto res = cli_.Get("/chunked");
  2346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2347. std::string out;
  2348. read_file("./image.jpg", out);
  2349. EXPECT_EQ(StatusCode::OK_200, res->status);
  2350. EXPECT_EQ(out, res->body);
  2351. }
  2352. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2353. std::string body;
  2354. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2355. body.append(data, data_length);
  2356. return true;
  2357. });
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. std::string out;
  2360. read_file("./image.jpg", out);
  2361. EXPECT_EQ(StatusCode::OK_200, res->status);
  2362. EXPECT_EQ(out, body);
  2363. }
  2364. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2365. std::string body;
  2366. auto res = cli_.Get(
  2367. "/chunked",
  2368. [&](const Response &response) {
  2369. EXPECT_EQ(StatusCode::OK_200, response.status);
  2370. return true;
  2371. },
  2372. [&](const char *data, size_t data_length) {
  2373. body.append(data, data_length);
  2374. return true;
  2375. });
  2376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2377. std::string out;
  2378. read_file("./image.jpg", out);
  2379. EXPECT_EQ(StatusCode::OK_200, res->status);
  2380. EXPECT_EQ(out, body);
  2381. }
  2382. TEST(RangeTest, FromHTTPBin_Online) {
  2383. auto host = "httpbingo.org";
  2384. auto path = std::string{"/range/32"};
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. auto port = 443;
  2387. SSLClient cli(host, port);
  2388. #else
  2389. auto port = 80;
  2390. Client cli(host, port);
  2391. #endif
  2392. cli.set_connection_timeout(5);
  2393. {
  2394. auto res = cli.Get(path);
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2397. EXPECT_EQ(StatusCode::OK_200, res->status);
  2398. }
  2399. {
  2400. Headers headers = {make_range_header({{1, -1}})};
  2401. auto res = cli.Get(path, headers);
  2402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2403. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2405. }
  2406. {
  2407. Headers headers = {make_range_header({{1, 10}})};
  2408. auto res = cli.Get(path, headers);
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. EXPECT_EQ("bcdefghijk", res->body);
  2411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2412. }
  2413. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2414. // entire resource, while the original httpbin returned 200. Both are
  2415. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2416. {
  2417. Headers headers = {make_range_header({{0, 31}})};
  2418. auto res = cli.Get(path, headers);
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2421. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2422. res->status == StatusCode::PartialContent_206);
  2423. }
  2424. {
  2425. Headers headers = {make_range_header({{0, -1}})};
  2426. auto res = cli.Get(path, headers);
  2427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2428. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2429. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2430. res->status == StatusCode::PartialContent_206);
  2431. }
  2432. // go-httpbin returns 206 with clamped range for over-range requests,
  2433. // while the original httpbin returned 416. Both behaviors are observed
  2434. // in real servers, so we only verify the request succeeds.
  2435. {
  2436. Headers headers = {make_range_header({{0, 32}})};
  2437. auto res = cli.Get(path, headers);
  2438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2439. }
  2440. }
  2441. TEST(RangeTest, IgnoredForPost) {
  2442. Server svr;
  2443. svr.Post("/", [](const Request &, Response &res) {
  2444. res.set_content("abcdefg", "text/plain");
  2445. });
  2446. auto port = svr.bind_to_any_port(HOST);
  2447. ASSERT_GT(port, 0);
  2448. thread t = thread([&] { svr.listen_after_bind(); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. t.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. Client cli(HOST, port);
  2456. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2457. auto res = cli.Post("/", Headers{{"Range", range}});
  2458. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2459. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2460. EXPECT_EQ("abcdefg", res->body) << range;
  2461. }
  2462. }
  2463. TEST(RangeTest, IgnoredForUnknownUnit) {
  2464. Server svr;
  2465. svr.Get("/", [](const Request &, Response &res) {
  2466. res.set_content("abcdefg", "text/plain");
  2467. });
  2468. auto port = svr.bind_to_any_port(HOST);
  2469. ASSERT_GT(port, 0);
  2470. thread t = thread([&] { svr.listen_after_bind(); });
  2471. auto se = detail::scope_exit([&] {
  2472. svr.stop();
  2473. t.join();
  2474. ASSERT_FALSE(svr.is_running());
  2475. });
  2476. svr.wait_until_ready();
  2477. Client cli(HOST, port);
  2478. for (auto range : {"items=1-2", "none=x"}) {
  2479. auto res = cli.Get("/", Headers{{"Range", range}});
  2480. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2481. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2482. EXPECT_EQ("abcdefg", res->body) << range;
  2483. }
  2484. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2485. ASSERT_TRUE(res) << to_string(res.error());
  2486. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2487. }
  2488. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2489. auto host = "unresolvableaddress.local";
  2490. auto path = std::string{"/"};
  2491. #ifdef CPPHTTPLIB_SSL_ENABLED
  2492. auto port = 443;
  2493. SSLClient cli(host, port);
  2494. #else
  2495. auto port = 80;
  2496. Client cli(host, port);
  2497. #endif
  2498. cli.set_connection_timeout(1);
  2499. {
  2500. auto res = cli.Get(path);
  2501. ASSERT_FALSE(res);
  2502. }
  2503. std::this_thread::sleep_for(std::chrono::seconds(8));
  2504. }
  2505. #if defined(__linux__) && defined(__GLIBC__) && \
  2506. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2507. // Forward declaration: in split builds split.py strips `inline` and moves the
  2508. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2509. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2510. // against the symbol in both header-only and split builds.
  2511. namespace httplib {
  2512. namespace detail {
  2513. int getaddrinfo_with_timeout(const char *node, const char *service,
  2514. const struct addrinfo *hints,
  2515. struct addrinfo **res, time_t timeout_sec);
  2516. } // namespace detail
  2517. } // namespace httplib
  2518. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2519. //
  2520. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2521. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2522. // gai_suspend() call hits the connection timeout the function calls
  2523. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2524. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2525. // still alive and still references the now-destroyed stack frame.
  2526. //
  2527. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2528. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2529. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2530. // and runs them in a container.
  2531. namespace {
  2532. bool should_run_issue_2431_tests() {
  2533. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2534. return v && *v && std::string(v) != "0";
  2535. }
  2536. std::string unique_unresolvable_host(int n) {
  2537. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2538. // glibc still asks the configured nameserver — which is exactly the path
  2539. // we want to exercise. A unique label per call avoids the resolver cache.
  2540. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2541. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2542. std::to_string(n) + ".invalid";
  2543. }
  2544. } // namespace
  2545. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2546. if (!should_run_issue_2431_tests()) {
  2547. GTEST_SKIP()
  2548. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2549. }
  2550. for (int i = 0; i < 8; ++i) {
  2551. struct addrinfo hints;
  2552. memset(&hints, 0, sizeof(hints));
  2553. hints.ai_family = AF_UNSPEC;
  2554. hints.ai_socktype = SOCK_STREAM;
  2555. auto host = unique_unresolvable_host(i);
  2556. struct addrinfo *result = nullptr;
  2557. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2558. &result, /*timeout_sec=*/1);
  2559. if (rc == 0 && result) { freeaddrinfo(result); }
  2560. }
  2561. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2562. // stack region they still believe holds their gaicb.
  2563. std::this_thread::sleep_for(std::chrono::seconds(3));
  2564. }
  2565. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2566. if (!should_run_issue_2431_tests()) {
  2567. GTEST_SKIP()
  2568. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2569. }
  2570. std::atomic<bool> stop{false};
  2571. std::vector<std::thread> threads;
  2572. for (int t = 0; t < 8; ++t) {
  2573. threads.emplace_back([t, &stop] {
  2574. int i = 0;
  2575. while (!stop.load(std::memory_order_relaxed)) {
  2576. struct addrinfo hints;
  2577. memset(&hints, 0, sizeof(hints));
  2578. hints.ai_family = AF_UNSPEC;
  2579. hints.ai_socktype = SOCK_STREAM;
  2580. auto host = unique_unresolvable_host(t * 100000 + i++);
  2581. struct addrinfo *result = nullptr;
  2582. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2583. &result, /*timeout_sec=*/1);
  2584. if (rc == 0 && result) { freeaddrinfo(result); }
  2585. }
  2586. });
  2587. }
  2588. std::this_thread::sleep_for(std::chrono::seconds(8));
  2589. stop.store(true, std::memory_order_relaxed);
  2590. for (auto &th : threads) {
  2591. th.join();
  2592. }
  2593. std::this_thread::sleep_for(std::chrono::seconds(3));
  2594. }
  2595. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2596. if (!should_run_issue_2431_tests()) {
  2597. GTEST_SKIP()
  2598. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2599. }
  2600. std::atomic<bool> stop{false};
  2601. std::vector<std::thread> threads;
  2602. for (int t = 0; t < 8; ++t) {
  2603. threads.emplace_back([t, &stop] {
  2604. int i = 0;
  2605. while (!stop.load(std::memory_order_relaxed)) {
  2606. auto host = unique_unresolvable_host(t * 100000 + i++);
  2607. Client cli(host, 80);
  2608. cli.set_connection_timeout(1, 0);
  2609. cli.set_read_timeout(1, 0);
  2610. cli.set_write_timeout(1, 0);
  2611. (void)cli.Get("/");
  2612. }
  2613. });
  2614. }
  2615. std::this_thread::sleep_for(std::chrono::seconds(8));
  2616. stop.store(true, std::memory_order_relaxed);
  2617. for (auto &th : threads) {
  2618. th.join();
  2619. }
  2620. std::this_thread::sleep_for(std::chrono::seconds(3));
  2621. }
  2622. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2623. TEST(ConnectionErrorTest, InvalidHost) {
  2624. auto host = "-abcde.com";
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. auto port = 443;
  2627. SSLClient cli(host, port);
  2628. #else
  2629. auto port = 80;
  2630. Client cli(host, port);
  2631. #endif
  2632. cli.set_connection_timeout(std::chrono::seconds(2));
  2633. auto res = cli.Get("/");
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Connection, res.error());
  2636. }
  2637. TEST(ConnectionErrorTest, InvalidHost2) {
  2638. auto host = "httpcan.org/";
  2639. #ifdef CPPHTTPLIB_SSL_ENABLED
  2640. SSLClient cli(host);
  2641. #else
  2642. Client cli(host);
  2643. #endif
  2644. cli.set_connection_timeout(std::chrono::seconds(2));
  2645. auto res = cli.Get("/");
  2646. ASSERT_TRUE(!res);
  2647. EXPECT_EQ(Error::Connection, res.error());
  2648. }
  2649. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2650. auto host = "httpcan.org/";
  2651. #ifdef CPPHTTPLIB_SSL_ENABLED
  2652. SSLClient cli(host);
  2653. #else
  2654. Client cli(host);
  2655. #endif
  2656. cli.set_connection_timeout(std::chrono::seconds(2));
  2657. auto res = cli.Get("/");
  2658. ASSERT_TRUE(!res);
  2659. stringstream s;
  2660. s << "error code: " << res.error();
  2661. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2662. }
  2663. TEST(ConnectionErrorTest, InvalidPort) {
  2664. auto host = "localhost";
  2665. auto port = 44380;
  2666. #ifdef CPPHTTPLIB_SSL_ENABLED
  2667. SSLClient cli(host, port);
  2668. #else
  2669. Client cli(host, port);
  2670. #endif
  2671. cli.set_connection_timeout(std::chrono::seconds(2));
  2672. auto res = cli.Get("/");
  2673. ASSERT_TRUE(!res);
  2674. EXPECT_TRUE(Error::Connection == res.error() ||
  2675. Error::ConnectionTimeout == res.error());
  2676. }
  2677. TEST(ConnectionErrorTest, Timeout_Online) {
  2678. auto host = "google.com";
  2679. #ifdef CPPHTTPLIB_SSL_ENABLED
  2680. auto port = 44380;
  2681. SSLClient cli(host, port);
  2682. #else
  2683. auto port = 8080;
  2684. Client cli(host, port);
  2685. #endif
  2686. cli.set_connection_timeout(std::chrono::seconds(2));
  2687. // only probe one address type so that the error reason
  2688. // correlates to the timed-out IPv4, not the unsupported
  2689. // IPv6 connection attempt
  2690. cli.set_address_family(AF_INET);
  2691. auto res = cli.Get("/");
  2692. ASSERT_TRUE(!res);
  2693. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2694. }
  2695. TEST(CancelTest, NoCancel_Online) {
  2696. auto host = "httpbingo.org";
  2697. auto path = std::string{"/range/32"};
  2698. #ifdef CPPHTTPLIB_SSL_ENABLED
  2699. auto port = 443;
  2700. SSLClient cli(host, port);
  2701. #else
  2702. auto port = 80;
  2703. Client cli(host, port);
  2704. #endif
  2705. cli.set_connection_timeout(std::chrono::seconds(5));
  2706. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2708. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2709. EXPECT_EQ(StatusCode::OK_200, res->status);
  2710. }
  2711. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2712. // Use /bytes with a large payload so that the DownloadProgress callback
  2713. // (which only fires for Content-Length responses) is invoked before the
  2714. // entire body is received, giving cancellation a chance to fire.
  2715. auto host = "httpbingo.org";
  2716. auto path = std::string{"/bytes/524288"};
  2717. #ifdef CPPHTTPLIB_SSL_ENABLED
  2718. auto port = 443;
  2719. SSLClient cli(host, port);
  2720. #else
  2721. auto port = 80;
  2722. Client cli(host, port);
  2723. #endif
  2724. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2725. cli.set_connection_timeout(std::chrono::seconds(5));
  2726. ASSERT_TRUE(!res);
  2727. EXPECT_EQ(Error::Canceled, res.error());
  2728. }
  2729. TEST(CancelTest, WithCancelLargePayload_Online) {
  2730. auto host = "httpbingo.org";
  2731. auto path = std::string{"/bytes/524288"};
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. auto port = 443;
  2734. SSLClient cli(host, port);
  2735. #else
  2736. auto port = 80;
  2737. Client cli(host, port);
  2738. #endif
  2739. cli.set_connection_timeout(std::chrono::seconds(5));
  2740. uint32_t count = 0;
  2741. auto res =
  2742. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2743. ASSERT_TRUE(!res);
  2744. EXPECT_EQ(Error::Canceled, res.error());
  2745. }
  2746. TEST(CancelTest, NoCancelPost) {
  2747. Server svr;
  2748. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2749. res.set_content("Hello World!", "text/plain");
  2750. });
  2751. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2752. auto se = detail::scope_exit([&] {
  2753. svr.stop();
  2754. thread.join();
  2755. ASSERT_FALSE(svr.is_running());
  2756. });
  2757. svr.wait_until_ready();
  2758. Client cli(HOST, PORT);
  2759. cli.set_connection_timeout(std::chrono::seconds(5));
  2760. auto res =
  2761. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2762. "application/json", [](uint64_t, uint64_t) { return true; });
  2763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2764. EXPECT_EQ("Hello World!", res->body);
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. }
  2767. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2768. Server svr;
  2769. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2770. res.set_content("Hello World!", "text/plain");
  2771. });
  2772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2773. auto se = detail::scope_exit([&] {
  2774. svr.stop();
  2775. thread.join();
  2776. ASSERT_FALSE(svr.is_running());
  2777. });
  2778. svr.wait_until_ready();
  2779. Client cli(HOST, PORT);
  2780. cli.set_connection_timeout(std::chrono::seconds(5));
  2781. auto res =
  2782. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2783. "application/json", [](uint64_t, uint64_t) { return false; });
  2784. ASSERT_TRUE(!res);
  2785. EXPECT_EQ(Error::Canceled, res.error());
  2786. }
  2787. TEST(CancelTest, WithCancelLargePayloadPost) {
  2788. Server svr;
  2789. svr.set_payload_max_length(200 * 1024 * 1024);
  2790. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2791. res.set_content(LARGE_DATA, "text/plain");
  2792. });
  2793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. thread.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. Client cli(HOST, PORT);
  2801. cli.set_payload_max_length(200 * 1024 * 1024);
  2802. cli.set_connection_timeout(std::chrono::seconds(5));
  2803. auto res =
  2804. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2805. "application/json", [](uint64_t, uint64_t) { return false; });
  2806. ASSERT_TRUE(!res);
  2807. EXPECT_EQ(Error::Canceled, res.error());
  2808. }
  2809. TEST(CancelTest, NoCancelPut) {
  2810. Server svr;
  2811. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2812. res.set_content("Hello World!", "text/plain");
  2813. });
  2814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2815. auto se = detail::scope_exit([&] {
  2816. svr.stop();
  2817. thread.join();
  2818. ASSERT_FALSE(svr.is_running());
  2819. });
  2820. svr.wait_until_ready();
  2821. Client cli(HOST, PORT);
  2822. cli.set_connection_timeout(std::chrono::seconds(5));
  2823. auto res =
  2824. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2825. "application/json", [](uint64_t, uint64_t) { return true; });
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ("Hello World!", res->body);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2831. Server svr;
  2832. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2833. res.set_content("Hello World!", "text/plain");
  2834. });
  2835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2836. auto se = detail::scope_exit([&] {
  2837. svr.stop();
  2838. thread.join();
  2839. ASSERT_FALSE(svr.is_running());
  2840. });
  2841. svr.wait_until_ready();
  2842. Client cli(HOST, PORT);
  2843. cli.set_connection_timeout(std::chrono::seconds(5));
  2844. auto res =
  2845. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2846. "application/json", [](uint64_t, uint64_t) { return false; });
  2847. ASSERT_TRUE(!res);
  2848. EXPECT_EQ(Error::Canceled, res.error());
  2849. }
  2850. TEST(CancelTest, WithCancelLargePayloadPut) {
  2851. Server svr;
  2852. svr.set_payload_max_length(200 * 1024 * 1024);
  2853. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2854. res.set_content(LARGE_DATA, "text/plain");
  2855. });
  2856. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2857. auto se = detail::scope_exit([&] {
  2858. svr.stop();
  2859. thread.join();
  2860. ASSERT_FALSE(svr.is_running());
  2861. });
  2862. svr.wait_until_ready();
  2863. Client cli(HOST, PORT);
  2864. cli.set_payload_max_length(200 * 1024 * 1024);
  2865. cli.set_connection_timeout(std::chrono::seconds(5));
  2866. auto res =
  2867. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2868. "application/json", [](uint64_t, uint64_t) { return false; });
  2869. ASSERT_TRUE(!res);
  2870. EXPECT_EQ(Error::Canceled, res.error());
  2871. }
  2872. TEST(CancelTest, NoCancelPatch) {
  2873. Server svr;
  2874. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2875. res.set_content("Hello World!", "text/plain");
  2876. });
  2877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2878. auto se = detail::scope_exit([&] {
  2879. svr.stop();
  2880. thread.join();
  2881. ASSERT_FALSE(svr.is_running());
  2882. });
  2883. svr.wait_until_ready();
  2884. Client cli(HOST, PORT);
  2885. cli.set_connection_timeout(std::chrono::seconds(5));
  2886. auto res =
  2887. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2888. "application/json", [](uint64_t, uint64_t) { return true; });
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ("Hello World!", res->body);
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. }
  2893. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2894. Server svr;
  2895. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2896. res.set_content("Hello World!", "text/plain");
  2897. });
  2898. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2899. auto se = detail::scope_exit([&] {
  2900. svr.stop();
  2901. thread.join();
  2902. ASSERT_FALSE(svr.is_running());
  2903. });
  2904. svr.wait_until_ready();
  2905. Client cli(HOST, PORT);
  2906. cli.set_connection_timeout(std::chrono::seconds(5));
  2907. auto res =
  2908. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2909. "application/json", [](uint64_t, uint64_t) { return false; });
  2910. ASSERT_TRUE(!res);
  2911. EXPECT_EQ(Error::Canceled, res.error());
  2912. }
  2913. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2914. Server svr;
  2915. svr.set_payload_max_length(200 * 1024 * 1024);
  2916. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2917. res.set_content(LARGE_DATA, "text/plain");
  2918. });
  2919. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2920. auto se = detail::scope_exit([&] {
  2921. svr.stop();
  2922. thread.join();
  2923. ASSERT_FALSE(svr.is_running());
  2924. });
  2925. svr.wait_until_ready();
  2926. Client cli(HOST, PORT);
  2927. cli.set_payload_max_length(200 * 1024 * 1024);
  2928. cli.set_connection_timeout(std::chrono::seconds(5));
  2929. auto res =
  2930. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2931. "application/json", [](uint64_t, uint64_t) { return false; });
  2932. ASSERT_TRUE(!res);
  2933. EXPECT_EQ(Error::Canceled, res.error());
  2934. }
  2935. TEST(CancelTest, NoCancelDelete) {
  2936. Server svr;
  2937. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2938. res.set_content("Hello World!", "text/plain");
  2939. });
  2940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2941. auto se = detail::scope_exit([&] {
  2942. svr.stop();
  2943. thread.join();
  2944. ASSERT_FALSE(svr.is_running());
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, PORT);
  2948. cli.set_connection_timeout(std::chrono::seconds(5));
  2949. auto res =
  2950. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2951. "application/json", [](uint64_t, uint64_t) { return true; });
  2952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2953. EXPECT_EQ("Hello World!", res->body);
  2954. EXPECT_EQ(StatusCode::OK_200, res->status);
  2955. }
  2956. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2957. Server svr;
  2958. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2959. res.set_content("Hello World!", "text/plain");
  2960. });
  2961. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2962. auto se = detail::scope_exit([&] {
  2963. svr.stop();
  2964. thread.join();
  2965. ASSERT_FALSE(svr.is_running());
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, PORT);
  2969. cli.set_connection_timeout(std::chrono::seconds(5));
  2970. auto res =
  2971. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2972. "application/json", [](uint64_t, uint64_t) { return false; });
  2973. ASSERT_TRUE(!res);
  2974. EXPECT_EQ(Error::Canceled, res.error());
  2975. }
  2976. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2977. Server svr;
  2978. svr.set_payload_max_length(200 * 1024 * 1024);
  2979. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2980. res.set_content(LARGE_DATA, "text/plain");
  2981. });
  2982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2983. auto se = detail::scope_exit([&] {
  2984. svr.stop();
  2985. thread.join();
  2986. ASSERT_FALSE(svr.is_running());
  2987. });
  2988. svr.wait_until_ready();
  2989. Client cli(HOST, PORT);
  2990. cli.set_payload_max_length(200 * 1024 * 1024);
  2991. cli.set_connection_timeout(std::chrono::seconds(5));
  2992. auto res =
  2993. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2994. "application/json", [](uint64_t, uint64_t) { return false; });
  2995. ASSERT_TRUE(!res);
  2996. EXPECT_EQ(Error::Canceled, res.error());
  2997. }
  2998. // One stop() from another thread ends a request that waits for the response
  2999. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3000. Server svr;
  3001. std::atomic<bool> received{false};
  3002. std::atomic<bool> done{false};
  3003. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3004. received.store(true);
  3005. while (!done.load()) {
  3006. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3007. }
  3008. res.set_content("Hello World!", "text/plain");
  3009. });
  3010. auto port = svr.bind_to_any_port(HOST);
  3011. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3012. Client cli(HOST, port);
  3013. cli.set_read_timeout(std::chrono::seconds(30));
  3014. std::future<Result> request;
  3015. auto se = detail::scope_exit([&] {
  3016. done.store(true);
  3017. svr.stop();
  3018. thread.join();
  3019. ASSERT_FALSE(svr.is_running());
  3020. });
  3021. svr.wait_until_ready();
  3022. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3023. for (int i = 0; i < 500 && !received.load(); ++i) {
  3024. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3025. }
  3026. ASSERT_TRUE(received.load());
  3027. // Let the client block in the wait for the response
  3028. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3029. auto start = std::chrono::steady_clock::now();
  3030. cli.stop();
  3031. ASSERT_EQ(std::future_status::ready,
  3032. request.wait_for(std::chrono::seconds(5)));
  3033. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3034. auto res = request.get();
  3035. ASSERT_TRUE(!res);
  3036. EXPECT_EQ(Error::Read, res.error());
  3037. }
  3038. // A listener whose backlog completes the TCP connections of clients, and that
  3039. // never answers them
  3040. struct SilentListener {
  3041. socket_t sock = INVALID_SOCKET;
  3042. sockaddr_in addr{};
  3043. int port = 0;
  3044. explicit SilentListener(int backlog = 1) {
  3045. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3046. addr.sin_family = AF_INET;
  3047. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3048. socklen_t len = sizeof(addr);
  3049. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3050. ::listen(sock, backlog) != 0 ||
  3051. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3052. detail::close_socket(sock);
  3053. sock = INVALID_SOCKET;
  3054. }
  3055. port = ntohs(addr.sin_port);
  3056. }
  3057. ~SilentListener() { detail::close_socket(sock); }
  3058. // The next connection, whose reads give up after 5 seconds
  3059. socket_t accept() const {
  3060. auto peer = ::accept(sock, nullptr, nullptr);
  3061. if (peer != INVALID_SOCKET) {
  3062. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3063. }
  3064. return peer;
  3065. }
  3066. };
  3067. static bool receives_a_byte(socket_t peer) {
  3068. char c = 0;
  3069. return detail::read_socket(peer, &c, 1, 0) == 1;
  3070. }
  3071. // Runs op, stops cli once the listener receives the first byte op sends, and
  3072. // expects op to end with error soon after
  3073. template <typename ClientType, typename Op>
  3074. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3075. Op op, Error error = Error::Canceled) {
  3076. auto ended = std::async(std::launch::async, op);
  3077. auto peer = listener.accept();
  3078. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3079. ASSERT_NE(INVALID_SOCKET, peer);
  3080. ASSERT_TRUE(receives_a_byte(peer));
  3081. cli.stop();
  3082. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3083. EXPECT_EQ(error, ended.get());
  3084. }
  3085. // Stops itself from another thread as the connection opens, the last moment a
  3086. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3087. // waits for the connection fails the test instead of hanging it.
  3088. class StoppedAsConnectedClient : public ClientImpl {
  3089. public:
  3090. using ClientImpl::ClientImpl;
  3091. protected:
  3092. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3093. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3094. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3095. stopper_.wait_for(std::chrono::seconds(1));
  3096. return true;
  3097. }
  3098. private:
  3099. std::future<void> stopper_;
  3100. };
  3101. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3102. SilentListener listener;
  3103. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3104. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3105. cli.set_read_timeout(std::chrono::seconds(3));
  3106. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3107. auto peer = listener.accept();
  3108. EXPECT_FALSE(receives_a_byte(peer));
  3109. detail::close_socket(peer);
  3110. auto handle = cli.open_stream("GET", "/");
  3111. EXPECT_FALSE(handle.is_valid());
  3112. EXPECT_EQ(Error::Canceled, handle.error);
  3113. peer = listener.accept();
  3114. EXPECT_FALSE(receives_a_byte(peer));
  3115. detail::close_socket(peer);
  3116. }
  3117. #ifdef __linux__
  3118. // A connect that a listener with a full backlog never completes
  3119. TEST(ClientStopTest, StopEndsAConnect) {
  3120. SilentListener listener(0);
  3121. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3122. std::vector<socket_t> backlog;
  3123. auto close_backlog = detail::scope_exit([&] {
  3124. for (auto sock : backlog) {
  3125. detail::close_socket(sock);
  3126. }
  3127. });
  3128. for (int i = 0; i < 8; i++) {
  3129. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3130. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3131. sizeof(listener.addr));
  3132. backlog.push_back(sock);
  3133. }
  3134. Client cli("127.0.0.1", listener.port);
  3135. cli.set_connection_timeout(std::chrono::seconds(3));
  3136. auto ended =
  3137. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3138. // A stop() before the request starts does not apply to it, so it repeats
  3139. auto status = std::future_status::timeout;
  3140. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3141. cli.stop();
  3142. status = ended.wait_for(std::chrono::milliseconds(10));
  3143. }
  3144. EXPECT_EQ(std::future_status::ready, status);
  3145. EXPECT_EQ(Error::Canceled, ended.get());
  3146. }
  3147. #endif
  3148. // The stream holds the socket while it waits for the head, out of the reach
  3149. // of shutdown()
  3150. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3151. SilentListener listener;
  3152. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3153. Client cli("127.0.0.1", listener.port);
  3154. cli.set_read_timeout(std::chrono::seconds(3));
  3155. expect_stop_ends(
  3156. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3157. Error::Read);
  3158. }
  3159. #ifdef CPPHTTPLIB_SSL_ENABLED
  3160. // A server that never answers the ClientHello
  3161. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3162. SilentListener listener;
  3163. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3164. SSLClient cli("127.0.0.1", listener.port);
  3165. cli.enable_server_certificate_verification(false);
  3166. cli.set_connection_timeout(std::chrono::seconds(3));
  3167. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3168. expect_stop_ends(cli, listener,
  3169. [&] { return cli.open_stream("GET", "/").error; });
  3170. }
  3171. // A proxy that takes the CONNECT and never answers it
  3172. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3173. SilentListener listener;
  3174. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3175. SSLClient cli("example.com", 443);
  3176. cli.set_proxy("127.0.0.1", listener.port);
  3177. cli.set_read_timeout(std::chrono::seconds(3));
  3178. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3179. }
  3180. #endif
  3181. // A read timeout past what the clock reaches waits for the response
  3182. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3183. SilentListener listener;
  3184. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3185. Client cli("127.0.0.1", listener.port);
  3186. cli.set_read_timeout(
  3187. static_cast<time_t>((std::min)(static_cast<long long>(
  3188. (std::numeric_limits<time_t>::max)()),
  3189. 10000000000LL)),
  3190. 0);
  3191. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3192. auto peer = listener.accept();
  3193. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3194. ASSERT_NE(INVALID_SOCKET, peer);
  3195. ASSERT_TRUE(receives_a_byte(peer));
  3196. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3197. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3198. "Connection: close\r\n\r\nok";
  3199. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3200. auto result = res.get();
  3201. ASSERT_TRUE(result);
  3202. EXPECT_EQ("ok", result->body);
  3203. }
  3204. static std::string remove_whitespace(const std::string &input) {
  3205. std::string output;
  3206. output.reserve(input.size());
  3207. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3208. [](unsigned char c) { return !std::isspace(c); });
  3209. return output;
  3210. }
  3211. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3212. auto host = "httpbingo.org";
  3213. auto path = std::string{"/basic-auth/hello/world"};
  3214. #ifdef CPPHTTPLIB_SSL_ENABLED
  3215. auto port = 443;
  3216. SSLClient cli(host, port);
  3217. #else
  3218. auto port = 80;
  3219. Client cli(host, port);
  3220. #endif
  3221. {
  3222. auto res = cli.Get(path);
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3225. }
  3226. {
  3227. auto res = cli.Get(
  3228. path, Headers{make_basic_authentication_header("hello", "world")});
  3229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3230. auto body = remove_whitespace(res->body);
  3231. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3232. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3233. EXPECT_EQ(StatusCode::OK_200, res->status);
  3234. }
  3235. {
  3236. cli.set_basic_auth("hello", "world");
  3237. auto res = cli.Get(path);
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. auto body = remove_whitespace(res->body);
  3240. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3241. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. }
  3244. {
  3245. cli.set_basic_auth("hello", "bad");
  3246. auto res = cli.Get(path);
  3247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3248. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3249. }
  3250. {
  3251. cli.set_basic_auth("bad", "world");
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3255. }
  3256. }
  3257. #ifdef CPPHTTPLIB_SSL_ENABLED
  3258. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3259. auto host = "httpbingo.org";
  3260. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3261. auto paths = std::vector<std::string>{
  3262. "/digest-auth/auth/hello/world/MD5",
  3263. "/digest-auth/auth/hello/world/SHA-256",
  3264. };
  3265. auto port = 443;
  3266. SSLClient cli(host, port);
  3267. {
  3268. auto res = cli.Get(unauth_path);
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3271. }
  3272. {
  3273. cli.set_digest_auth("hello", "world");
  3274. for (const auto &path : paths) {
  3275. auto res = cli.Get(path.c_str());
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. auto body = remove_whitespace(res->body);
  3278. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3279. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. cli.set_digest_auth("hello", "bad");
  3283. for (const auto &path : paths) {
  3284. auto res = cli.Get(path.c_str());
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3287. }
  3288. }
  3289. }
  3290. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3291. // comma-separated list of challenges, and each challenge may itself carry a
  3292. // comma-separated auth-param list, so a server can legally offer Basic
  3293. // before Digest, either as two field lines or packed into one. Runs one 401
  3294. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3295. // value() joins them in receipt order) and checks that the retry carries a
  3296. // well-formed Digest Authorization header naming expected_realm.
  3297. static void
  3298. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3299. const std::string &expected_realm) {
  3300. std::atomic<int> hits{0};
  3301. Server svr;
  3302. svr.Get("/x", [&](const Request &req, Response &res) {
  3303. if (++hits == 1) {
  3304. res.status = StatusCode::Unauthorized_401;
  3305. for (const auto &challenge : challenges) {
  3306. res.set_header("WWW-Authenticate", challenge);
  3307. }
  3308. } else {
  3309. auto authorization = req.get_header_value("Authorization");
  3310. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3311. EXPECT_NE(std::string::npos,
  3312. authorization.find("realm=\"" + expected_realm + "\""));
  3313. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3314. res.set_content("ok", "text/plain");
  3315. }
  3316. });
  3317. auto port = svr.bind_to_any_port(HOST);
  3318. std::thread t([&]() { svr.listen_after_bind(); });
  3319. auto se = detail::scope_exit([&] {
  3320. svr.stop();
  3321. t.join();
  3322. });
  3323. svr.wait_until_ready();
  3324. Client cli(HOST, port);
  3325. cli.set_digest_auth("hello", "world");
  3326. auto res = cli.Get("/x");
  3327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3328. EXPECT_EQ(2, hits.load());
  3329. }
  3330. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3331. static const char *kDigestChallenge =
  3332. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3333. "algorithm=MD5";
  3334. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3335. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3336. "testrealm");
  3337. }
  3338. // Same challenge list with the schemes in the opposite order, to make sure
  3339. // the fix above didn't just special-case "Basic first".
  3340. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3341. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3342. "testrealm");
  3343. }
  3344. // A comma inside a quoted auth-param value must not be mistaken for the
  3345. // separator between two challenges (or two auth-params).
  3346. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3347. run_digest_challenge_list_test(
  3348. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3349. "algorithm=MD5"},
  3350. "test,realm");
  3351. }
  3352. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3353. // the params and leaves out the fragment.
  3354. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3355. Server svr;
  3356. std::string uri, target;
  3357. svr.Get("/a b", [&](const Request &req, Response &res) {
  3358. auto auth = req.get_header_value("Authorization");
  3359. if (auth.empty()) {
  3360. res.status = StatusCode::Unauthorized_401;
  3361. res.set_header("WWW-Authenticate",
  3362. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3363. return;
  3364. }
  3365. auto b = auth.find("uri=\"") + 5;
  3366. uri = auth.substr(b, auth.find('"', b) - b);
  3367. target = req.target;
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. std::thread t([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. t.join();
  3374. });
  3375. svr.wait_until_ready();
  3376. Client cli(HOST, port);
  3377. cli.set_digest_auth("hello", "world");
  3378. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ("/a%20b?x=1", target);
  3381. EXPECT_EQ(target, uri);
  3382. }
  3383. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3384. // make_digest_authentication_header() dereferences both unconditionally, so
  3385. // a server sending a challenge missing either one must not be treated as
  3386. // usable -- doing so used to crash the client with std::out_of_range.
  3387. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3388. Server svr;
  3389. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3390. res.status = StatusCode::Unauthorized_401;
  3391. res.set_header("WWW-Authenticate", challenge);
  3392. });
  3393. auto port = svr.bind_to_any_port(HOST);
  3394. std::thread t([&]() { svr.listen_after_bind(); });
  3395. auto se = detail::scope_exit([&] {
  3396. svr.stop();
  3397. t.join();
  3398. });
  3399. svr.wait_until_ready();
  3400. Client cli(HOST, port);
  3401. cli.set_digest_auth("hello", "world");
  3402. auto res = cli.Get("/x");
  3403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3404. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3405. }
  3406. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3407. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3408. }
  3409. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3410. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3411. }
  3412. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3413. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3414. }
  3415. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3416. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3417. // when storing the values, so the header builder has to re-escape them (and
  3418. // keep algorithm a bare token); otherwise the value breaks out of its
  3419. // quoted-string and injects extra auth-params into the client's Authorization.
  3420. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3421. std::atomic<int> hits{0};
  3422. std::string authorization;
  3423. Server svr;
  3424. svr.Get("/x", [&](const Request &req, Response &res) {
  3425. if (++hits == 1) {
  3426. res.status = StatusCode::Unauthorized_401;
  3427. // On the wire the quotes embedded in the values are backslash-escaped.
  3428. res.set_header("WWW-Authenticate",
  3429. "Digest realm=\"testrealm\", "
  3430. "nonce=\"n\\\"; injected=\\\"x\", "
  3431. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3432. } else {
  3433. authorization = req.get_header_value("Authorization");
  3434. res.set_content("ok", "text/plain");
  3435. }
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. std::thread t([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. t.join();
  3442. });
  3443. svr.wait_until_ready();
  3444. Client cli(HOST, port);
  3445. cli.set_digest_auth("hello", "world");
  3446. auto res = cli.Get("/x");
  3447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3448. EXPECT_EQ(2, hits.load());
  3449. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3450. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3451. // inside its quoted-string rather than starting an "injected" auth-param.
  3452. EXPECT_NE(std::string::npos,
  3453. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3454. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3455. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3456. }
  3457. #endif
  3458. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3459. auto host = "google.com";
  3460. auto another_host = "example.com";
  3461. auto wrong_ip = "0.0.0.0";
  3462. #ifdef CPPHTTPLIB_SSL_ENABLED
  3463. SSLClient cli(host);
  3464. #else
  3465. Client cli(host);
  3466. #endif
  3467. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3468. auto res = cli.Get("/");
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3471. }
  3472. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3473. auto host = "google.com";
  3474. auto wrong_ip = "0.0.0.0";
  3475. #ifdef CPPHTTPLIB_SSL_ENABLED
  3476. SSLClient cli(host);
  3477. #else
  3478. Client cli(host);
  3479. #endif
  3480. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3481. auto res = cli.Get("/");
  3482. ASSERT_TRUE(!res);
  3483. EXPECT_EQ(Error::Connection, res.error());
  3484. }
  3485. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3486. // A mapped value that is not an IP literal must be resolved. "localhost"
  3487. // resolves from the hosts file, so this test needs no external DNS.
  3488. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3489. auto host = "target.invalid";
  3490. Server svr;
  3491. std::string received_host;
  3492. svr.Get("/hi", [&](const Request &req, Response &res) {
  3493. received_host = req.get_header_value("Host");
  3494. res.set_content("Hello World!", "text/plain");
  3495. });
  3496. auto port = svr.bind_to_any_port(HOST);
  3497. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3498. auto se = detail::scope_exit([&] {
  3499. svr.stop();
  3500. thread.join();
  3501. ASSERT_FALSE(svr.is_running());
  3502. });
  3503. svr.wait_until_ready();
  3504. Client cli(host, port);
  3505. cli.set_direct_hostname_addr_map({{host, HOST}});
  3506. auto res = cli.Get("/hi");
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. // The mapping only redirects the connection; the identity stays host_.
  3510. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3511. }
  3512. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3513. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3514. auto host = "target.invalid";
  3515. Server svr;
  3516. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3517. res.set_content("Hello World!", "text/plain");
  3518. });
  3519. auto port = svr.bind_to_any_port("127.0.0.1");
  3520. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3521. auto se = detail::scope_exit([&] {
  3522. svr.stop();
  3523. thread.join();
  3524. ASSERT_FALSE(svr.is_running());
  3525. });
  3526. svr.wait_until_ready();
  3527. Client cli(host, port);
  3528. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3529. auto res = cli.Get("/hi");
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. }
  3533. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3534. // An empty mapped value must leave host_ as the connection target. Without
  3535. // that guard the empty value would become the host argument, getaddrinfo
  3536. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3537. // loopback - silently connecting somewhere the caller never asked for.
  3538. // The server listens on loopback, so such a fallback would succeed and is
  3539. // therefore observable as a failure of this test.
  3540. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3541. Server svr;
  3542. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3543. res.set_content("Hello World!", "text/plain");
  3544. });
  3545. auto port = svr.bind_to_any_port(HOST);
  3546. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3547. auto se = detail::scope_exit([&] {
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. });
  3552. svr.wait_until_ready();
  3553. Client cli(blackhole, port);
  3554. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3555. cli.set_connection_timeout(1);
  3556. auto res = cli.Get("/hi");
  3557. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3558. }
  3559. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3560. auto host = "target.invalid";
  3561. Server svr;
  3562. std::string received_host;
  3563. svr.Get("/hi", [&](const Request &req, Response &res) {
  3564. received_host = req.get_header_value("Host");
  3565. res.set_content("Hello World!", "text/plain");
  3566. });
  3567. auto port = svr.bind_to_any_port("127.0.0.1");
  3568. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3569. auto se = detail::scope_exit([&] {
  3570. svr.stop();
  3571. thread.join();
  3572. ASSERT_FALSE(svr.is_running());
  3573. });
  3574. svr.wait_until_ready();
  3575. Client cli(host, port);
  3576. #pragma GCC diagnostic push
  3577. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3578. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3579. #pragma GCC diagnostic pop
  3580. auto res = cli.Get("/hi");
  3581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3584. }
  3585. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3586. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3587. Server svr;
  3588. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3589. res.set_content("Hello World!", "text/plain");
  3590. });
  3591. auto port = svr.bind_to_any_port("127.0.0.1");
  3592. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3593. auto se = detail::scope_exit([&] {
  3594. svr.stop();
  3595. thread.join();
  3596. ASSERT_FALSE(svr.is_running());
  3597. });
  3598. svr.wait_until_ready();
  3599. Client cli("127.0.0.1", port);
  3600. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3601. cli.set_connection_timeout(1);
  3602. auto res = cli.Get("/hi");
  3603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3604. EXPECT_EQ(StatusCode::OK_200, res->status);
  3605. }
  3606. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3607. auto host = "httpbingo.org";
  3608. auto path = std::string{"/absolute-redirect/3"};
  3609. #ifdef CPPHTTPLIB_SSL_ENABLED
  3610. SSLClient cli(host);
  3611. #else
  3612. Client cli(host);
  3613. #endif
  3614. cli.set_follow_location(true);
  3615. auto res = cli.Get(path);
  3616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. }
  3619. TEST(RedirectTest, Redirect_Online) {
  3620. auto host = "httpbingo.org";
  3621. auto path = std::string{"/redirect/3"};
  3622. #ifdef CPPHTTPLIB_SSL_ENABLED
  3623. SSLClient cli(host);
  3624. #else
  3625. Client cli(host);
  3626. #endif
  3627. cli.set_follow_location(true);
  3628. auto res = cli.Get(path);
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. }
  3632. TEST(RelativeRedirectTest, Redirect_Online) {
  3633. auto host = "httpbingo.org";
  3634. auto path = std::string{"/relative-redirect/3"};
  3635. #ifdef CPPHTTPLIB_SSL_ENABLED
  3636. SSLClient cli(host);
  3637. #else
  3638. Client cli(host);
  3639. #endif
  3640. cli.set_follow_location(true);
  3641. auto res = cli.Get(path);
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. }
  3645. TEST(TooManyRedirectTest, Redirect_Online) {
  3646. auto host = "httpbingo.org";
  3647. auto path = std::string{"/redirect/21"};
  3648. #ifdef CPPHTTPLIB_SSL_ENABLED
  3649. SSLClient cli(host);
  3650. #else
  3651. Client cli(host);
  3652. #endif
  3653. cli.set_follow_location(true);
  3654. auto res = cli.Get(path);
  3655. ASSERT_TRUE(!res);
  3656. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3657. }
  3658. #ifdef CPPHTTPLIB_SSL_ENABLED
  3659. TEST(YahooRedirectTest, Redirect_Online) {
  3660. Client cli("yahoo.com");
  3661. auto res = cli.Get("/");
  3662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3663. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3664. cli.set_follow_location(true);
  3665. res = cli.Get("/");
  3666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3669. }
  3670. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3671. #define REDIR_HOST "httpbingo.org"
  3672. #define REDIR_PATH "/redirect-to"
  3673. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3674. SSLClient cli(REDIR_HOST);
  3675. cli.set_follow_location(true);
  3676. auto res =
  3677. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. }
  3681. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3682. SSLClient cli(REDIR_HOST);
  3683. cli.set_follow_location(true);
  3684. Params params;
  3685. params.emplace("url", "http://example.com");
  3686. params.emplace("status_code", "302");
  3687. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3689. EXPECT_EQ(StatusCode::OK_200, res->status);
  3690. }
  3691. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3692. SSLClient cli(REDIR_HOST);
  3693. cli.set_follow_location(true);
  3694. Params params;
  3695. params.emplace("url", "http://example.com");
  3696. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::OK_200, res->status);
  3699. }
  3700. TEST(UrlWithSpace, Redirect_Online) {
  3701. SSLClient cli("edge.forgecdn.net");
  3702. cli.set_follow_location(true);
  3703. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. EXPECT_EQ(StatusCode::OK_200, res->status);
  3706. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3707. }
  3708. #endif
  3709. #if !defined(_WIN32) && !defined(_WIN64)
  3710. TEST(ReceiveSignals, Signal) {
  3711. auto setupSignalHandlers = []() {
  3712. struct sigaction act;
  3713. sigemptyset(&act.sa_mask);
  3714. act.sa_flags = SA_SIGINFO;
  3715. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3716. switch (sig) {
  3717. case SIGINT:
  3718. default: break;
  3719. }
  3720. };
  3721. ::sigaction(SIGINT, &act, nullptr);
  3722. };
  3723. Server svr;
  3724. int port = 0;
  3725. auto thread = std::thread([&]() {
  3726. setupSignalHandlers();
  3727. port = svr.bind_to_any_port(HOST);
  3728. svr.listen_after_bind();
  3729. });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. ASSERT_TRUE(svr.is_running());
  3737. pthread_kill(thread.native_handle(), SIGINT);
  3738. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3739. ASSERT_TRUE(svr.is_running());
  3740. }
  3741. #endif
  3742. TEST(RedirectToDifferentPort, Redirect) {
  3743. Server svr1;
  3744. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3745. res.set_content("Hello World!", "text/plain");
  3746. });
  3747. int svr1_port = 0;
  3748. auto thread1 = std::thread([&]() {
  3749. svr1_port = svr1.bind_to_any_port(HOST);
  3750. svr1.listen_after_bind();
  3751. });
  3752. Server svr2;
  3753. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3754. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3755. });
  3756. int svr2_port = 0;
  3757. auto thread2 = std::thread([&]() {
  3758. svr2_port = svr2.bind_to_any_port(HOST);
  3759. svr2.listen_after_bind();
  3760. });
  3761. auto se = detail::scope_exit([&] {
  3762. svr2.stop();
  3763. thread2.join();
  3764. svr1.stop();
  3765. thread1.join();
  3766. ASSERT_FALSE(svr2.is_running());
  3767. ASSERT_FALSE(svr1.is_running());
  3768. });
  3769. svr1.wait_until_ready();
  3770. svr2.wait_until_ready();
  3771. Client cli("localhost", svr2_port);
  3772. cli.set_follow_location(true);
  3773. auto res = cli.Get("/2");
  3774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3775. EXPECT_EQ(StatusCode::OK_200, res->status);
  3776. EXPECT_EQ("Hello World!", res->body);
  3777. }
  3778. // GET /redir on one server redirects to /target on another port, so the
  3779. // client follows it with a new client.
  3780. static Result
  3781. GetThroughRedirectToDifferentPort(Server::Handler target,
  3782. const std::function<void(Client &)> &setup,
  3783. const Headers &headers = Headers()) {
  3784. Server target_svr;
  3785. target_svr.Get("/target", target);
  3786. int target_port = 0;
  3787. auto target_thread = std::thread([&]() {
  3788. target_port = target_svr.bind_to_any_port(HOST);
  3789. target_svr.listen_after_bind();
  3790. });
  3791. Server origin_svr;
  3792. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3793. res.set_redirect(
  3794. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3795. });
  3796. int origin_port = 0;
  3797. auto origin_thread = std::thread([&]() {
  3798. origin_port = origin_svr.bind_to_any_port(HOST);
  3799. origin_svr.listen_after_bind();
  3800. });
  3801. auto se = detail::scope_exit([&] {
  3802. origin_svr.stop();
  3803. origin_thread.join();
  3804. target_svr.stop();
  3805. target_thread.join();
  3806. });
  3807. target_svr.wait_until_ready();
  3808. origin_svr.wait_until_ready();
  3809. Client cli("localhost", origin_port);
  3810. cli.set_follow_location(true);
  3811. setup(cli);
  3812. return cli.Get("/redir", headers);
  3813. }
  3814. static void
  3815. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3816. std::string captured_authorization;
  3817. auto result = GetThroughRedirectToDifferentPort(
  3818. [&](const Request &req, Response &res) {
  3819. captured_authorization = req.get_header_value("Authorization");
  3820. res.set_content("OK", "text/plain");
  3821. },
  3822. set_auth);
  3823. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3824. EXPECT_EQ(StatusCode::OK_200, result->status);
  3825. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3826. EXPECT_TRUE(captured_authorization.empty());
  3827. }
  3828. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3829. TestDoNotForwardCredentialsOnRedirect(
  3830. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3831. }
  3832. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3833. TestDoNotForwardCredentialsOnRedirect(
  3834. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3835. }
  3836. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3837. std::string captured_cookie;
  3838. auto result = GetThroughRedirectToDifferentPort(
  3839. [&](const Request &req, Response &res) {
  3840. captured_cookie = req.get_header_value("Cookie");
  3841. res.set_content("OK", "text/plain");
  3842. },
  3843. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3844. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3845. EXPECT_EQ(StatusCode::OK_200, result->status);
  3846. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3847. EXPECT_TRUE(captured_cookie.empty());
  3848. }
  3849. TEST(RedirectToSamePort, ForwardCookie) {
  3850. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3851. // header so that ordinary session flows keep working.
  3852. Server svr;
  3853. std::string captured_cookie;
  3854. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3855. res.set_redirect("/target", 302);
  3856. });
  3857. svr.Get("/target", [&](const Request &req, Response &res) {
  3858. captured_cookie = req.get_header_value("Cookie");
  3859. res.set_content("OK", "text/plain");
  3860. });
  3861. auto port = svr.bind_to_any_port(HOST);
  3862. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3863. auto se = detail::scope_exit([&] {
  3864. svr.stop();
  3865. thread.join();
  3866. ASSERT_FALSE(svr.is_running());
  3867. });
  3868. svr.wait_until_ready();
  3869. Client cli(HOST, port);
  3870. cli.set_follow_location(true);
  3871. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3872. auto res = cli.Get("/redir", headers);
  3873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3874. EXPECT_EQ(StatusCode::OK_200, res->status);
  3875. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3876. }
  3877. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3878. // The Location alone names the next target, on any origin.
  3879. Server target_svr;
  3880. std::string cross_target;
  3881. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3882. cross_target = req.target;
  3883. res.set_content("OK", "text/plain");
  3884. });
  3885. auto target_port = target_svr.bind_to_any_port(HOST);
  3886. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3887. Server origin_svr;
  3888. std::string same_target;
  3889. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3890. res.set_redirect(
  3891. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3892. });
  3893. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3894. res.set_redirect("/landing", 302);
  3895. });
  3896. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3897. same_target = req.target;
  3898. res.set_content("OK", "text/plain");
  3899. });
  3900. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3901. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3902. auto se = detail::scope_exit([&] {
  3903. origin_svr.stop();
  3904. origin_thread.join();
  3905. target_svr.stop();
  3906. target_thread.join();
  3907. });
  3908. target_svr.wait_until_ready();
  3909. origin_svr.wait_until_ready();
  3910. Client cli("localhost", origin_port);
  3911. cli.set_follow_location(true);
  3912. Request req;
  3913. req.method = "GET";
  3914. req.params = {{"api_key", "SECRET"}};
  3915. req.path = "/cross";
  3916. auto res = cli.send(req);
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ("/landing", cross_target);
  3919. req.path = "/same";
  3920. res = cli.send(req);
  3921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3922. EXPECT_EQ("/landing", same_target);
  3923. }
  3924. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3925. std::string authorization;
  3926. std::string trace_id;
  3927. auto result = GetThroughRedirectToDifferentPort(
  3928. [&](const Request &req, Response &res) {
  3929. authorization = req.get_header_value("Authorization");
  3930. trace_id = req.get_header_value("X-Trace-Id");
  3931. res.set_content("OK", "text/plain");
  3932. },
  3933. [](Client &cli) {
  3934. cli.set_default_headers(
  3935. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3936. });
  3937. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3938. EXPECT_EQ(StatusCode::OK_200, result->status);
  3939. // Like a header given with the request, a default one goes along unless it
  3940. // carries credentials (RFC 9110 15.4).
  3941. EXPECT_TRUE(authorization.empty());
  3942. EXPECT_EQ("42", trace_id);
  3943. }
  3944. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3945. auto result = GetThroughRedirectToDifferentPort(
  3946. [](const Request &, Response &res) {
  3947. res.set_content(std::string(2048, 'x'), "text/plain");
  3948. },
  3949. [](Client &cli) { cli.set_payload_max_length(1024); });
  3950. EXPECT_FALSE(result);
  3951. }
  3952. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3953. auto result = GetThroughRedirectToDifferentPort(
  3954. [](const Request &req, Response &res) {
  3955. // Answer after a second, or once the client gives up.
  3956. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3957. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3958. }
  3959. res.set_content("late", "text/plain");
  3960. },
  3961. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3962. ASSERT_FALSE(result);
  3963. EXPECT_EQ(Error::Read, result.error());
  3964. }
  3965. #ifdef CPPHTTPLIB_SSL_ENABLED
  3966. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3967. auto result = GetThroughRedirectToDifferentPort(
  3968. [](const Request &, Response &res) {
  3969. res.status = StatusCode::Unauthorized_401;
  3970. res.set_header("WWW-Authenticate",
  3971. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3972. },
  3973. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3974. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3975. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3976. }
  3977. #endif
  3978. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3979. Server svr;
  3980. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3981. // Port number that overflows int — should not crash
  3982. res.set_redirect("http://localhost:99999999999999999999/target");
  3983. });
  3984. auto port = svr.bind_to_any_port(HOST);
  3985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3986. auto se = detail::scope_exit([&] {
  3987. svr.stop();
  3988. thread.join();
  3989. ASSERT_FALSE(svr.is_running());
  3990. });
  3991. svr.wait_until_ready();
  3992. Client cli(HOST, port);
  3993. cli.set_follow_location(true);
  3994. auto res = cli.Get("/redir");
  3995. // Should fail gracefully, not crash (no valid response due to bad port)
  3996. EXPECT_FALSE(res);
  3997. }
  3998. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3999. Server svr;
  4000. auto port = svr.bind_to_any_port(HOST);
  4001. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4002. // The server's own port followed by junk must not be followed
  4003. res.set_redirect("http://" + std::string(HOST) + ":" +
  4004. std::to_string(port) + "junk/target");
  4005. });
  4006. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4007. res.set_content("target", "text/plain");
  4008. });
  4009. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4010. auto se = detail::scope_exit([&] {
  4011. svr.stop();
  4012. thread.join();
  4013. ASSERT_FALSE(svr.is_running());
  4014. });
  4015. svr.wait_until_ready();
  4016. Client cli(HOST, port);
  4017. cli.set_follow_location(true);
  4018. auto res = cli.Get("/redir");
  4019. EXPECT_FALSE(res);
  4020. }
  4021. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4022. Server target_svr;
  4023. std::atomic<int> target_hits{0};
  4024. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4025. target_hits++;
  4026. res.set_content("target", "text/plain");
  4027. });
  4028. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4029. res.set_content("target", "text/plain");
  4030. });
  4031. int target_port = 0;
  4032. auto target_thread = std::thread([&]() {
  4033. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4034. target_svr.listen_after_bind();
  4035. });
  4036. Server origin_svr;
  4037. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4038. res.set_redirect(req.get_param_value("to"));
  4039. });
  4040. int origin_port = 0;
  4041. auto origin_thread = std::thread([&]() {
  4042. origin_port = origin_svr.bind_to_any_port(HOST);
  4043. origin_svr.listen_after_bind();
  4044. });
  4045. auto se = detail::scope_exit([&] {
  4046. origin_svr.stop();
  4047. origin_thread.join();
  4048. target_svr.stop();
  4049. target_thread.join();
  4050. ASSERT_FALSE(origin_svr.is_running());
  4051. ASSERT_FALSE(target_svr.is_running());
  4052. });
  4053. target_svr.wait_until_ready();
  4054. origin_svr.wait_until_ready();
  4055. auto port = std::to_string(target_port);
  4056. for (const auto &to :
  4057. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4058. Client cli(HOST, origin_port);
  4059. cli.set_follow_location(true);
  4060. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4061. EXPECT_FALSE(res) << to;
  4062. }
  4063. EXPECT_EQ(0, target_hits);
  4064. Client cli(HOST, origin_port);
  4065. cli.set_follow_location(true);
  4066. auto res = cli.Get("/redir?to=" +
  4067. encode_query_component("//127.0.0.1:" + port + "/target"));
  4068. ASSERT_TRUE(res) << to_string(res.error());
  4069. EXPECT_EQ(StatusCode::OK_200, res->status);
  4070. EXPECT_EQ("target", res->body);
  4071. }
  4072. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4073. Server svr;
  4074. std::atomic<bool> followed{false};
  4075. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4076. res.status = StatusCode::NotModified_304;
  4077. res.set_header("Location", "/target");
  4078. });
  4079. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::UseProxy_305;
  4081. res.set_header("Location", "/target");
  4082. });
  4083. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4084. followed = true;
  4085. res.set_content("target", "text/plain");
  4086. });
  4087. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4088. auto se = detail::scope_exit([&] {
  4089. svr.stop();
  4090. th.join();
  4091. ASSERT_FALSE(svr.is_running());
  4092. });
  4093. svr.wait_until_ready();
  4094. Client cli("localhost", PORT);
  4095. cli.set_follow_location(true);
  4096. auto res = cli.Get("/304");
  4097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4098. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4099. res = cli.Get("/305");
  4100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4101. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4102. EXPECT_FALSE(followed);
  4103. }
  4104. TEST(RedirectFromPageWithContent, Redirect) {
  4105. Server svr;
  4106. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4107. res.set_content("___", "text/plain");
  4108. res.set_redirect("/2");
  4109. });
  4110. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4111. res.set_content("Hello World!", "text/plain");
  4112. });
  4113. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4114. auto se = detail::scope_exit([&] {
  4115. svr.stop();
  4116. th.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. svr.wait_until_ready();
  4120. {
  4121. Client cli("localhost", PORT);
  4122. cli.set_follow_location(true);
  4123. std::string body;
  4124. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4125. body.append(data, data_length);
  4126. return true;
  4127. });
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ(StatusCode::OK_200, res->status);
  4130. EXPECT_EQ("Hello World!", body);
  4131. }
  4132. {
  4133. Client cli("localhost", PORT);
  4134. std::string body;
  4135. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4136. body.append(data, data_length);
  4137. return true;
  4138. });
  4139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4140. EXPECT_EQ(StatusCode::Found_302, res->status);
  4141. EXPECT_EQ("___", body);
  4142. }
  4143. }
  4144. // A server can close the connection after a request with "Connection: close"
  4145. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4146. // redirected request must go out on a new connection.
  4147. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4148. #ifndef _WIN32
  4149. signal(SIGPIPE, SIG_IGN);
  4150. #endif
  4151. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4152. default_socket_options(srv);
  4153. sockaddr_in addr{};
  4154. addr.sin_family = AF_INET;
  4155. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4156. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4157. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4158. ASSERT_EQ(0, ::listen(srv, 2));
  4159. auto send_text = [](socket_t sock, const std::string &text) {
  4160. ::send(sock,
  4161. #ifdef _WIN32
  4162. static_cast<const char *>(text.c_str()),
  4163. static_cast<int>(text.size()),
  4164. #else
  4165. text.c_str(), text.size(),
  4166. #endif
  4167. 0);
  4168. };
  4169. auto reused = false;
  4170. auto server_thread = std::thread([&] {
  4171. char buf[4096];
  4172. auto first = ::accept(srv, nullptr, nullptr);
  4173. if (first == INVALID_SOCKET) { return; }
  4174. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4175. ::recv(first, buf, sizeof(buf), 0);
  4176. send_text(
  4177. first,
  4178. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4179. auto next = first;
  4180. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4181. reused = true;
  4182. } else {
  4183. detail::close_socket(first);
  4184. next = ::accept(srv, nullptr, nullptr);
  4185. if (next == INVALID_SOCKET) { return; }
  4186. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4187. ::recv(next, buf, sizeof(buf), 0);
  4188. }
  4189. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4190. "Connection: close\r\n\r\nok");
  4191. detail::close_socket(next);
  4192. });
  4193. Client cli("127.0.0.1", PORT + 2);
  4194. cli.set_follow_location(true);
  4195. cli.set_read_timeout(5, 0);
  4196. auto res = cli.Get("/1");
  4197. server_thread.join();
  4198. detail::close_socket(srv);
  4199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4200. EXPECT_EQ(StatusCode::OK_200, res->status);
  4201. EXPECT_EQ("ok", res->body);
  4202. EXPECT_FALSE(reused);
  4203. }
  4204. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4205. Server svr;
  4206. auto port_str = std::to_string(PORT);
  4207. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4208. auto expected_host = "[::1]:" + port_str;
  4209. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4210. res.set_content("___", "text/plain");
  4211. // res.set_redirect("/2");
  4212. res.set_redirect(redirect_url);
  4213. });
  4214. svr.Get("/2", [&](const Request &req, Response &res) {
  4215. auto host_header = req.headers.find("Host");
  4216. ASSERT_TRUE(host_header != req.headers.end());
  4217. EXPECT_EQ(expected_host, host_header->second);
  4218. res.set_content("Hello World!", "text/plain");
  4219. });
  4220. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4221. auto se = detail::scope_exit([&] {
  4222. svr.stop();
  4223. th.join();
  4224. ASSERT_FALSE(svr.is_running());
  4225. });
  4226. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4227. // actually starts anything, so the condition !svr.is_running() will
  4228. // always remain true, and the loop never stops.
  4229. // This basically counts how many milliseconds have passed since the
  4230. // call to svr.listen(), and if after 5 seconds nothing started yet
  4231. // aborts the test.
  4232. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4233. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4234. ASSERT_LT(milliseconds, 5000U);
  4235. }
  4236. {
  4237. Client cli("::1", PORT);
  4238. cli.set_follow_location(true);
  4239. std::string body;
  4240. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4241. body.append(data, data_length);
  4242. return true;
  4243. });
  4244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4245. EXPECT_EQ(StatusCode::OK_200, res->status);
  4246. EXPECT_EQ("Hello World!", body);
  4247. }
  4248. {
  4249. Client cli("::1", PORT);
  4250. std::string body;
  4251. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4252. body.append(data, data_length);
  4253. return true;
  4254. });
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ(StatusCode::Found_302, res->status);
  4257. EXPECT_EQ("___", body);
  4258. }
  4259. }
  4260. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4261. Server svr;
  4262. svr.Get("/foo", [](const Request &req, Response &res) {
  4263. auto a = req.params.find("a");
  4264. if (a != req.params.end()) {
  4265. res.set_content((*a).second, "text/plain");
  4266. res.status = StatusCode::OK_200;
  4267. } else {
  4268. res.status = StatusCode::BadRequest_400;
  4269. }
  4270. });
  4271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4272. auto se = detail::scope_exit([&] {
  4273. svr.stop();
  4274. thread.join();
  4275. ASSERT_FALSE(svr.is_running());
  4276. });
  4277. svr.wait_until_ready();
  4278. {
  4279. Client cli(HOST, PORT);
  4280. cli.set_path_encode(false);
  4281. auto res = cli.Get("/foo?a=explicitly+encoded");
  4282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. // This expects it back with a space, as the `+` won't have been
  4285. // url-encoded, and server-side the params get decoded turning `+`
  4286. // into spaces.
  4287. EXPECT_EQ("explicitly encoded", res->body);
  4288. }
  4289. }
  4290. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4291. // When path encoding is disabled the client must transmit the supplied
  4292. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4293. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4294. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4295. // than a space (0x20). Assert on the raw wire target to catch this.
  4296. Server svr;
  4297. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4298. svr.Get("/foo", [&](const Request &req, Response &res) {
  4299. EXPECT_EQ(expected_target, req.target);
  4300. res.status = StatusCode::OK_200;
  4301. });
  4302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4303. auto se = detail::scope_exit([&] {
  4304. svr.stop();
  4305. thread.join();
  4306. ASSERT_FALSE(svr.is_running());
  4307. });
  4308. svr.wait_until_ready();
  4309. {
  4310. Client cli(HOST, PORT);
  4311. cli.set_path_encode(false);
  4312. auto res = cli.Get(expected_target.c_str());
  4313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4314. EXPECT_EQ(StatusCode::OK_200, res->status);
  4315. }
  4316. }
  4317. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4318. // `open_stream()` used to skip the path encoding that the buffered send
  4319. // path applies, so the same `path` produced different bytes in the request
  4320. // line depending on which API was used. Assert the two agree.
  4321. Server svr;
  4322. std::string target;
  4323. svr.Get(".*", [&](const Request &req, Response &res) {
  4324. target = req.target;
  4325. res.status = StatusCode::OK_200;
  4326. });
  4327. auto port = svr.bind_to_any_port(HOST);
  4328. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4329. auto se = detail::scope_exit([&] {
  4330. svr.stop();
  4331. thread.join();
  4332. ASSERT_FALSE(svr.is_running());
  4333. });
  4334. svr.wait_until_ready();
  4335. struct {
  4336. const char *path;
  4337. const char *expected;
  4338. } cases[] = {
  4339. {"/a b?x=1", "/a%20b?x=1"},
  4340. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4341. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4342. };
  4343. for (const auto &c : cases) {
  4344. Client cli(HOST, port);
  4345. target.clear();
  4346. auto res = cli.Get(c.path);
  4347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4348. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4349. auto buffered_target = target;
  4350. target.clear();
  4351. auto handle = cli.open_stream("GET", c.path);
  4352. EXPECT_TRUE(handle.is_valid())
  4353. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4354. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4355. }
  4356. }
  4357. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4358. // The `set_path_encode(false)` contract — transmit the supplied target
  4359. // verbatim — must hold for the streaming API too.
  4360. Server svr;
  4361. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4362. std::string target;
  4363. svr.Get("/foo", [&](const Request &req, Response &res) {
  4364. target = req.target;
  4365. res.status = StatusCode::OK_200;
  4366. });
  4367. auto port = svr.bind_to_any_port(HOST);
  4368. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4369. auto se = detail::scope_exit([&] {
  4370. svr.stop();
  4371. thread.join();
  4372. ASSERT_FALSE(svr.is_running());
  4373. });
  4374. svr.wait_until_ready();
  4375. {
  4376. Client cli(HOST, port);
  4377. cli.set_path_encode(false);
  4378. auto handle = cli.open_stream("GET", expected_target);
  4379. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4380. EXPECT_EQ(expected_target, target);
  4381. }
  4382. }
  4383. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4384. // With path encoding enabled a CR/LF in the target is percent-encoded
  4385. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4386. // write_request_line still backstops `set_path_encode(false)`, which is
  4387. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4388. Server svr;
  4389. // Captured before routing: the decoded path contains a newline, which a
  4390. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4391. std::string target;
  4392. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4393. target = req.target;
  4394. res.status = StatusCode::OK_200;
  4395. return Server::HandlerResponse::Handled;
  4396. });
  4397. auto port = svr.bind_to_any_port(HOST);
  4398. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4399. auto se = detail::scope_exit([&] {
  4400. svr.stop();
  4401. thread.join();
  4402. ASSERT_FALSE(svr.is_running());
  4403. });
  4404. svr.wait_until_ready();
  4405. {
  4406. Client cli(HOST, port);
  4407. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4408. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4409. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4410. }
  4411. }
  4412. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4413. // Every control character is percent-encoded, not just CR/LF, so the target
  4414. // passes the request-target check in write_request_line.
  4415. Server svr;
  4416. std::string target;
  4417. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4418. target = req.target;
  4419. res.status = StatusCode::OK_200;
  4420. return Server::HandlerResponse::Handled;
  4421. });
  4422. auto port = svr.bind_to_any_port(HOST);
  4423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4424. auto se = detail::scope_exit([&] {
  4425. svr.stop();
  4426. thread.join();
  4427. ASSERT_FALSE(svr.is_running());
  4428. });
  4429. svr.wait_until_ready();
  4430. {
  4431. Client cli(HOST, port);
  4432. auto res = cli.Get("/a\tb\x1b\x7f");
  4433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4434. EXPECT_EQ("/a%09b%1B%7F", target);
  4435. }
  4436. }
  4437. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4438. // Nothing may reach the wire: a raw CR/LF target would split the request
  4439. // line and inject headers.
  4440. Server svr;
  4441. // Pre-routing so that "not called" means nothing reached the server at all,
  4442. // rather than merely failing to match a handler pattern.
  4443. auto handler_called = false;
  4444. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4445. handler_called = true;
  4446. res.status = StatusCode::OK_200;
  4447. return Server::HandlerResponse::Handled;
  4448. });
  4449. auto port = svr.bind_to_any_port(HOST);
  4450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4451. auto se = detail::scope_exit([&] {
  4452. svr.stop();
  4453. thread.join();
  4454. ASSERT_FALSE(svr.is_running());
  4455. });
  4456. svr.wait_until_ready();
  4457. {
  4458. Client cli(HOST, port);
  4459. cli.set_path_encode(false);
  4460. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4461. EXPECT_FALSE(handle.is_valid());
  4462. EXPECT_EQ(Error::Write, handle.error);
  4463. EXPECT_FALSE(handler_called);
  4464. }
  4465. }
  4466. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4467. // Which of the two branches runs is decided by whether the query component
  4468. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4469. // an empty query and must still fall back to building one from
  4470. // `req.params`, while a non-empty query must win over `req.params`.
  4471. Server svr;
  4472. std::string target;
  4473. svr.Get("/foo", [&](const Request &req, Response &res) {
  4474. target = req.target;
  4475. res.status = StatusCode::OK_200;
  4476. });
  4477. auto port = svr.bind_to_any_port(HOST);
  4478. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4479. auto se = detail::scope_exit([&] {
  4480. svr.stop();
  4481. thread.join();
  4482. ASSERT_FALSE(svr.is_running());
  4483. });
  4484. svr.wait_until_ready();
  4485. {
  4486. // Trailing `?` -> empty query component -> `req.params` is used.
  4487. Client cli(HOST, port);
  4488. Request req;
  4489. req.method = "GET";
  4490. req.path = "/foo?";
  4491. req.params.emplace("a", "1");
  4492. target.clear();
  4493. auto res = cli.send(req);
  4494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4495. EXPECT_EQ("/foo?a=1", target);
  4496. }
  4497. {
  4498. // Non-empty query in `req.path` -> `req.params` is not appended.
  4499. Client cli(HOST, port);
  4500. Request req;
  4501. req.method = "GET";
  4502. req.path = "/foo?b=2";
  4503. req.params.emplace("a", "1");
  4504. target.clear();
  4505. auto res = cli.send(req);
  4506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4507. EXPECT_EQ("/foo?b=2", target);
  4508. }
  4509. }
  4510. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4511. Server svr;
  4512. svr.Get("/", [](const Request &req, Response &) {
  4513. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4514. });
  4515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4516. auto se = detail::scope_exit([&] {
  4517. svr.stop();
  4518. thread.join();
  4519. ASSERT_FALSE(svr.is_running());
  4520. });
  4521. svr.wait_until_ready();
  4522. {
  4523. Client cli(HOST, PORT);
  4524. cli.set_path_encode(false);
  4525. auto res = cli.Get("/?something=%0A");
  4526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. }
  4529. }
  4530. TEST(BindServerTest, BindDualStack) {
  4531. Server svr;
  4532. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4533. res.set_content("Hello World!", "text/plain");
  4534. });
  4535. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. Client cli("127.0.0.1", PORT);
  4544. auto res = cli.Get("/1");
  4545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("Hello World!", res->body);
  4548. }
  4549. {
  4550. Client cli("::1", PORT);
  4551. auto res = cli.Get("/1");
  4552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("Hello World!", res->body);
  4555. }
  4556. }
  4557. TEST(BindServerTest, BindAndListenSeparately) {
  4558. Server svr;
  4559. int port = svr.bind_to_any_port("0.0.0.0");
  4560. ASSERT_TRUE(svr.is_valid());
  4561. ASSERT_TRUE(port > 0);
  4562. svr.stop();
  4563. }
  4564. // Reports whether anything is still listening on a loopback port. A plain
  4565. // connect() is used instead of a Client request because a socket left bound by
  4566. // mistake accepts the connection into its backlog and never answers, which
  4567. // would hang the test instead of failing it.
  4568. static bool is_loopback_port_accepting(int port) {
  4569. sockaddr_in addr{};
  4570. addr.sin_family = AF_INET;
  4571. addr.sin_port = htons(static_cast<uint16_t>(port));
  4572. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4573. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4574. EXPECT_NE(sock, INVALID_SOCKET);
  4575. if (sock == INVALID_SOCKET) { return false; }
  4576. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4577. static_cast<socklen_t>(sizeof(addr)));
  4578. detail::close_socket(sock);
  4579. return ret == 0;
  4580. }
  4581. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4582. Server svr;
  4583. auto port = svr.bind_to_any_port("127.0.0.1");
  4584. ASSERT_TRUE(port > 0);
  4585. svr.stop();
  4586. // bind_to_any_port() already called listen(2), so until stop() closed the
  4587. // descriptor the port kept accepting connections into the backlog. ASSERT
  4588. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4589. // below blocks forever in the accept loop.
  4590. ASSERT_FALSE(is_loopback_port_accepting(port));
  4591. // Nothing is left to accept on, so listen_after_bind() must report failure
  4592. // instead of returning success without ever serving.
  4593. EXPECT_FALSE(svr.listen_after_bind());
  4594. // The failed listen marks the server decommissioned, so a waiter returns
  4595. // instead of spinning forever.
  4596. svr.wait_until_ready();
  4597. }
  4598. #ifdef CPPHTTPLIB_SSL_ENABLED
  4599. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4601. CLIENT_CA_CERT_DIR);
  4602. int port = svr.bind_to_any_port("0.0.0.0");
  4603. ASSERT_TRUE(svr.is_valid());
  4604. ASSERT_TRUE(port > 0);
  4605. svr.stop();
  4606. }
  4607. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4608. // or a rejected CustomRoute() registration would not stop the server binding.
  4609. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4611. CLIENT_CA_CERT_DIR);
  4612. ASSERT_TRUE(svr.is_valid());
  4613. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4614. EXPECT_FALSE(svr.is_valid());
  4615. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4616. }
  4617. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4618. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4619. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4620. int port = svr.bind_to_any_port("0.0.0.0");
  4621. ASSERT_TRUE(svr.is_valid());
  4622. ASSERT_TRUE(port > 0);
  4623. svr.stop();
  4624. }
  4625. TEST(BindServerTest, UpdateCertsPem) {
  4626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4627. int port = svr.bind_to_any_port("0.0.0.0");
  4628. ASSERT_TRUE(svr.is_valid());
  4629. ASSERT_TRUE(port > 0);
  4630. // Read PEM files
  4631. std::string cert_pem, key_pem, ca_pem;
  4632. read_file(SERVER_CERT_FILE, cert_pem);
  4633. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4634. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4635. // Update server certificates using PEM API
  4636. ASSERT_TRUE(
  4637. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4638. ASSERT_TRUE(svr.is_valid());
  4639. svr.stop();
  4640. }
  4641. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4642. // Start server with client CA (enables client auth)
  4643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4644. ASSERT_TRUE(svr.is_valid());
  4645. bool handler_called = false;
  4646. svr.Get("/test", [&](const Request &req, Response &res) {
  4647. handler_called = true;
  4648. // Verify client certificate is present
  4649. auto cert = req.peer_cert();
  4650. EXPECT_TRUE(static_cast<bool>(cert));
  4651. res.set_content("ok", "text/plain");
  4652. });
  4653. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4654. auto se = detail::scope_exit([&] {
  4655. svr.stop();
  4656. t.join();
  4657. ASSERT_FALSE(svr.is_running());
  4658. });
  4659. svr.wait_until_ready();
  4660. // Read PEM files
  4661. std::string cert_pem, key_pem, ca_pem;
  4662. read_file(SERVER_CERT_FILE, cert_pem);
  4663. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4664. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4665. // Update server certificates and client CA using PEM API while server running
  4666. ASSERT_TRUE(
  4667. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4668. // Connect with client certificate
  4669. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4670. cli.enable_server_certificate_verification(false);
  4671. cli.set_connection_timeout(30);
  4672. auto res = cli.Get("/test");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_TRUE(handler_called);
  4676. EXPECT_EQ("ok", res->body);
  4677. }
  4678. // Puts a CA that did not sign the client's certificate in the old one's place.
  4679. static bool replace_client_ca(SSLServer &svr) {
  4680. std::string cert_pem, key_pem, ca_pem;
  4681. read_file(SERVER_CERT_FILE, cert_pem);
  4682. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4683. read_file(SERVER_CERT2_FILE, ca_pem);
  4684. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4685. ca_pem.c_str());
  4686. }
  4687. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4689. ASSERT_TRUE(svr.is_valid());
  4690. svr.Get("/test", [](const Request &, Response &res) {
  4691. res.set_content("ok", "text/plain");
  4692. });
  4693. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4694. auto se = detail::scope_exit([&] {
  4695. svr.stop();
  4696. t.join();
  4697. ASSERT_FALSE(svr.is_running());
  4698. });
  4699. svr.wait_until_ready();
  4700. auto get = [] {
  4701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4702. cli.enable_server_certificate_verification(false);
  4703. return cli.Get("/test");
  4704. };
  4705. ASSERT_TRUE(get());
  4706. ASSERT_TRUE(replace_client_ca(svr));
  4707. EXPECT_FALSE(get());
  4708. }
  4709. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4710. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4712. ASSERT_TRUE(svr.is_valid());
  4713. tls::set_verify_callback(svr.tls_context(),
  4714. [](const tls::VerifyContext &) -> bool {
  4715. throw std::runtime_error("verify");
  4716. });
  4717. svr.Get("/test", [](const Request &, Response &res) {
  4718. res.set_content("ok", "text/plain");
  4719. });
  4720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4721. auto se = detail::scope_exit([&] {
  4722. svr.stop();
  4723. t.join();
  4724. ASSERT_FALSE(svr.is_running());
  4725. });
  4726. svr.wait_until_ready();
  4727. auto get = [] {
  4728. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4729. cli.enable_server_certificate_verification(false);
  4730. return cli.Get("/test");
  4731. };
  4732. EXPECT_FALSE(get());
  4733. // The handshake is over, so an update does not wait for it.
  4734. std::string cert_pem, key_pem;
  4735. read_file(SERVER_CERT_FILE, cert_pem);
  4736. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4737. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4738. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4739. return v.preverify_ok;
  4740. });
  4741. auto res = get();
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. EXPECT_EQ("ok", res->body);
  4744. }
  4745. #endif
  4746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4747. // Sends each request over a new connection with a client certificate,
  4748. // resuming the session of the one before when there is one.
  4749. class ResumingClient {
  4750. public:
  4751. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4752. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4753. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4754. SSL_FILETYPE_PEM);
  4755. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4756. // callback, not through SSL_get1_session().
  4757. SSL_CTX_set_app_data(ctx_, this);
  4758. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4759. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4760. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4761. auto self = static_cast<ResumingClient *>(
  4762. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4763. SSL_SESSION_free(self->session_);
  4764. self->session_ = session;
  4765. return 1; // Keeps the reference
  4766. });
  4767. }
  4768. ~ResumingClient() {
  4769. SSL_SESSION_free(session_);
  4770. SSL_CTX_free(ctx_);
  4771. }
  4772. // Tells whether the request was answered.
  4773. bool get() {
  4774. auto error = Error::Success;
  4775. auto sock = detail::create_client_socket(
  4776. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4777. /*connection_timeout_sec=*/5, 0,
  4778. /*read_timeout_sec=*/5, 0,
  4779. /*write_timeout_sec=*/5, 0, std::string(), error);
  4780. if (sock == INVALID_SOCKET) { return false; }
  4781. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4782. auto ssl = SSL_new(ctx_);
  4783. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4784. SSL_set_fd(ssl, static_cast<int>(sock));
  4785. if (session_) { SSL_set_session(ssl, session_); }
  4786. if (SSL_connect(ssl) != 1) { return false; }
  4787. reused_ = SSL_session_reused(ssl) == 1;
  4788. // Reading the response also takes in a TLS 1.3 session ticket.
  4789. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4790. "Connection: close\r\n\r\n";
  4791. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4792. std::string res;
  4793. char buf[256];
  4794. int n;
  4795. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4796. res.append(buf, static_cast<size_t>(n));
  4797. }
  4798. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4799. SSL_shutdown(ssl);
  4800. return res.find("200 OK") != std::string::npos;
  4801. }
  4802. // Whether the last connection resumed a session
  4803. bool reused() const { return reused_; }
  4804. private:
  4805. SSL_CTX *ctx_;
  4806. SSL_SESSION *session_ = nullptr;
  4807. bool reused_ = false;
  4808. };
  4809. // A client that resumes its session gets through, but not once the client CA
  4810. // has changed, as a resumed session does not show the certificate again.
  4811. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4813. ASSERT_TRUE(svr.is_valid());
  4814. svr.Get("/test", [](const Request &, Response &res) {
  4815. res.set_content("ok", "text/plain");
  4816. });
  4817. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4818. auto se = detail::scope_exit([&] {
  4819. svr.stop();
  4820. t.join();
  4821. ASSERT_FALSE(svr.is_running());
  4822. });
  4823. svr.wait_until_ready();
  4824. ResumingClient cli;
  4825. ASSERT_TRUE(cli.get());
  4826. ASSERT_TRUE(cli.get());
  4827. EXPECT_TRUE(cli.reused());
  4828. ASSERT_TRUE(replace_client_ca(svr));
  4829. EXPECT_FALSE(cli.get());
  4830. }
  4831. // A resumed session does not show the certificate again, so the server does
  4832. // not resume one with a verify callback to run on it.
  4833. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4835. ASSERT_TRUE(svr.is_valid());
  4836. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4837. return v.preverify_ok;
  4838. });
  4839. svr.Get("/test", [](const Request &, Response &res) {
  4840. res.set_content("ok", "text/plain");
  4841. });
  4842. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4843. auto se = detail::scope_exit([&] {
  4844. svr.stop();
  4845. t.join();
  4846. ASSERT_FALSE(svr.is_running());
  4847. });
  4848. svr.wait_until_ready();
  4849. ResumingClient cli;
  4850. ASSERT_TRUE(cli.get());
  4851. ASSERT_TRUE(cli.get());
  4852. EXPECT_FALSE(cli.reused());
  4853. }
  4854. #endif
  4855. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4856. // wolfSSL shares its session cache between contexts, so a resumed session
  4857. // could carry a client certificate checked against another server's CA, or
  4858. // against a client CA since replaced.
  4859. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4861. ASSERT_TRUE(svr.is_valid());
  4862. // Trusts a CA that did not sign the client's certificate.
  4863. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4864. ASSERT_TRUE(other.is_valid());
  4865. for (auto s : {&svr, &other}) {
  4866. s->Get("/test", [](const Request &, Response &res) {
  4867. res.set_content("ok", "text/plain");
  4868. });
  4869. }
  4870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4871. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4872. auto se = detail::scope_exit([&] {
  4873. other.stop();
  4874. svr.stop();
  4875. t2.join();
  4876. t.join();
  4877. });
  4878. svr.wait_until_ready();
  4879. other.wait_until_ready();
  4880. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4881. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4882. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4883. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4884. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4885. ASSERT_EQ(WOLFSSL_SUCCESS,
  4886. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4887. WOLFSSL_FILETYPE_PEM));
  4888. WOLFSSL_SESSION *session = nullptr;
  4889. auto session_se = detail::scope_exit([&] {
  4890. if (session) { wolfSSL_SESSION_free(session); }
  4891. });
  4892. // A request over a new connection, resuming `session` when there is one and
  4893. // keeping the connection's own in its place. Tells whether it was answered.
  4894. auto get = [&](int port) {
  4895. auto error = Error::Success;
  4896. auto sock = detail::create_client_socket(
  4897. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4898. /*connection_timeout_sec=*/5, 0,
  4899. /*read_timeout_sec=*/5, 0,
  4900. /*write_timeout_sec=*/5, 0, std::string(), error);
  4901. if (sock == INVALID_SOCKET) { return false; }
  4902. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4903. auto ssl = wolfSSL_new(ctx);
  4904. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4905. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4906. if (session) { wolfSSL_set_session(ssl, session); }
  4907. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4908. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4909. "Connection: close\r\n\r\n";
  4910. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4911. std::string res;
  4912. char buf[256];
  4913. int n;
  4914. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4915. res.append(buf, static_cast<size_t>(n));
  4916. }
  4917. wolfSSL_shutdown(ssl);
  4918. if (session) { wolfSSL_SESSION_free(session); }
  4919. session = wolfSSL_get1_session(ssl);
  4920. return res.find("200 OK") != std::string::npos;
  4921. };
  4922. ASSERT_TRUE(get(PORT));
  4923. EXPECT_FALSE(get(PORT + 1));
  4924. ASSERT_TRUE(get(PORT));
  4925. ASSERT_TRUE(replace_client_ca(svr));
  4926. EXPECT_FALSE(get(PORT));
  4927. }
  4928. #endif
  4929. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4931. ASSERT_TRUE(svr.is_valid());
  4932. // Keep-alive parking would wait for the ClientHello without a handshake.
  4933. svr.set_keep_alive_parking(false);
  4934. svr.Get("/test", [](const Request &, Response &res) {
  4935. res.set_content("ok", "text/plain");
  4936. });
  4937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4938. auto se = detail::scope_exit([&] {
  4939. svr.stop();
  4940. t.join();
  4941. ASSERT_FALSE(svr.is_running());
  4942. });
  4943. svr.wait_until_ready();
  4944. // A connection that sends no ClientHello keeps its handshake in progress,
  4945. // once the server has had a moment to start it.
  4946. auto error = Error::Success;
  4947. auto sock = detail::create_client_socket(
  4948. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4949. /*connection_timeout_sec=*/5, 0,
  4950. /*read_timeout_sec=*/5, 0,
  4951. /*write_timeout_sec=*/5, 0, std::string(), error);
  4952. ASSERT_NE(INVALID_SOCKET, sock);
  4953. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4954. std::string cert_pem, key_pem;
  4955. read_file(SERVER_CERT_FILE, cert_pem);
  4956. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4957. auto update = std::async(std::launch::async, [&]() {
  4958. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4959. });
  4960. EXPECT_EQ(std::future_status::timeout,
  4961. update.wait_for(std::chrono::milliseconds(200)));
  4962. detail::close_socket(sock);
  4963. EXPECT_TRUE(update.get());
  4964. SSLClient cli(HOST, PORT);
  4965. cli.enable_server_certificate_verification(false);
  4966. auto res = cli.Get("/test");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. }
  4970. #endif
  4971. TEST(ErrorHandlerTest, ContentLength) {
  4972. Server svr;
  4973. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4974. res.status = StatusCode::OK_200;
  4975. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4976. "text/html"); // <= Content-Length still 13
  4977. });
  4978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4979. res.set_content("Hello World!\n", "text/plain");
  4980. res.status = 524;
  4981. });
  4982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4983. auto se = detail::scope_exit([&] {
  4984. svr.stop();
  4985. thread.join();
  4986. ASSERT_FALSE(svr.is_running());
  4987. });
  4988. svr.wait_until_ready();
  4989. {
  4990. Client cli(HOST, PORT);
  4991. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4995. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4996. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4997. }
  4998. }
  4999. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5000. TEST(ExceptionTest, WithoutExceptionHandler) {
  5001. Server svr;
  5002. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5003. throw std::runtime_error("exception...");
  5004. });
  5005. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5006. throw std::runtime_error("exception\r\n...");
  5007. });
  5008. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. listen_thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli("localhost", PORT);
  5016. {
  5017. auto res = cli.Get("/exception");
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5020. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5021. }
  5022. {
  5023. auto res = cli.Get("/unknown");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5026. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5027. }
  5028. }
  5029. TEST(ExceptionTest, WithExceptionHandler) {
  5030. Server svr;
  5031. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5032. std::exception_ptr ep) {
  5033. EXPECT_FALSE(ep == nullptr);
  5034. try {
  5035. std::rethrow_exception(ep);
  5036. } catch (std::exception &e) {
  5037. EXPECT_EQ("abc", std::string(e.what()));
  5038. } catch (...) {}
  5039. res.status = StatusCode::InternalServerError_500;
  5040. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5041. "text/html"); // <= Content-Length still 13 at this point
  5042. });
  5043. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5044. res.set_content("Hello World!\n", "text/plain");
  5045. throw std::runtime_error("abc");
  5046. });
  5047. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5048. auto se = detail::scope_exit([&] {
  5049. svr.stop();
  5050. thread.join();
  5051. ASSERT_FALSE(svr.is_running());
  5052. });
  5053. svr.wait_until_ready();
  5054. for (size_t i = 0; i < 10; i++) {
  5055. Client cli(HOST, PORT);
  5056. for (size_t j = 0; j < 100; j++) {
  5057. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5059. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5060. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5061. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5063. }
  5064. cli.set_keep_alive(true);
  5065. for (size_t j = 0; j < 100; j++) {
  5066. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5068. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5069. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5070. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5071. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5072. }
  5073. }
  5074. }
  5075. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5076. Server svr;
  5077. svr.set_exception_handler(
  5078. [](const Request &, Response &res, std::exception_ptr) {
  5079. res.set_content("oops", "text/plain");
  5080. });
  5081. svr.Get("/throw", [](const Request &, Response &) {
  5082. throw std::runtime_error("throw");
  5083. });
  5084. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5085. res.status = StatusCode::Created_201;
  5086. throw std::runtime_error("created-then-throw");
  5087. });
  5088. auto port = svr.bind_to_any_port(HOST);
  5089. ASSERT_GT(port, 0);
  5090. thread t = thread([&] { svr.listen_after_bind(); });
  5091. auto se = detail::scope_exit([&] {
  5092. svr.stop();
  5093. t.join();
  5094. ASSERT_FALSE(svr.is_running());
  5095. });
  5096. svr.wait_until_ready();
  5097. Client cli(HOST, port);
  5098. for (auto path : {"/throw", "/created-then-throw"}) {
  5099. auto res = cli.Get(path);
  5100. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5101. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5102. }
  5103. }
  5104. TEST(ExceptionTest, AndErrorHandler) {
  5105. Server svr;
  5106. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5107. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5108. });
  5109. svr.set_exception_handler(
  5110. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5111. EXPECT_FALSE(ep == nullptr);
  5112. try {
  5113. std::rethrow_exception(ep);
  5114. } catch (std::exception &e) {
  5115. res.set_content(e.what(), "text/html");
  5116. } catch (...) {}
  5117. res.status = StatusCode::InternalServerError_500;
  5118. });
  5119. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5120. throw std::runtime_error("EXCEPTION");
  5121. });
  5122. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5123. res.set_content("ERROR", "text/html");
  5124. res.status = StatusCode::InternalServerError_500;
  5125. });
  5126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5127. auto se = detail::scope_exit([&] {
  5128. svr.stop();
  5129. thread.join();
  5130. ASSERT_FALSE(svr.is_running());
  5131. });
  5132. svr.wait_until_ready();
  5133. Client cli(HOST, PORT);
  5134. {
  5135. auto res = cli.Get("/exception");
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5138. EXPECT_EQ("EXCEPTION", res->body);
  5139. }
  5140. {
  5141. auto res = cli.Get("/error");
  5142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5143. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5144. EXPECT_EQ("ERROR", res->body);
  5145. }
  5146. {
  5147. auto res = cli.Get("/invalid");
  5148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5150. EXPECT_EQ("NOT_FOUND", res->body);
  5151. }
  5152. }
  5153. #endif
  5154. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5155. // An exception from a user callback outside process_request()'s try/catch
  5156. // used to unwind into the task queue - which does not catch - and terminate
  5157. // the process. Each test below runs the server on a single worker thread: a
  5158. // guard that catches the exception but still loses the thread would otherwise
  5159. // be hidden by a spare worker serving the follow-up request. Note that a
  5160. // regression here aborts the whole test binary rather than failing one test.
  5161. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5162. Server svr;
  5163. svr.new_task_queue = [] { return new ThreadPool(1); };
  5164. std::atomic<int> reported{0};
  5165. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5166. if (err == Error::UserCallbackException) { reported++; }
  5167. });
  5168. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5169. res.set_content_provider(
  5170. 1024, "text/plain",
  5171. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5172. sink.write("hello", 5);
  5173. throw std::runtime_error("from the content provider");
  5174. });
  5175. });
  5176. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5177. res.set_content("ok", "text/plain");
  5178. });
  5179. auto port = svr.bind_to_any_port(HOST);
  5180. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5181. auto se = detail::scope_exit([&] {
  5182. svr.stop();
  5183. listen_thread.join();
  5184. ASSERT_FALSE(svr.is_running());
  5185. });
  5186. svr.wait_until_ready();
  5187. {
  5188. Client cli(HOST, port);
  5189. cli.set_read_timeout(5, 0);
  5190. EXPECT_FALSE(cli.Get("/throw"));
  5191. }
  5192. EXPECT_TRUE(svr.is_running());
  5193. EXPECT_EQ(1, reported.load());
  5194. // A request on a fresh connection is still served.
  5195. {
  5196. Client cli(HOST, port);
  5197. auto res = cli.Get("/ok");
  5198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. EXPECT_EQ("ok", res->body);
  5201. }
  5202. }
  5203. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5204. Server svr;
  5205. svr.new_task_queue = [] { return new ThreadPool(1); };
  5206. std::atomic<bool> should_throw{true};
  5207. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5208. res.set_content("hi", "text/plain");
  5209. });
  5210. svr.set_post_routing_handler(
  5211. [&](const Request & /*req*/, Response & /*res*/) {
  5212. if (should_throw) {
  5213. throw std::runtime_error("from the post-routing handler");
  5214. }
  5215. });
  5216. auto port = svr.bind_to_any_port(HOST);
  5217. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5218. auto se = detail::scope_exit([&] {
  5219. svr.stop();
  5220. listen_thread.join();
  5221. ASSERT_FALSE(svr.is_running());
  5222. });
  5223. svr.wait_until_ready();
  5224. {
  5225. Client cli(HOST, port);
  5226. cli.set_read_timeout(5, 0);
  5227. EXPECT_FALSE(cli.Get("/hi"));
  5228. }
  5229. EXPECT_TRUE(svr.is_running());
  5230. should_throw = false;
  5231. {
  5232. Client cli(HOST, port);
  5233. auto res = cli.Get("/hi");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. EXPECT_EQ("hi", res->body);
  5237. }
  5238. }
  5239. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5240. // The guard reports the caught exception through the error logger, which is
  5241. // a user callback too. A logger that throws has to be contained as well, or
  5242. // the process would terminate from inside the catch.
  5243. Server svr;
  5244. svr.new_task_queue = [] { return new ThreadPool(1); };
  5245. std::atomic<int> reported{0};
  5246. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5247. if (err == Error::UserCallbackException) {
  5248. reported++;
  5249. throw std::runtime_error("from the error logger");
  5250. }
  5251. });
  5252. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5253. res.set_content_provider(
  5254. 1024, "text/plain",
  5255. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5256. sink.write("hello", 5);
  5257. throw std::runtime_error("from the content provider");
  5258. });
  5259. });
  5260. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5261. res.set_content("ok", "text/plain");
  5262. });
  5263. auto port = svr.bind_to_any_port(HOST);
  5264. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5265. auto se = detail::scope_exit([&] {
  5266. svr.stop();
  5267. listen_thread.join();
  5268. ASSERT_FALSE(svr.is_running());
  5269. });
  5270. svr.wait_until_ready();
  5271. {
  5272. Client cli(HOST, port);
  5273. cli.set_read_timeout(5, 0);
  5274. EXPECT_FALSE(cli.Get("/throw"));
  5275. }
  5276. EXPECT_TRUE(svr.is_running());
  5277. EXPECT_EQ(1, reported.load());
  5278. {
  5279. Client cli(HOST, port);
  5280. auto res = cli.Get("/ok");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. EXPECT_EQ(StatusCode::OK_200, res->status);
  5283. EXPECT_EQ("ok", res->body);
  5284. }
  5285. }
  5286. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5287. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5288. // so the exception unwinds through the ws::WebSocket object on its way to
  5289. // the guard. None of the HTTP cases above cross that.
  5290. Server svr;
  5291. svr.new_task_queue = [] { return new ThreadPool(1); };
  5292. std::atomic<int> reported{0};
  5293. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5294. if (err == Error::UserCallbackException) { reported++; }
  5295. });
  5296. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5297. throw std::runtime_error("from the WebSocket handler");
  5298. });
  5299. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5300. res.set_content("ok", "text/plain");
  5301. });
  5302. auto port = svr.bind_to_any_port(HOST);
  5303. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5304. auto se = detail::scope_exit([&] {
  5305. svr.stop();
  5306. listen_thread.join();
  5307. ASSERT_FALSE(svr.is_running());
  5308. });
  5309. svr.wait_until_ready();
  5310. {
  5311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5312. "/ws");
  5313. auto res = client.connect();
  5314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5315. // The server dropped the connection instead of dying.
  5316. std::string msg;
  5317. EXPECT_FALSE(client.read(msg));
  5318. client.close();
  5319. }
  5320. EXPECT_TRUE(svr.is_running());
  5321. EXPECT_EQ(1, reported.load());
  5322. {
  5323. Client cli(HOST, port);
  5324. auto res = cli.Get("/ok");
  5325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5326. EXPECT_EQ(StatusCode::OK_200, res->status);
  5327. EXPECT_EQ("ok", res->body);
  5328. }
  5329. }
  5330. #ifdef CPPHTTPLIB_SSL_ENABLED
  5331. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5332. // SSLServer::process_and_close_socket() is a separate overload with its own
  5333. // guard, so it is exercised on its own.
  5334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5335. ASSERT_TRUE(svr.is_valid());
  5336. svr.new_task_queue = [] { return new ThreadPool(1); };
  5337. std::atomic<int> reported{0};
  5338. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5339. if (err == Error::UserCallbackException) { reported++; }
  5340. });
  5341. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5342. res.set_content_provider(
  5343. 1024, "text/plain",
  5344. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5345. sink.write("hello", 5);
  5346. throw std::runtime_error("from the content provider");
  5347. });
  5348. });
  5349. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5350. res.set_content("ok", "text/plain");
  5351. });
  5352. auto port = svr.bind_to_any_port(HOST);
  5353. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5354. auto se = detail::scope_exit([&] {
  5355. svr.stop();
  5356. listen_thread.join();
  5357. ASSERT_FALSE(svr.is_running());
  5358. });
  5359. svr.wait_until_ready();
  5360. {
  5361. SSLClient cli(HOST, port);
  5362. cli.enable_server_certificate_verification(false);
  5363. cli.set_read_timeout(5, 0);
  5364. EXPECT_FALSE(cli.Get("/throw"));
  5365. }
  5366. EXPECT_TRUE(svr.is_running());
  5367. EXPECT_EQ(1, reported.load());
  5368. {
  5369. SSLClient cli(HOST, port);
  5370. cli.enable_server_certificate_verification(false);
  5371. auto res = cli.Get("/ok");
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::OK_200, res->status);
  5374. EXPECT_EQ("ok", res->body);
  5375. }
  5376. }
  5377. #endif
  5378. #endif
  5379. TEST(NoContentTest, ContentLength) {
  5380. Server svr;
  5381. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5382. res.status = StatusCode::NoContent_204;
  5383. });
  5384. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5385. auto se = detail::scope_exit([&] {
  5386. svr.stop();
  5387. thread.join();
  5388. ASSERT_FALSE(svr.is_running());
  5389. });
  5390. svr.wait_until_ready();
  5391. {
  5392. Client cli(HOST, PORT);
  5393. auto res = cli.Get("/hi");
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5396. // RFC 9110 8.6: none in a 204 response
  5397. EXPECT_FALSE(res->has_header("Content-Length"));
  5398. }
  5399. }
  5400. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5401. Server svr;
  5402. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5403. res.set_header("Content-Length", "5");
  5404. res.set_content("hello world", "text/plain");
  5405. });
  5406. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5407. // A body that reads as the last chunk, were it taken as chunked
  5408. res.set_header("Transfer-Encoding", "chunked");
  5409. res.set_content("0\r\n\r\n", "text/plain");
  5410. });
  5411. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5412. res.set_header("Content-Length", "2");
  5413. res.set_content_provider(5, "text/plain",
  5414. [](size_t offset, size_t length, DataSink &sink) {
  5415. sink.write(&"hello"[offset], length);
  5416. return true;
  5417. });
  5418. });
  5419. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5420. res.set_header("Content-Length", "1234");
  5421. });
  5422. thread t = thread([&] { svr.listen(HOST, PORT); });
  5423. auto se = detail::scope_exit([&] {
  5424. svr.stop();
  5425. t.join();
  5426. ASSERT_FALSE(svr.is_running());
  5427. });
  5428. svr.wait_until_ready();
  5429. Client cli(HOST, PORT);
  5430. cli.set_read_timeout(1, 0);
  5431. auto expect_body = [&](const Result &res, const std::string &body) {
  5432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5433. EXPECT_EQ(body, res->body);
  5434. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5435. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5436. };
  5437. Headers identity{{"Accept-Encoding", ""}};
  5438. expect_body(cli.Get("/body", identity), "hello world");
  5439. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5440. expect_body(cli.Get("/body",
  5441. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5442. "he");
  5443. expect_body(cli.Get("/provider", identity), "hello");
  5444. expect_body(cli.Get("/empty", identity), "");
  5445. // A HEAD response may give the length of the body a GET would get.
  5446. auto res = cli.Head("/empty");
  5447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5448. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5449. }
  5450. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5451. Server svr;
  5452. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5453. res.set_content("short", "text/plain");
  5454. });
  5455. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5456. res.body += " with a footer";
  5457. res.set_header("Transfer-Encoding", "chunked");
  5458. });
  5459. thread t = thread([&] { svr.listen(HOST, PORT); });
  5460. auto se = detail::scope_exit([&] {
  5461. svr.stop();
  5462. t.join();
  5463. ASSERT_FALSE(svr.is_running());
  5464. });
  5465. svr.wait_until_ready();
  5466. Client cli(HOST, PORT);
  5467. cli.set_read_timeout(1, 0);
  5468. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5470. EXPECT_EQ("short with a footer", res->body);
  5471. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5472. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5473. }
  5474. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5475. Server svr;
  5476. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5477. res.set_header("Content-Length", "3");
  5478. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5479. sink.write("abc", 3);
  5480. sink.done();
  5481. return true;
  5482. });
  5483. });
  5484. thread t = thread([&] { svr.listen(HOST, PORT); });
  5485. auto se = detail::scope_exit([&] {
  5486. svr.stop();
  5487. t.join();
  5488. ASSERT_FALSE(svr.is_running());
  5489. });
  5490. svr.wait_until_ready();
  5491. Client cli(HOST, PORT);
  5492. cli.set_keep_alive(true);
  5493. auto res = cli.Get("/");
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. EXPECT_EQ("abc", res->body);
  5496. EXPECT_FALSE(res->has_header("Content-Length"));
  5497. EXPECT_EQ("close", res->get_header_value("Connection"));
  5498. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5499. // No body to delimit
  5500. auto head = cli.Head("/");
  5501. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5502. EXPECT_FALSE(head->has_header("Connection"));
  5503. }
  5504. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5505. #ifdef CPPHTTPLIB_SSL_ENABLED
  5506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5507. ASSERT_TRUE(svr.is_valid());
  5508. #else
  5509. Server svr;
  5510. #endif
  5511. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5512. if (req.path == "/routing_handler") {
  5513. res.set_header("PRE_ROUTING", "on");
  5514. res.set_content("Routing Handler", "text/plain");
  5515. return httplib::Server::HandlerResponse::Handled;
  5516. }
  5517. return httplib::Server::HandlerResponse::Unhandled;
  5518. });
  5519. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5520. res.set_content("Error", "text/html");
  5521. });
  5522. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5523. if (req.path == "/routing_handler") {
  5524. res.set_header("POST_ROUTING", "on");
  5525. }
  5526. });
  5527. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5528. res.set_content("Hello World!\n", "text/plain");
  5529. });
  5530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5531. auto se = detail::scope_exit([&] {
  5532. svr.stop();
  5533. thread.join();
  5534. ASSERT_FALSE(svr.is_running());
  5535. });
  5536. svr.wait_until_ready();
  5537. {
  5538. #ifdef CPPHTTPLIB_SSL_ENABLED
  5539. SSLClient cli(HOST, PORT);
  5540. cli.enable_server_certificate_verification(false);
  5541. #else
  5542. Client cli(HOST, PORT);
  5543. #endif
  5544. auto res = cli.Get("/routing_handler");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. EXPECT_EQ("Routing Handler", res->body);
  5548. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5549. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5550. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5551. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5552. }
  5553. {
  5554. #ifdef CPPHTTPLIB_SSL_ENABLED
  5555. SSLClient cli(HOST, PORT);
  5556. cli.enable_server_certificate_verification(false);
  5557. #else
  5558. Client cli(HOST, PORT);
  5559. #endif
  5560. auto res = cli.Get("/hi");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ("Hello World!\n", res->body);
  5564. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5565. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5566. }
  5567. {
  5568. #ifdef CPPHTTPLIB_SSL_ENABLED
  5569. SSLClient cli(HOST, PORT);
  5570. cli.enable_server_certificate_verification(false);
  5571. #else
  5572. Client cli(HOST, PORT);
  5573. #endif
  5574. auto res = cli.Get("/aaa");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5577. EXPECT_EQ("Error", res->body);
  5578. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5579. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5580. }
  5581. }
  5582. TEST(RequestHandlerTest, PreRequestHandler) {
  5583. auto route_path = "/user/:user";
  5584. Server svr;
  5585. svr.Get("/hi", [](const Request &, Response &res) {
  5586. res.set_content("hi", "text/plain");
  5587. });
  5588. svr.Get(route_path, [](const Request &req, Response &res) {
  5589. res.set_content(req.path_params.at("user"), "text/plain");
  5590. });
  5591. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5592. if (req.matched_route == route_path) {
  5593. auto user = req.path_params.at("user");
  5594. if (user != "john") {
  5595. res.status = StatusCode::Forbidden_403;
  5596. res.set_content("error", "text/html");
  5597. return Server::HandlerResponse::Handled;
  5598. }
  5599. }
  5600. return Server::HandlerResponse::Unhandled;
  5601. });
  5602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5603. auto se = detail::scope_exit([&] {
  5604. svr.stop();
  5605. thread.join();
  5606. ASSERT_FALSE(svr.is_running());
  5607. });
  5608. svr.wait_until_ready();
  5609. Client cli(HOST, PORT);
  5610. {
  5611. auto res = cli.Get("/hi");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::OK_200, res->status);
  5614. EXPECT_EQ("hi", res->body);
  5615. }
  5616. {
  5617. auto res = cli.Get("/user/john");
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. EXPECT_EQ("john", res->body);
  5621. }
  5622. {
  5623. auto res = cli.Get("/user/invalid-user");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5626. EXPECT_EQ("error", res->body);
  5627. }
  5628. }
  5629. // The pre-request handler must run before the request body is read, so a
  5630. // rejected request never forces the server to buffer a (potentially large)
  5631. // body. Here the posted body is larger than the payload limit: if the body
  5632. // were read first the server would answer 413, but because the pre-request
  5633. // handler runs first it answers 403 and the body is never read.
  5634. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5635. Server svr;
  5636. svr.set_payload_max_length(8);
  5637. auto handler_ran = false;
  5638. svr.Post("/reject", [&](const Request &req, Response &res) {
  5639. handler_ran = true;
  5640. res.set_content(req.body, "text/plain");
  5641. });
  5642. svr.Post("/accept", [](const Request &req, Response &res) {
  5643. res.set_content(req.body, "text/plain");
  5644. });
  5645. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5646. if (req.matched_route == "/reject") {
  5647. res.status = StatusCode::Forbidden_403;
  5648. res.set_content("denied", "text/plain");
  5649. return Server::HandlerResponse::Handled;
  5650. }
  5651. return Server::HandlerResponse::Unhandled;
  5652. });
  5653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5654. auto se = detail::scope_exit([&] {
  5655. svr.stop();
  5656. thread.join();
  5657. ASSERT_FALSE(svr.is_running());
  5658. });
  5659. svr.wait_until_ready();
  5660. Client cli(HOST, PORT);
  5661. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5662. // rejects with 403 before the body is read, so 413 is never reached.
  5663. {
  5664. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5667. EXPECT_EQ("denied", res->body);
  5668. EXPECT_FALSE(handler_ran);
  5669. }
  5670. // An approved route still reads the body and enforces the payload limit.
  5671. {
  5672. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5675. }
  5676. }
  5677. TEST(UserDataTest, BasicOperations) {
  5678. httplib::UserData ud;
  5679. // Initially empty
  5680. EXPECT_FALSE(ud.has("key"));
  5681. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5682. // set and get
  5683. ud.set("key", 42);
  5684. EXPECT_TRUE(ud.has("key"));
  5685. auto *p = ud.get<int>("key");
  5686. ASSERT_NE(nullptr, p);
  5687. EXPECT_EQ(42, *p);
  5688. // Type mismatch → nullptr
  5689. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5690. // Overwrite with different type
  5691. ud.set("key", std::string("hello"));
  5692. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5693. auto *s = ud.get<std::string>("key");
  5694. ASSERT_NE(nullptr, s);
  5695. EXPECT_EQ("hello", *s);
  5696. // erase
  5697. ud.erase("key");
  5698. EXPECT_FALSE(ud.has("key"));
  5699. // clear
  5700. ud.set("a", 1);
  5701. ud.set("b", 2);
  5702. ud.clear();
  5703. EXPECT_FALSE(ud.has("a"));
  5704. EXPECT_FALSE(ud.has("b"));
  5705. }
  5706. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5707. struct AuthCtx {
  5708. std::string user_id;
  5709. };
  5710. Server svr;
  5711. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5712. res.user_data.set("auth", AuthCtx{"alice"});
  5713. return Server::HandlerResponse::Unhandled;
  5714. });
  5715. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5716. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5717. ASSERT_NE(nullptr, ctx);
  5718. res.set_content("Hello " + ctx->user_id, "text/plain");
  5719. });
  5720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5721. auto se = detail::scope_exit([&] {
  5722. svr.stop();
  5723. thread.join();
  5724. ASSERT_FALSE(svr.is_running());
  5725. });
  5726. svr.wait_until_ready();
  5727. Client cli(HOST, PORT);
  5728. auto res = cli.Get("/me");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. EXPECT_EQ("Hello alice", res->body);
  5732. }
  5733. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5734. struct RoleCtx {
  5735. std::string role;
  5736. };
  5737. Server svr;
  5738. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5739. res.user_data.set("role", RoleCtx{"admin"});
  5740. return Server::HandlerResponse::Unhandled;
  5741. });
  5742. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5743. auto *ctx = res.user_data.get<RoleCtx>("role");
  5744. ASSERT_NE(nullptr, ctx);
  5745. res.set_content(ctx->role, "text/plain");
  5746. });
  5747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5748. auto se = detail::scope_exit([&] {
  5749. svr.stop();
  5750. thread.join();
  5751. ASSERT_FALSE(svr.is_running());
  5752. });
  5753. svr.wait_until_ready();
  5754. Client cli(HOST, PORT);
  5755. auto res = cli.Get("/role");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. EXPECT_EQ("admin", res->body);
  5759. }
  5760. TEST(InvalidFormatTest, StatusCode) {
  5761. Server svr;
  5762. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5763. res.set_content("Hello World!\n", "text/plain");
  5764. res.status = 9999; // Status should be a three-digit code...
  5765. });
  5766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5767. auto se = detail::scope_exit([&] {
  5768. svr.stop();
  5769. thread.join();
  5770. ASSERT_FALSE(svr.is_running());
  5771. });
  5772. svr.wait_until_ready();
  5773. {
  5774. Client cli(HOST, PORT);
  5775. auto res = cli.Get("/hi");
  5776. ASSERT_FALSE(res);
  5777. }
  5778. }
  5779. TEST(URLFragmentTest, WithFragment) {
  5780. Server svr;
  5781. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5782. EXPECT_TRUE(req.target == "/hi");
  5783. });
  5784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5785. auto se = detail::scope_exit([&] {
  5786. svr.stop();
  5787. thread.join();
  5788. ASSERT_FALSE(svr.is_running());
  5789. });
  5790. svr.wait_until_ready();
  5791. {
  5792. Client cli(HOST, PORT);
  5793. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5794. EXPECT_TRUE(res);
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. res = cli.Get("/hi%23key1=val1=key2=val2");
  5797. EXPECT_TRUE(res);
  5798. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5799. }
  5800. }
  5801. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5802. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5803. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5804. Server svr;
  5805. std::vector<std::string> targets;
  5806. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5807. targets.push_back(req.target);
  5808. });
  5809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5810. auto se = detail::scope_exit([&] {
  5811. svr.stop();
  5812. thread.join();
  5813. ASSERT_FALSE(svr.is_running());
  5814. });
  5815. svr.wait_until_ready();
  5816. Client cli(HOST, PORT);
  5817. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5818. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5819. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5820. // A '?' after the '#' belongs to the fragment, not to the query.
  5821. Request req;
  5822. req.method = "GET";
  5823. req.path = "/hi#f?x=1";
  5824. req.params.emplace("a", "1");
  5825. Response res;
  5826. auto error = Error::Success;
  5827. EXPECT_TRUE(cli.send(req, res, error));
  5828. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5829. "/hi?a=1"}),
  5830. targets);
  5831. }
  5832. TEST(HeaderWriter, SetHeaderWriter) {
  5833. Server svr;
  5834. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5835. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5836. return detail::write_headers(strm, hdrs);
  5837. });
  5838. svr.Get("/hi", [](const Request &req, Response &res) {
  5839. auto it = req.headers.find("CustomClientHeader");
  5840. EXPECT_TRUE(it != req.headers.end());
  5841. EXPECT_EQ(it->second, "CustomClientValue");
  5842. res.set_content("Hello World!\n", "text/plain");
  5843. });
  5844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5845. auto se = detail::scope_exit([&] {
  5846. svr.stop();
  5847. thread.join();
  5848. ASSERT_FALSE(svr.is_running());
  5849. });
  5850. svr.wait_until_ready();
  5851. {
  5852. Client cli(HOST, PORT);
  5853. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5854. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5855. return detail::write_headers(strm, hdrs);
  5856. });
  5857. auto res = cli.Get("/hi");
  5858. EXPECT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. auto it = res->headers.find("CustomServerHeader");
  5861. EXPECT_TRUE(it != res->headers.end());
  5862. EXPECT_EQ(it->second, "CustomServerValue");
  5863. }
  5864. }
  5865. class ServerTest : public ::testing::Test {
  5866. protected:
  5867. ServerTest()
  5868. : cli_(HOST, PORT)
  5869. #ifdef CPPHTTPLIB_SSL_ENABLED
  5870. ,
  5871. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5872. #endif
  5873. {
  5874. #ifdef CPPHTTPLIB_SSL_ENABLED
  5875. cli_.enable_server_certificate_verification(false);
  5876. #endif
  5877. // Allow LARGE_DATA (100MB) responses
  5878. cli_.set_payload_max_length(200 * 1024 * 1024);
  5879. }
  5880. virtual void SetUp() {
  5881. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5882. svr_.set_payload_max_length(200 * 1024 * 1024);
  5883. svr_.set_mount_point("/", "./www");
  5884. svr_.set_mount_point("/mount", "./www2");
  5885. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5886. svr_.Get("/hi",
  5887. [&](const Request & /*req*/, Response &res) {
  5888. res.set_content("Hello World!", "text/plain");
  5889. })
  5890. .Get("/file_content",
  5891. [&](const Request & /*req*/, Response &res) {
  5892. res.set_file_content("./www/dir/test.html");
  5893. })
  5894. .Get("/file_content_with_content_type",
  5895. [&](const Request & /*req*/, Response &res) {
  5896. res.set_file_content("./www/file", "text/plain");
  5897. })
  5898. .Get("/invalid_file_content",
  5899. [&](const Request & /*req*/, Response &res) {
  5900. res.set_file_content("./www/dir/invalid_file_path");
  5901. })
  5902. .Get("/http_response_splitting",
  5903. [&](const Request & /*req*/, Response &res) {
  5904. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5905. EXPECT_EQ(0U, res.headers.size());
  5906. EXPECT_FALSE(res.has_header("a"));
  5907. res.set_header("a", "1\nSet-Cookie: a=1");
  5908. EXPECT_EQ(0U, res.headers.size());
  5909. EXPECT_FALSE(res.has_header("a"));
  5910. res.set_header("a", "1\rSet-Cookie: a=1");
  5911. EXPECT_EQ(0U, res.headers.size());
  5912. EXPECT_FALSE(res.has_header("a"));
  5913. res.set_header("a\r\nb", "0");
  5914. EXPECT_EQ(0U, res.headers.size());
  5915. EXPECT_FALSE(res.has_header("a"));
  5916. res.set_header("a\rb", "0");
  5917. EXPECT_EQ(0U, res.headers.size());
  5918. EXPECT_FALSE(res.has_header("a"));
  5919. res.set_header("a\nb", "0");
  5920. EXPECT_EQ(0U, res.headers.size());
  5921. EXPECT_FALSE(res.has_header("a"));
  5922. res.set_redirect("1\r\nSet-Cookie: a=1");
  5923. EXPECT_EQ(0U, res.headers.size());
  5924. EXPECT_FALSE(res.has_header("Location"));
  5925. })
  5926. .Get("/slow",
  5927. [&](const Request & /*req*/, Response &res) {
  5928. std::this_thread::sleep_for(std::chrono::seconds(4));
  5929. res.set_content("slow", "text/plain");
  5930. })
  5931. #if 0
  5932. .Post("/slowpost",
  5933. [&](const Request & /*req*/, Response &res) {
  5934. std::this_thread::sleep_for(std::chrono::seconds(2));
  5935. res.set_content("slow", "text/plain");
  5936. })
  5937. #endif
  5938. .Get("/remote_addr",
  5939. [&](const Request &req, Response &res) {
  5940. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5941. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5942. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5943. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5944. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5945. #endif
  5946. res.set_content(req.remote_addr, "text/plain");
  5947. })
  5948. .Get("/local_addr",
  5949. [&](const Request &req, Response &res) {
  5950. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5951. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5952. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5953. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5954. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5955. #endif
  5956. auto local_addr = req.local_addr;
  5957. auto local_port = std::to_string(req.local_port);
  5958. res.set_content(local_addr.append(":").append(local_port),
  5959. "text/plain");
  5960. })
  5961. .Get("/endwith%",
  5962. [&](const Request & /*req*/, Response &res) {
  5963. res.set_content("Hello World!", "text/plain");
  5964. })
  5965. .Get("/a\\+\\+b",
  5966. [&](const Request &req, Response &res) {
  5967. ASSERT_TRUE(req.has_param("a +b"));
  5968. auto val = req.get_param_value("a +b");
  5969. res.set_content(val, "text/plain");
  5970. })
  5971. .Get("/", [&](const Request & /*req*/,
  5972. Response &res) { res.set_redirect("/hi"); })
  5973. .Post("/1",
  5974. [](const Request & /*req*/, Response &res) {
  5975. res.set_redirect("/2", StatusCode::SeeOther_303);
  5976. })
  5977. .Get("/2",
  5978. [](const Request & /*req*/, Response &res) {
  5979. res.set_content("redirected.", "text/plain");
  5980. res.status = StatusCode::OK_200;
  5981. })
  5982. .Post("/person",
  5983. [&](const Request &req, Response &res) {
  5984. if (req.has_param("name") && req.has_param("note")) {
  5985. persons_[req.get_param_value("name")] =
  5986. req.get_param_value("note");
  5987. } else {
  5988. res.status = StatusCode::BadRequest_400;
  5989. }
  5990. })
  5991. .Put("/person",
  5992. [&](const Request &req, Response &res) {
  5993. if (req.has_param("name") && req.has_param("note")) {
  5994. persons_[req.get_param_value("name")] =
  5995. req.get_param_value("note");
  5996. } else {
  5997. res.status = StatusCode::BadRequest_400;
  5998. }
  5999. })
  6000. .Get("/person/(.*)",
  6001. [&](const Request &req, Response &res) {
  6002. string name = req.matches[1];
  6003. if (persons_.find(name) != persons_.end()) {
  6004. auto note = persons_[name];
  6005. res.set_content(note, "text/plain");
  6006. } else {
  6007. res.status = StatusCode::NotFound_404;
  6008. }
  6009. })
  6010. .Delete("/person",
  6011. [&](const Request &req, Response &res) {
  6012. if (req.has_param("name")) {
  6013. string name = req.get_param_value("name");
  6014. if (persons_.find(name) != persons_.end()) {
  6015. persons_.erase(name);
  6016. res.set_content("DELETED", "text/plain");
  6017. } else {
  6018. res.status = StatusCode::NotFound_404;
  6019. }
  6020. } else {
  6021. res.status = StatusCode::BadRequest_400;
  6022. }
  6023. })
  6024. .Post("/x-www-form-urlencoded-json",
  6025. [&](const Request &req, Response &res) {
  6026. auto json = req.get_param_value("json");
  6027. ASSERT_EQ(JSON_DATA, json);
  6028. res.set_content(json, "appliation/json");
  6029. res.status = StatusCode::OK_200;
  6030. })
  6031. .Get("/streamed-chunked",
  6032. [&](const Request & /*req*/, Response &res) {
  6033. res.set_chunked_content_provider(
  6034. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6035. sink.os << "123";
  6036. sink.os << "456";
  6037. sink.os << "789";
  6038. sink.done();
  6039. return true;
  6040. });
  6041. })
  6042. .Get("/streamed-chunked-with-prohibited-trailer",
  6043. [&](const Request & /*req*/, Response &res) {
  6044. auto i = new int(0);
  6045. // Declare both a prohibited trailer (Content-Length) and an
  6046. // allowed one
  6047. res.set_header("Trailer", "Content-Length, X-Allowed");
  6048. res.set_chunked_content_provider(
  6049. "text/plain",
  6050. [i](size_t /*offset*/, DataSink &sink) {
  6051. switch (*i) {
  6052. case 0: sink.os << "123"; break;
  6053. case 1: sink.os << "456"; break;
  6054. case 2: sink.os << "789"; break;
  6055. case 3: {
  6056. sink.done_with_trailer(
  6057. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6058. } break;
  6059. }
  6060. (*i)++;
  6061. return true;
  6062. },
  6063. [i](bool success) {
  6064. EXPECT_TRUE(success);
  6065. delete i;
  6066. });
  6067. })
  6068. .Get("/streamed-chunked2",
  6069. [&](const Request & /*req*/, Response &res) {
  6070. auto i = new int(0);
  6071. res.set_chunked_content_provider(
  6072. "text/plain",
  6073. [i](size_t /*offset*/, DataSink &sink) {
  6074. switch (*i) {
  6075. case 0: sink.os << "123"; break;
  6076. case 1: sink.os << "456"; break;
  6077. case 2: sink.os << "789"; break;
  6078. case 3: sink.done(); break;
  6079. }
  6080. (*i)++;
  6081. return true;
  6082. },
  6083. [i](bool success) {
  6084. EXPECT_TRUE(success);
  6085. delete i;
  6086. });
  6087. })
  6088. .Get("/streamed-chunked-with-trailer",
  6089. [&](const Request & /*req*/, Response &res) {
  6090. auto i = new int(0);
  6091. res.set_header("Trailer", "Dummy1, Dummy2");
  6092. res.set_chunked_content_provider(
  6093. "text/plain",
  6094. [i](size_t /*offset*/, DataSink &sink) {
  6095. switch (*i) {
  6096. case 0: sink.os << "123"; break;
  6097. case 1: sink.os << "456"; break;
  6098. case 2: sink.os << "789"; break;
  6099. case 3: {
  6100. sink.done_with_trailer(
  6101. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6102. } break;
  6103. }
  6104. (*i)++;
  6105. return true;
  6106. },
  6107. [i](bool success) {
  6108. EXPECT_TRUE(success);
  6109. delete i;
  6110. });
  6111. })
  6112. .Get("/streamed",
  6113. [&](const Request & /*req*/, Response &res) {
  6114. res.set_content_provider(
  6115. 6, "text/plain",
  6116. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6117. sink.os << (offset < 3 ? "a" : "b");
  6118. return true;
  6119. });
  6120. })
  6121. .Get("/streamed-without-length",
  6122. [&](const Request & /*req*/, Response &res) {
  6123. auto data = new std::string("abcdefg");
  6124. res.set_content_provider(
  6125. "text/plain",
  6126. [data](size_t offset, DataSink &sink) {
  6127. if (offset < data->size()) {
  6128. sink.os << data->substr(offset);
  6129. }
  6130. sink.done();
  6131. return true;
  6132. },
  6133. [data](bool success) {
  6134. EXPECT_TRUE(success);
  6135. delete data;
  6136. });
  6137. })
  6138. .Get("/streamed-with-range",
  6139. [&](const Request &req, Response &res) {
  6140. auto data = new std::string("abcdefg");
  6141. // An explicit status keeps the server from picking the 206 it
  6142. // would otherwise choose for a ranged request, so the response
  6143. // is not a partial representation.
  6144. auto status = req.get_param_value("status");
  6145. if (status == "200") {
  6146. res.status = StatusCode::OK_200;
  6147. } else if (status == "403") {
  6148. res.status = StatusCode::Forbidden_403;
  6149. }
  6150. res.set_content_provider(
  6151. data->size(), "text/plain",
  6152. [data](size_t offset, size_t length, DataSink &sink) {
  6153. size_t DATA_CHUNK_SIZE = 4;
  6154. const auto &d = *data;
  6155. auto out_len =
  6156. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6157. auto ret =
  6158. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6159. EXPECT_TRUE(ret);
  6160. return true;
  6161. },
  6162. [data, &req](bool success) {
  6163. EXPECT_EQ(success, !req.has_param("error"));
  6164. delete data;
  6165. });
  6166. })
  6167. .Get("/streamed-cancel",
  6168. [&](const Request & /*req*/, Response &res) {
  6169. res.set_content_provider(
  6170. size_t(-1), "text/plain",
  6171. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6172. sink.os << "data_chunk";
  6173. return true;
  6174. });
  6175. })
  6176. .Get("/regex-with-delimiter",
  6177. [&](const Request &req, Response & /*res*/) {
  6178. ASSERT_TRUE(req.has_param("key"));
  6179. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6180. })
  6181. .Get("/with-range",
  6182. [&](const Request & /*req*/, Response &res) {
  6183. res.set_content("abcdefg", "text/plain");
  6184. })
  6185. .Get("/test-start-time",
  6186. [&](const Request &req, Response & /*res*/) {
  6187. EXPECT_NE(req.start_time_,
  6188. std::chrono::steady_clock::time_point::min());
  6189. })
  6190. .Get("/with-range-customized-response",
  6191. [&](const Request & /*req*/, Response &res) {
  6192. res.status = StatusCode::BadRequest_400;
  6193. res.set_content(JSON_DATA, "application/json");
  6194. })
  6195. .Post("/chunked",
  6196. [&](const Request &req, Response & /*res*/) {
  6197. EXPECT_EQ(req.body, "dechunked post body");
  6198. })
  6199. .Post("/large-chunked",
  6200. [&](const Request &req, Response & /*res*/) {
  6201. std::string expected(6 * 30 * 1024u, 'a');
  6202. EXPECT_EQ(req.body, expected);
  6203. })
  6204. .Post("/multipart",
  6205. [&](const Request &req, Response & /*res*/) {
  6206. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6207. req.form.get_field_count("text2") +
  6208. req.form.get_field_count("file3") +
  6209. req.form.get_field_count("file4"));
  6210. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6211. req.form.get_file_count("file2"));
  6212. ASSERT_TRUE(!req.form.has_file("???"));
  6213. ASSERT_TRUE(!req.form.has_field("???"));
  6214. ASSERT_TRUE(req.body.empty());
  6215. {
  6216. const auto &text = req.form.get_field("text1");
  6217. EXPECT_EQ("text default", text);
  6218. }
  6219. {
  6220. const auto &text = req.form.get_field("text2");
  6221. EXPECT_EQ("aωb", text);
  6222. }
  6223. {
  6224. const auto &file = req.form.get_file("file1");
  6225. EXPECT_EQ("hello.txt", file.filename);
  6226. EXPECT_EQ("text/plain", file.content_type);
  6227. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6228. }
  6229. {
  6230. const auto &file = req.form.get_file("file2");
  6231. EXPECT_EQ("world.json", file.filename);
  6232. EXPECT_EQ("application/json", file.content_type);
  6233. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6234. }
  6235. {
  6236. const auto &text = req.form.get_field("file3");
  6237. EXPECT_EQ(0u, text.size());
  6238. }
  6239. {
  6240. const auto &text = req.form.get_field("file4");
  6241. EXPECT_EQ(0u, text.size());
  6242. }
  6243. })
  6244. .Post("/multipart/multi_file_values",
  6245. [&](const Request &req, Response & /*res*/) {
  6246. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6247. req.form.get_field_count("multi_text1"));
  6248. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6249. ASSERT_TRUE(!req.form.has_file("???"));
  6250. ASSERT_TRUE(!req.form.has_field("???"));
  6251. ASSERT_TRUE(req.body.empty());
  6252. {
  6253. const auto &text = req.form.get_field("text");
  6254. EXPECT_EQ("default text", text);
  6255. }
  6256. {
  6257. const auto &text1_values = req.form.get_fields("multi_text1");
  6258. EXPECT_EQ(2u, text1_values.size());
  6259. EXPECT_EQ("aaaaa", text1_values[0]);
  6260. EXPECT_EQ("bbbbb", text1_values[1]);
  6261. }
  6262. {
  6263. const auto &file1_values = req.form.get_files("multi_file1");
  6264. EXPECT_EQ(2u, file1_values.size());
  6265. auto file1 = file1_values[0];
  6266. EXPECT_EQ(file1.filename, "hello.txt");
  6267. EXPECT_EQ(file1.content_type, "text/plain");
  6268. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6269. auto file2 = file1_values[1];
  6270. EXPECT_EQ(file2.filename, "world.json");
  6271. EXPECT_EQ(file2.content_type, "application/json");
  6272. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6273. }
  6274. })
  6275. .Post("/empty",
  6276. [&](const Request &req, Response &res) {
  6277. EXPECT_EQ(req.body, "");
  6278. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6279. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6280. res.set_content("empty", "text/plain");
  6281. })
  6282. .Post("/empty-no-content-type",
  6283. [&](const Request &req, Response &res) {
  6284. EXPECT_EQ(req.body, "");
  6285. EXPECT_FALSE(req.has_header("Content-Type"));
  6286. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6287. res.set_content("empty-no-content-type", "text/plain");
  6288. })
  6289. .Post("/path-only",
  6290. [&](const Request &req, Response &res) {
  6291. EXPECT_EQ(req.body, "");
  6292. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6293. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6294. res.set_content("path-only", "text/plain");
  6295. })
  6296. .Post("/path-headers-only",
  6297. [&](const Request &req, Response &res) {
  6298. EXPECT_EQ(req.body, "");
  6299. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6300. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6301. EXPECT_EQ("world", req.get_header_value("hello"));
  6302. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6303. res.set_content("path-headers-only", "text/plain");
  6304. })
  6305. .Post("/post-large",
  6306. [&](const Request &req, Response &res) {
  6307. EXPECT_EQ(req.body, LARGE_DATA);
  6308. res.set_content(req.body, "text/plain");
  6309. })
  6310. .Post("/post-loopback",
  6311. [&](const Request &, Response &res,
  6312. ContentReader const &content_reader) {
  6313. std::string body;
  6314. content_reader([&](const char *data, size_t data_length) {
  6315. body.append(data, data_length);
  6316. return true;
  6317. });
  6318. res.set_content(body, "text/plain");
  6319. })
  6320. .Put("/put-loopback",
  6321. [&](const Request &, Response &res,
  6322. ContentReader const &content_reader) {
  6323. std::string body;
  6324. content_reader([&](const char *data, size_t data_length) {
  6325. body.append(data, data_length);
  6326. return true;
  6327. });
  6328. res.set_content(body, "text/plain");
  6329. })
  6330. .Patch("/patch-loopback",
  6331. [&](const Request &, Response &res,
  6332. ContentReader const &content_reader) {
  6333. std::string body;
  6334. content_reader([&](const char *data, size_t data_length) {
  6335. body.append(data, data_length);
  6336. return true;
  6337. });
  6338. res.set_content(body, "text/plain");
  6339. })
  6340. .Put("/empty-no-content-type",
  6341. [&](const Request &req, Response &res) {
  6342. EXPECT_EQ(req.body, "");
  6343. EXPECT_FALSE(req.has_header("Content-Type"));
  6344. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6345. res.set_content("empty-no-content-type", "text/plain");
  6346. })
  6347. .Put("/put",
  6348. [&](const Request &req, Response &res) {
  6349. EXPECT_EQ(req.body, "PUT");
  6350. res.set_content(req.body, "text/plain");
  6351. })
  6352. .Put("/put-large",
  6353. [&](const Request &req, Response &res) {
  6354. EXPECT_EQ(req.body, LARGE_DATA);
  6355. res.set_content(req.body, "text/plain");
  6356. })
  6357. .Patch("/patch",
  6358. [&](const Request &req, Response &res) {
  6359. EXPECT_EQ(req.body, "PATCH");
  6360. res.set_content(req.body, "text/plain");
  6361. })
  6362. .Delete("/delete",
  6363. [&](const Request & /*req*/, Response &res) {
  6364. res.set_content("DELETE", "text/plain");
  6365. })
  6366. .Delete("/delete-body",
  6367. [&](const Request &req, Response &res) {
  6368. EXPECT_EQ(req.body, "content");
  6369. res.set_content(req.body, "text/plain");
  6370. })
  6371. .Options(R"(\*)",
  6372. [&](const Request & /*req*/, Response &res) {
  6373. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6374. })
  6375. .CustomRoute("PROPFIND", "/dav/:id",
  6376. [&](const Request &req, Response &res) {
  6377. res.set_header("x-body-size",
  6378. std::to_string(req.body.size()));
  6379. res.set_header("x-matched-route", req.matched_route);
  6380. res.set_header("x-dav-id", req.path_params.at("id"));
  6381. res.status = StatusCode::MultiStatus_207;
  6382. res.set_content(req.body, "application/xml");
  6383. })
  6384. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6385. [&](const Request &req, Response &res) {
  6386. res.set_header("x-dav-match", req.matches[1]);
  6387. res.status = StatusCode::MultiStatus_207;
  6388. })
  6389. .CustomRoute("MKCOL", "/dav-mkcol",
  6390. [&](const Request &req, Response &res) {
  6391. EXPECT_TRUE(req.body.empty());
  6392. res.status = StatusCode::Created_201;
  6393. })
  6394. .CustomRoute(
  6395. "REPORT", "/dav-report",
  6396. [&](const Request & /*req*/, Response &res,
  6397. const ContentReader &content_reader) {
  6398. std::string body;
  6399. content_reader([&](const char *data, size_t data_length) {
  6400. body.append(data, data_length);
  6401. return true;
  6402. });
  6403. res.set_header("x-body-size", std::to_string(body.size()));
  6404. res.status = StatusCode::MultiStatus_207;
  6405. res.set_content(body, "application/xml");
  6406. })
  6407. .Get("/request-target",
  6408. [&](const Request &req, Response & /*res*/) {
  6409. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6410. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6411. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6412. })
  6413. .Get("/long-query-value",
  6414. [&](const Request &req, Response & /*res*/) {
  6415. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6416. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6417. })
  6418. .Get("/too-long-query-value",
  6419. [&](const Request &req, Response & /*res*/) {
  6420. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6421. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6422. })
  6423. .Get("/array-param",
  6424. [&](const Request &req, Response & /*res*/) {
  6425. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6426. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6427. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6428. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6429. })
  6430. .Get("/array-param-values",
  6431. [&](const Request &req, Response & /*res*/) {
  6432. auto values = req.get_param_values("array");
  6433. EXPECT_EQ(3u, values.size());
  6434. EXPECT_EQ("value1", values[0]);
  6435. EXPECT_EQ("value2", values[1]);
  6436. EXPECT_EQ("value3", values[2]);
  6437. auto empty = req.get_param_values("nonexistent");
  6438. EXPECT_TRUE(empty.empty());
  6439. })
  6440. .Post("/validate-no-multiple-headers",
  6441. [&](const Request &req, Response & /*res*/) {
  6442. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6443. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6444. })
  6445. .Post("/content_receiver",
  6446. [&](const Request &req, Response &res,
  6447. const ContentReader &content_reader) {
  6448. if (req.is_multipart_form_data()) {
  6449. std::vector<FormData> items;
  6450. content_reader(
  6451. [&](const FormData &file) {
  6452. items.push_back(file);
  6453. return true;
  6454. },
  6455. [&](const char *data, size_t data_length) {
  6456. items.back().content.append(data, data_length);
  6457. return true;
  6458. });
  6459. EXPECT_EQ(5u, items.size());
  6460. {
  6461. const auto &file = get_file_value(items, "text1");
  6462. EXPECT_TRUE(file.filename.empty());
  6463. EXPECT_EQ("text default", file.content);
  6464. }
  6465. {
  6466. const auto &file = get_file_value(items, "text2");
  6467. EXPECT_TRUE(file.filename.empty());
  6468. EXPECT_EQ("aωb", file.content);
  6469. }
  6470. {
  6471. const auto &file = get_file_value(items, "file1");
  6472. EXPECT_EQ("hello.txt", file.filename);
  6473. EXPECT_EQ("text/plain", file.content_type);
  6474. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6475. }
  6476. {
  6477. const auto &file = get_file_value(items, "file2");
  6478. EXPECT_EQ("world.json", file.filename);
  6479. EXPECT_EQ("application/json", file.content_type);
  6480. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6481. }
  6482. {
  6483. const auto &file = get_file_value(items, "file3");
  6484. EXPECT_TRUE(file.filename.empty());
  6485. EXPECT_EQ("application/octet-stream", file.content_type);
  6486. EXPECT_EQ(0u, file.content.size());
  6487. }
  6488. } else {
  6489. std::string body;
  6490. content_reader([&](const char *data, size_t data_length) {
  6491. EXPECT_EQ(7U, data_length);
  6492. body.append(data, data_length);
  6493. return true;
  6494. });
  6495. EXPECT_EQ(body, "content");
  6496. res.set_content(body, "text/plain");
  6497. }
  6498. })
  6499. .Put("/content_receiver",
  6500. [&](const Request & /*req*/, Response &res,
  6501. const ContentReader &content_reader) {
  6502. std::string body;
  6503. content_reader([&](const char *data, size_t data_length) {
  6504. body.append(data, data_length);
  6505. return true;
  6506. });
  6507. EXPECT_EQ(body, "content");
  6508. res.set_content(body, "text/plain");
  6509. })
  6510. .Patch("/content_receiver",
  6511. [&](const Request & /*req*/, Response &res,
  6512. const ContentReader &content_reader) {
  6513. std::string body;
  6514. content_reader([&](const char *data, size_t data_length) {
  6515. body.append(data, data_length);
  6516. return true;
  6517. });
  6518. EXPECT_EQ(body, "content");
  6519. res.set_content(body, "text/plain");
  6520. })
  6521. .Post("/query-string-and-body",
  6522. [&](const Request &req, Response & /*res*/) {
  6523. ASSERT_TRUE(req.has_param("key"));
  6524. EXPECT_EQ(req.get_param_value("key"), "value");
  6525. EXPECT_EQ(req.body, "content");
  6526. })
  6527. .Get("/last-request",
  6528. [&](const Request &req, Response & /*res*/) {
  6529. EXPECT_EQ("close", req.get_header_value("Connection"));
  6530. })
  6531. .Get(R"(/redirect/(\d+))",
  6532. [&](const Request &req, Response &res) {
  6533. auto num = std::stoi(req.matches[1]) + 1;
  6534. std::string url = "/redirect/" + std::to_string(num);
  6535. res.set_redirect(url);
  6536. })
  6537. .Post("/binary",
  6538. [&](const Request &req, Response &res) {
  6539. EXPECT_EQ(4U, req.body.size());
  6540. EXPECT_EQ("application/octet-stream",
  6541. req.get_header_value("Content-Type"));
  6542. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6543. res.set_content(req.body, "application/octet-stream");
  6544. })
  6545. .Put("/binary",
  6546. [&](const Request &req, Response &res) {
  6547. EXPECT_EQ(4U, req.body.size());
  6548. EXPECT_EQ("application/octet-stream",
  6549. req.get_header_value("Content-Type"));
  6550. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6551. res.set_content(req.body, "application/octet-stream");
  6552. })
  6553. .Patch("/binary",
  6554. [&](const Request &req, Response &res) {
  6555. EXPECT_EQ(4U, req.body.size());
  6556. EXPECT_EQ("application/octet-stream",
  6557. req.get_header_value("Content-Type"));
  6558. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6559. res.set_content(req.body, "application/octet-stream");
  6560. })
  6561. .Delete("/binary",
  6562. [&](const Request &req, Response &res) {
  6563. EXPECT_EQ(4U, req.body.size());
  6564. EXPECT_EQ("application/octet-stream",
  6565. req.get_header_value("Content-Type"));
  6566. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6567. res.set_content(req.body, "application/octet-stream");
  6568. })
  6569. .Get("/issue1772",
  6570. [&](const Request & /*req*/, Response &res) {
  6571. res.status = 401;
  6572. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6573. })
  6574. .Delete("/issue609",
  6575. [](const httplib::Request &, httplib::Response &res,
  6576. const httplib::ContentReader &) {
  6577. res.set_content("ok", "text/plain");
  6578. })
  6579. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6580. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6581. .Get("/compress",
  6582. [&](const Request & /*req*/, Response &res) {
  6583. res.set_content(
  6584. "12345678901234567890123456789012345678901234567890123456789"
  6585. "01234567890123456789012345678901234567890",
  6586. "text/plain");
  6587. })
  6588. .Get("/compress-with-charset",
  6589. [&](const Request & /*req*/, Response &res) {
  6590. res.set_content(
  6591. "12345678901234567890123456789012345678901234567890123456789"
  6592. "01234567890123456789012345678901234567890",
  6593. "application/json; charset=utf-8");
  6594. })
  6595. .Get("/nocompress",
  6596. [&](const Request & /*req*/, Response &res) {
  6597. res.set_content(
  6598. "12345678901234567890123456789012345678901234567890123456789"
  6599. "01234567890123456789012345678901234567890",
  6600. "application/octet-stream");
  6601. })
  6602. .Post("/compress-multipart",
  6603. [&](const Request &req, Response & /*res*/) {
  6604. EXPECT_EQ(2u, req.form.fields.size());
  6605. ASSERT_TRUE(!req.form.has_field("???"));
  6606. {
  6607. const auto &text = req.form.get_field("key1");
  6608. EXPECT_EQ("test", text);
  6609. }
  6610. {
  6611. const auto &text = req.form.get_field("key2");
  6612. EXPECT_EQ("--abcdefg123", text);
  6613. }
  6614. })
  6615. #endif
  6616. ;
  6617. persons_["john"] = "programmer";
  6618. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6619. svr_.wait_until_ready();
  6620. }
  6621. virtual void TearDown() {
  6622. svr_.stop();
  6623. if (!request_threads_.empty()) {
  6624. std::this_thread::sleep_for(std::chrono::seconds(1));
  6625. for (auto &t : request_threads_) {
  6626. t.join();
  6627. }
  6628. }
  6629. t_.join();
  6630. }
  6631. map<string, string> persons_;
  6632. #ifdef CPPHTTPLIB_SSL_ENABLED
  6633. SSLClient cli_;
  6634. SSLServer svr_;
  6635. #else
  6636. Client cli_;
  6637. Server svr_;
  6638. #endif
  6639. thread t_;
  6640. std::vector<thread> request_threads_;
  6641. };
  6642. TEST_F(ServerTest, GetMethod200) {
  6643. auto res = cli_.Get("/hi");
  6644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6645. EXPECT_EQ("HTTP/1.1", res->version);
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ("OK", res->reason);
  6648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6649. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6650. EXPECT_EQ("Hello World!", res->body);
  6651. }
  6652. TEST_F(ServerTest, GetEmptyFile) {
  6653. auto res = cli_.Get("/empty_file");
  6654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6655. EXPECT_EQ(StatusCode::OK_200, res->status);
  6656. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6657. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6658. EXPECT_EQ("", res->body);
  6659. }
  6660. TEST_F(ServerTest, GetFileContent) {
  6661. auto res = cli_.Get("/file_content");
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::OK_200, res->status);
  6664. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6665. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6666. EXPECT_EQ("test.html", res->body);
  6667. }
  6668. TEST_F(ServerTest, GetFileContentWithRange) {
  6669. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6673. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6674. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6675. EXPECT_EQ("est", res->body);
  6676. }
  6677. TEST_F(ServerTest, GetFileContentWithContentType) {
  6678. auto res = cli_.Get("/file_content_with_content_type");
  6679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6680. EXPECT_EQ(StatusCode::OK_200, res->status);
  6681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6682. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6683. EXPECT_EQ("file\n", res->body);
  6684. }
  6685. TEST_F(ServerTest, GetInvalidFileContent) {
  6686. auto res = cli_.Get("/invalid_file_content");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6689. }
  6690. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6691. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ("HTTP/1.1", res->version);
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6696. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6697. EXPECT_EQ("Hello World!", res->body);
  6698. }
  6699. TEST_F(ServerTest, GetMethod302) {
  6700. auto res = cli_.Get("/");
  6701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6702. EXPECT_EQ(StatusCode::Found_302, res->status);
  6703. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6704. }
  6705. TEST_F(ServerTest, GetMethod302Redirect) {
  6706. cli_.set_follow_location(true);
  6707. auto res = cli_.Get("/");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. EXPECT_EQ("Hello World!", res->body);
  6711. EXPECT_EQ("/hi", res->location);
  6712. }
  6713. TEST_F(ServerTest, GetMethod404) {
  6714. auto res = cli_.Get("/invalid");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6717. }
  6718. TEST_F(ServerTest, HeadMethod200) {
  6719. auto res = cli_.Head("/hi");
  6720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6721. EXPECT_EQ(StatusCode::OK_200, res->status);
  6722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6723. EXPECT_TRUE(res->body.empty());
  6724. }
  6725. TEST_F(ServerTest, HeadMethod200Static) {
  6726. auto res = cli_.Head("/mount/dir/index.html");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6731. EXPECT_TRUE(res->body.empty());
  6732. }
  6733. TEST_F(ServerTest, HeadMethod404) {
  6734. auto res = cli_.Head("/invalid");
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6737. EXPECT_TRUE(res->body.empty());
  6738. }
  6739. TEST_F(ServerTest, GetMethodPersonJohn) {
  6740. auto res = cli_.Get("/person/john");
  6741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6744. EXPECT_EQ("programmer", res->body);
  6745. }
  6746. TEST_F(ServerTest, PostMethod1) {
  6747. auto res = cli_.Get("/person/john1");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6750. res = cli_.Post("/person", "name=john1&note=coder",
  6751. "application/x-www-form-urlencoded");
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. ASSERT_EQ(StatusCode::OK_200, res->status);
  6754. res = cli_.Get("/person/john1");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. ASSERT_EQ(StatusCode::OK_200, res->status);
  6757. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6758. ASSERT_EQ("coder", res->body);
  6759. }
  6760. TEST_F(ServerTest, PostMethod2) {
  6761. auto res = cli_.Get("/person/john2");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6764. Params params;
  6765. params.emplace("name", "john2");
  6766. params.emplace("note", "coder");
  6767. res = cli_.Post("/person", params);
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. ASSERT_EQ(StatusCode::OK_200, res->status);
  6770. res = cli_.Get("/person/john2");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. ASSERT_EQ(StatusCode::OK_200, res->status);
  6773. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6774. ASSERT_EQ("coder", res->body);
  6775. }
  6776. TEST_F(ServerTest, PutMethod3) {
  6777. auto res = cli_.Get("/person/john3");
  6778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6779. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6780. Params params;
  6781. params.emplace("name", "john3");
  6782. params.emplace("note", "coder");
  6783. res = cli_.Put("/person", params);
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. ASSERT_EQ(StatusCode::OK_200, res->status);
  6786. res = cli_.Get("/person/john3");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. ASSERT_EQ(StatusCode::OK_200, res->status);
  6789. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6790. ASSERT_EQ("coder", res->body);
  6791. }
  6792. TEST_F(ServerTest, DeleteMethod1) {
  6793. auto res = cli_.Get("/person/john4");
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6796. Params params;
  6797. params.emplace("name", "john4");
  6798. params.emplace("note", "coder");
  6799. res = cli_.Post("/person", params);
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. ASSERT_EQ(StatusCode::OK_200, res->status);
  6802. res = cli_.Get("/person/john4");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. ASSERT_EQ(StatusCode::OK_200, res->status);
  6805. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6806. ASSERT_EQ("coder", res->body);
  6807. Params delete_params;
  6808. delete_params.emplace("name", "john4");
  6809. res = cli_.Delete("/person", delete_params);
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. ASSERT_EQ(StatusCode::OK_200, res->status);
  6812. ASSERT_EQ("DELETED", res->body);
  6813. res = cli_.Get("/person/john4");
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6816. }
  6817. TEST_F(ServerTest, DeleteMethod2) {
  6818. auto res = cli_.Get("/person/john5");
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6821. Params params;
  6822. params.emplace("name", "john5");
  6823. params.emplace("note", "developer");
  6824. res = cli_.Post("/person", params);
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. ASSERT_EQ(StatusCode::OK_200, res->status);
  6827. res = cli_.Get("/person/john5");
  6828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6829. ASSERT_EQ(StatusCode::OK_200, res->status);
  6830. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6831. ASSERT_EQ("developer", res->body);
  6832. Params delete_params;
  6833. delete_params.emplace("name", "john5");
  6834. Headers headers;
  6835. headers.emplace("Custom-Header", "test-value");
  6836. res = cli_.Delete("/person", headers, delete_params);
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. ASSERT_EQ(StatusCode::OK_200, res->status);
  6839. ASSERT_EQ("DELETED", res->body);
  6840. res = cli_.Get("/person/john5");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6843. }
  6844. TEST_F(ServerTest, DeleteMethod3) {
  6845. auto res = cli_.Get("/person/john6");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6848. Params params;
  6849. params.emplace("name", "john6");
  6850. params.emplace("note", "tester");
  6851. res = cli_.Post("/person", params);
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. ASSERT_EQ(StatusCode::OK_200, res->status);
  6854. res = cli_.Get("/person/john6");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. ASSERT_EQ(StatusCode::OK_200, res->status);
  6857. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6858. ASSERT_EQ("tester", res->body);
  6859. Params delete_params;
  6860. delete_params.emplace("name", "john6");
  6861. Headers headers;
  6862. headers.emplace("Custom-Header", "test-value");
  6863. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. ASSERT_EQ(StatusCode::OK_200, res->status);
  6866. ASSERT_EQ("DELETED", res->body);
  6867. res = cli_.Get("/person/john6");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6870. }
  6871. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6872. Params params;
  6873. params.emplace("json", JSON_DATA);
  6874. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. ASSERT_EQ(StatusCode::OK_200, res->status);
  6877. ASSERT_EQ(JSON_DATA, res->body);
  6878. }
  6879. TEST_F(ServerTest, PostEmptyContent) {
  6880. auto res = cli_.Post("/empty", "", "text/plain");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. ASSERT_EQ(StatusCode::OK_200, res->status);
  6883. ASSERT_EQ("empty", res->body);
  6884. }
  6885. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6886. auto res = cli_.Post("/empty-no-content-type");
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. ASSERT_EQ(StatusCode::OK_200, res->status);
  6889. ASSERT_EQ("empty-no-content-type", res->body);
  6890. }
  6891. TEST_F(ServerTest, PostPathOnly) {
  6892. auto res = cli_.Post("/path-only");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::OK_200, res->status);
  6895. ASSERT_EQ("path-only", res->body);
  6896. }
  6897. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6898. auto res = cli_.Post("/path-headers-only",
  6899. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. ASSERT_EQ(StatusCode::OK_200, res->status);
  6902. ASSERT_EQ("path-headers-only", res->body);
  6903. }
  6904. TEST_F(ServerTest, PostLarge) {
  6905. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. ASSERT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ(LARGE_DATA, res->body);
  6909. }
  6910. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6911. auto res = cli_.Put("/empty-no-content-type");
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. ASSERT_EQ(StatusCode::OK_200, res->status);
  6914. ASSERT_EQ("empty-no-content-type", res->body);
  6915. }
  6916. TEST_F(ServerTest, GetMethodDir) {
  6917. auto res = cli_.Get("/dir/");
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_EQ(StatusCode::OK_200, res->status);
  6920. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6921. auto body = R"(<html>
  6922. <head>
  6923. </head>
  6924. <body>
  6925. <a href="/dir/test.html">Test</a>
  6926. <a href="/hi">hi</a>
  6927. </body>
  6928. </html>
  6929. )";
  6930. EXPECT_EQ(body, res->body);
  6931. }
  6932. TEST_F(ServerTest, GetMethodDirTest) {
  6933. auto res = cli_.Get("/dir/test.html");
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6937. EXPECT_EQ("test.html", res->body);
  6938. }
  6939. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6940. auto res = cli_.Get("/dir/../dir/test.html");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6943. }
  6944. TEST_F(ServerTest, GetMethodInvalidPath) {
  6945. auto res = cli_.Get("/dir/../test.html");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6948. }
  6949. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6950. auto res = cli_.Get("/../www/dir/test.html");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6953. }
  6954. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6955. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6958. }
  6959. TEST_F(ServerTest, GetMethodDirMountTest) {
  6960. auto res = cli_.Get("/mount/dir/test.html");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6964. EXPECT_EQ("test.html", res->body);
  6965. }
  6966. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6967. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6970. }
  6971. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6972. auto res = cli_.Get("/mount/dir/../test.html");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6975. }
  6976. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6977. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6980. }
  6981. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6982. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6985. }
  6986. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6987. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6990. }
  6991. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6992. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6994. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6995. }
  6996. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6997. auto res = cli_.Get("/mount/dir");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7000. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7001. }
  7002. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7003. auto res = cli_.Get("//dir");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7006. EXPECT_FALSE(res->has_header("Location"));
  7007. }
  7008. TEST_F(ServerTest, PostMethod303) {
  7009. auto res = cli_.Post("/1", "body", "text/plain");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7012. EXPECT_EQ("/2", res->get_header_value("Location"));
  7013. }
  7014. TEST_F(ServerTest, PostMethod303Redirect) {
  7015. cli_.set_follow_location(true);
  7016. auto res = cli_.Post("/1", "body", "text/plain");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("redirected.", res->body);
  7020. EXPECT_EQ("/2", res->location);
  7021. }
  7022. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7023. auto res = cli_.Get("/dir/test.abcde");
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7027. EXPECT_EQ("abcde", res->body);
  7028. }
  7029. TEST_F(ServerTest, StaticFileRange) {
  7030. auto res =
  7031. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7034. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7035. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7036. EXPECT_EQ(true, res->has_header("Content-Range"));
  7037. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7038. EXPECT_EQ(std::string("cd"), res->body);
  7039. }
  7040. TEST_F(ServerTest, StaticFileRanges) {
  7041. auto res = cli_.Get("/dir/test.abcde",
  7042. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7045. EXPECT_TRUE(
  7046. res->get_header_value("Content-Type")
  7047. .find(
  7048. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7049. 0);
  7050. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7051. }
  7052. TEST_F(ServerTest, StaticFileRangeHead) {
  7053. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7056. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7057. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7058. EXPECT_EQ(true, res->has_header("Content-Range"));
  7059. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7060. }
  7061. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7062. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7066. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7067. EXPECT_EQ(true, res->has_header("Content-Range"));
  7068. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7069. res->get_header_value("Content-Range"));
  7070. EXPECT_EQ("LAST\n", res->body);
  7071. }
  7072. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7073. auto res =
  7074. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7078. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7079. EXPECT_EQ(true, res->has_header("Content-Range"));
  7080. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7081. }
  7082. TEST_F(ServerTest, StaticFileBigFile) {
  7083. auto res = cli_.Get("/dir/1MB.txt");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::OK_200, res->status);
  7086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7087. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7088. }
  7089. TEST_F(ServerTest, InvalidBaseDirMount) {
  7090. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7091. }
  7092. TEST_F(ServerTest, Binary) {
  7093. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7094. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7095. "application/octet-stream");
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. ASSERT_EQ(StatusCode::OK_200, res->status);
  7098. ASSERT_EQ(4U, res->body.size());
  7099. res = cli_.Put("/binary", binary.data(), binary.size(),
  7100. "application/octet-stream");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. ASSERT_EQ(StatusCode::OK_200, res->status);
  7103. ASSERT_EQ(4U, res->body.size());
  7104. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7105. "application/octet-stream");
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. ASSERT_EQ(StatusCode::OK_200, res->status);
  7108. ASSERT_EQ(4U, res->body.size());
  7109. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7110. "application/octet-stream");
  7111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7112. ASSERT_EQ(StatusCode::OK_200, res->status);
  7113. ASSERT_EQ(4U, res->body.size());
  7114. }
  7115. TEST_F(ServerTest, BinaryString) {
  7116. auto binary = std::string("\x00\x01\x02\x03", 4);
  7117. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. ASSERT_EQ(StatusCode::OK_200, res->status);
  7120. ASSERT_EQ(4U, res->body.size());
  7121. res = cli_.Put("/binary", binary, "application/octet-stream");
  7122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7123. ASSERT_EQ(StatusCode::OK_200, res->status);
  7124. ASSERT_EQ(4U, res->body.size());
  7125. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. ASSERT_EQ(StatusCode::OK_200, res->status);
  7128. ASSERT_EQ(4U, res->body.size());
  7129. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7131. ASSERT_EQ(StatusCode::OK_200, res->status);
  7132. ASSERT_EQ(4U, res->body.size());
  7133. }
  7134. TEST_F(ServerTest, EmptyRequest) {
  7135. auto res = cli_.Get("");
  7136. ASSERT_TRUE(!res);
  7137. EXPECT_EQ(Error::Connection, res.error());
  7138. }
  7139. TEST_F(ServerTest, LongRequest) {
  7140. std::string request;
  7141. for (size_t i = 0; i < 545; i++) {
  7142. request += "/TooLongRequest";
  7143. }
  7144. request += "OK";
  7145. auto res = cli_.Get(request.c_str());
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7148. }
  7149. TEST_F(ServerTest, TooLongRequest) {
  7150. std::string request;
  7151. for (size_t i = 0; i < 546; i++) {
  7152. request += "/TooLongRequest";
  7153. }
  7154. request += "_NG";
  7155. auto start = std::chrono::high_resolution_clock::now();
  7156. cli_.set_keep_alive(true);
  7157. auto res = cli_.Get(request.c_str());
  7158. auto end = std::chrono::high_resolution_clock::now();
  7159. auto elapsed =
  7160. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7161. .count();
  7162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7163. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7164. EXPECT_LE(elapsed, 1000);
  7165. EXPECT_EQ("close", res->get_header_value("Connection"));
  7166. EXPECT_FALSE(cli_.is_socket_open());
  7167. }
  7168. TEST_F(ServerTest, AlmostTooLongRequest) {
  7169. // test for #2046 - URI length check shouldn't include other content on req
  7170. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7171. // leading /, space, HTTP/1.1)
  7172. std::string request =
  7173. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7174. auto res = cli_.Get(request.c_str());
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7177. }
  7178. TEST_F(ServerTest, LongHeader) {
  7179. Request req;
  7180. req.method = "GET";
  7181. req.path = "/hi";
  7182. std::string host_and_port;
  7183. host_and_port += HOST;
  7184. host_and_port += ":";
  7185. host_and_port += std::to_string(PORT);
  7186. req.headers.emplace("Host", host_and_port.c_str());
  7187. req.headers.emplace("Accept", "*/*");
  7188. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7189. req.headers.emplace(
  7190. "Header-Name",
  7191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7219. "@@@@@@@@@@@@@@@@");
  7220. auto res = std::make_shared<Response>();
  7221. auto error = Error::Success;
  7222. auto ret = cli_.send(req, *res, error);
  7223. ASSERT_TRUE(ret);
  7224. EXPECT_EQ(StatusCode::OK_200, res->status);
  7225. }
  7226. TEST_F(ServerTest, LongQueryValue) {
  7227. auto start = std::chrono::high_resolution_clock::now();
  7228. cli_.set_keep_alive(true);
  7229. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7230. auto end = std::chrono::high_resolution_clock::now();
  7231. auto elapsed =
  7232. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7233. .count();
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7236. EXPECT_LE(elapsed, 1000);
  7237. EXPECT_EQ("close", res->get_header_value("Connection"));
  7238. EXPECT_FALSE(cli_.is_socket_open());
  7239. }
  7240. TEST_F(ServerTest, TooLongQueryValue) {
  7241. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7242. ASSERT_FALSE(res);
  7243. EXPECT_EQ(Error::Read, res.error());
  7244. }
  7245. TEST_F(ServerTest, TooLongHeader) {
  7246. Request req;
  7247. req.method = "GET";
  7248. req.path = "/hi";
  7249. std::string host_and_port;
  7250. host_and_port += HOST;
  7251. host_and_port += ":";
  7252. host_and_port += std::to_string(PORT);
  7253. req.headers.emplace("Host", host_and_port.c_str());
  7254. req.headers.emplace("Accept", "*/*");
  7255. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7256. req.headers.emplace(
  7257. "Header-Name",
  7258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7286. "@@@@@@@@@@@@@@@@@");
  7287. auto res = std::make_shared<Response>();
  7288. auto error = Error::Success;
  7289. auto ret = cli_.send(req, *res, error);
  7290. ASSERT_TRUE(ret);
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. TEST_F(ServerTest, HeaderCountAtLimit) {
  7294. // Test with headers just under the 100 limit
  7295. httplib::Headers headers;
  7296. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7297. // This should keep us just under the 100 header limit
  7298. for (int i = 0; i < 95; i++) {
  7299. std::string name = "X-Test-Header-" + std::to_string(i);
  7300. std::string value = "value" + std::to_string(i);
  7301. headers.emplace(name, value);
  7302. }
  7303. // This should work fine as we're under the limit
  7304. auto res = cli_.Get("/hi", headers);
  7305. EXPECT_TRUE(res);
  7306. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7307. }
  7308. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7309. // Test with many headers to exceed the 100 limit
  7310. httplib::Headers headers;
  7311. // Add 150 headers to definitely exceed the 100 limit
  7312. for (int i = 0; i < 150; i++) {
  7313. std::string name = "X-Test-Header-" + std::to_string(i);
  7314. std::string value = "value" + std::to_string(i);
  7315. headers.emplace(name, value);
  7316. }
  7317. // This should fail due to exceeding header count limit
  7318. cli_.set_keep_alive(true);
  7319. auto res = cli_.Get("/hi", headers);
  7320. // The server should respond with 400 Bad Request
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7323. EXPECT_EQ("close", res->get_header_value("Connection"));
  7324. EXPECT_FALSE(cli_.is_socket_open());
  7325. }
  7326. TEST_F(ServerTest, PercentEncoding) {
  7327. auto res = cli_.Get("/e%6edwith%");
  7328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7329. EXPECT_EQ(StatusCode::OK_200, res->status);
  7330. }
  7331. TEST_F(ServerTest, PercentEncodingUnicode) {
  7332. auto res = cli_.Get("/e%u006edwith%");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. }
  7336. TEST_F(ServerTest, InvalidPercentEncoding) {
  7337. auto res = cli_.Get("/%endwith%");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7340. }
  7341. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7342. auto res = cli_.Get("/%uendwith%");
  7343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7345. }
  7346. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7347. auto res = cli_.Get("/hello?aaa=bbb%");
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7350. }
  7351. TEST_F(ServerTest, PlusSignEncoding) {
  7352. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7354. EXPECT_EQ(StatusCode::OK_200, res->status);
  7355. EXPECT_EQ("a +b", res->body);
  7356. }
  7357. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7358. // This test simulates a potential DoS attack using many headers
  7359. // to verify our security fix prevents memory exhaustion
  7360. httplib::Headers attack_headers;
  7361. // Attempt to add many headers like an attacker would (200 headers to far
  7362. // exceed limit)
  7363. for (int i = 0; i < 200; i++) {
  7364. std::string name = "X-Attack-Header-" + std::to_string(i);
  7365. std::string value = "attack_payload_" + std::to_string(i);
  7366. attack_headers.emplace(name, value);
  7367. }
  7368. // Try to POST with excessive headers
  7369. cli_.set_keep_alive(true);
  7370. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7371. // Should either fail or return 400 Bad Request due to security limit
  7372. if (res) {
  7373. // If we get a response, it should be 400 Bad Request
  7374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7375. EXPECT_EQ("close", res->get_header_value("Connection"));
  7376. }
  7377. EXPECT_FALSE(cli_.is_socket_open());
  7378. }
  7379. TEST_F(ServerTest, MultipartFormData) {
  7380. UploadFormDataItems items = {
  7381. {"text1", "text default", "", ""},
  7382. {"text2", "aωb", "", ""},
  7383. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7384. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7385. {"file3", "", "", "application/octet-stream"},
  7386. {"file4", "", "", " application/json tmp-string "}};
  7387. auto res = cli_.Post("/multipart", items);
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::OK_200, res->status);
  7390. }
  7391. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7392. UploadFormDataItems items = {
  7393. {"text", "default text", "", ""},
  7394. {"multi_text1", "aaaaa", "", ""},
  7395. {"multi_text1", "bbbbb", "", ""},
  7396. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7397. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7398. "application/json"},
  7399. };
  7400. auto res = cli_.Post("/multipart/multi_file_values", items);
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. }
  7404. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7405. auto res = cli_.Get("/hi");
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7409. EXPECT_EQ("Hello World!", res->body);
  7410. }
  7411. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7412. Request req;
  7413. req.method = "POST";
  7414. req.path = "/chunked";
  7415. std::string host_and_port;
  7416. host_and_port += HOST;
  7417. host_and_port += ":";
  7418. host_and_port += std::to_string(PORT);
  7419. req.headers.emplace("Host", host_and_port.c_str());
  7420. req.headers.emplace("Accept", "*/*");
  7421. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7422. req.headers.emplace("Content-Type", "text/plain");
  7423. req.headers.emplace("Content-Length", "0");
  7424. req.headers.emplace(
  7425. "Transfer-Encoding",
  7426. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7427. // Client does not chunk, so make a chunked body manually.
  7428. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7429. auto res = std::make_shared<Response>();
  7430. auto error = Error::Success;
  7431. auto ret = cli_.send(req, *res, error);
  7432. ASSERT_TRUE(ret);
  7433. EXPECT_EQ(StatusCode::OK_200, res->status);
  7434. }
  7435. template <typename ClientT>
  7436. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7437. int expected_status) {
  7438. Request req;
  7439. req.method = "POST";
  7440. req.path = "/chunked";
  7441. std::string host_and_port;
  7442. host_and_port += HOST;
  7443. host_and_port += ":";
  7444. host_and_port += std::to_string(PORT);
  7445. req.headers.emplace("Host", host_and_port.c_str());
  7446. req.headers.emplace("Content-Length", "0");
  7447. req.headers.emplace("Transfer-Encoding", "chunked");
  7448. req.body = body;
  7449. auto res = std::make_shared<Response>();
  7450. auto error = Error::Success;
  7451. ASSERT_TRUE(cli.send(req, *res, error));
  7452. EXPECT_EQ(expected_status, res->status);
  7453. }
  7454. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7455. // rather than treat them as valid lengths.
  7456. template <typename ClientT>
  7457. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7458. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7459. }
  7460. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7461. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7462. }
  7463. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7464. expect_chunked_body_rejected(
  7465. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7466. }
  7467. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7468. // chunk-size line carries no CR, LF or other control character ahead of its
  7469. // terminator. Such a line must be refused rather than read as extension text.
  7470. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7471. expect_chunked_body_rejected(
  7472. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7473. }
  7474. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7475. expect_chunked_body_rejected(
  7476. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7477. }
  7478. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7479. expect_chunked_body_rejected(
  7480. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7481. }
  7482. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7483. // The literal stays split: a hex escape consumes every hex digit that
  7484. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7485. expect_chunked_body_rejected(
  7486. cli_, "4;a\x01"
  7487. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7488. }
  7489. // The bytes around chunk data are no payload, so they cannot ride on the
  7490. // payload limit
  7491. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7492. // Small enough that the whole request is sent before the server turns it
  7493. // down, yet past the limit by the last chunks
  7494. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7495. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7496. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7497. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7498. SCOPED_TRACE(size_line.substr(0, 2));
  7499. std::string body;
  7500. for (auto c : std::string("dechunked post body")) {
  7501. body += size_line + "\r\n" + c + "\r\n";
  7502. }
  7503. body += "0\r\n\r\n";
  7504. expect_chunked_body_rejected(cli_, body.c_str());
  7505. }
  7506. }
  7507. TEST_F(ServerTest, AcceptsChunkExtension) {
  7508. expect_chunked_body_status(cli_,
  7509. "4;name=value\r\ndech\r\n"
  7510. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7511. "0;last\r\n\r\n",
  7512. StatusCode::OK_200);
  7513. }
  7514. TEST_F(ServerTest, GetStreamed2) {
  7515. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7518. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7519. EXPECT_EQ(true, res->has_header("Content-Range"));
  7520. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7521. EXPECT_EQ(std::string("ab"), res->body);
  7522. }
  7523. TEST_F(ServerTest, GetStreamed) {
  7524. auto res = cli_.Get("/streamed");
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::OK_200, res->status);
  7527. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7528. EXPECT_EQ(std::string("aaabbb"), res->body);
  7529. }
  7530. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7531. auto res = cli_.Get("/streamed-without-length",
  7532. Headers{make_range_header({{0, -1}})});
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(false, res->has_header("Content-Length"));
  7536. EXPECT_EQ(false, res->has_header("Content-Range"));
  7537. EXPECT_EQ(std::string("abcdefg"), res->body);
  7538. }
  7539. TEST_F(ServerTest, GetStreamedWithRange1) {
  7540. auto res =
  7541. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7543. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7544. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7545. EXPECT_EQ(true, res->has_header("Content-Range"));
  7546. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7547. EXPECT_EQ(std::string("def"), res->body);
  7548. }
  7549. TEST_F(ServerTest, GetStreamedWithRange2) {
  7550. auto res =
  7551. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7554. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7555. EXPECT_EQ(true, res->has_header("Content-Range"));
  7556. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7557. EXPECT_EQ(std::string("bcdefg"), res->body);
  7558. }
  7559. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7560. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7563. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7564. EXPECT_EQ(true, res->has_header("Content-Range"));
  7565. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7566. EXPECT_EQ(std::string("efg"), res->body);
  7567. }
  7568. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7569. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7570. // the entire representation.
  7571. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7572. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7575. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7576. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7577. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7578. }
  7579. }
  7580. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7581. auto res =
  7582. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7584. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7585. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7586. EXPECT_EQ(false, res->has_header("Content-Range"));
  7587. EXPECT_EQ(0U, res->body.size());
  7588. }
  7589. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7590. // Only a 206 is served as a partial representation. Under any other status
  7591. // `apply_ranges()` reported the full content length, so the body must match
  7592. // that header, and the content provider must never be asked for an offset
  7593. // outside the representation.
  7594. auto check = [&](int status, const char *range) {
  7595. auto path =
  7596. std::string("/streamed-with-range?status=") + std::to_string(status);
  7597. auto ctx = path + " Range: " + range;
  7598. auto res = cli_.Get(path, Headers{{"Range", range}});
  7599. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7600. EXPECT_EQ(status, res->status) << ctx;
  7601. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7602. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7603. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7604. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7605. };
  7606. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7607. check(403, "bytes=3-5");
  7608. // The offset is far past the representation.
  7609. check(403, "bytes=100000-100200");
  7610. // `first_pos` is still -1 here, and the bounds asserts in
  7611. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7612. check(403, "bytes=-3");
  7613. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7614. // multipart branch would have written one that is empty.
  7615. check(403, "bytes=1-2, 4-5");
  7616. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7617. // covers the whole representation.
  7618. check(200, "bytes=3-5");
  7619. check(200, "bytes=1-2, 4-5");
  7620. }
  7621. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7622. auto res =
  7623. cli_.Get("/streamed-with-range",
  7624. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7625. "92233720368547758079223372036854775807"}});
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7628. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7629. EXPECT_EQ(false, res->has_header("Content-Range"));
  7630. EXPECT_EQ(0U, res->body.size());
  7631. }
  7632. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7633. auto res = cli_.Get(
  7634. "/with-range",
  7635. Headers{{"Range",
  7636. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7637. {"Accept-Encoding", ""}});
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7640. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ(true, res->has_header("Content-Range"));
  7642. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7643. EXPECT_EQ(std::string("abcdefg"), res->body);
  7644. }
  7645. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7646. auto res = cli_.Get("/with-range", Headers{
  7647. {"Range", "bytes=0-"},
  7648. {"Accept-Encoding", ""},
  7649. });
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7652. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7653. EXPECT_EQ(true, res->has_header("Content-Range"));
  7654. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7655. EXPECT_EQ(std::string("abcdefg"), res->body);
  7656. }
  7657. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7658. auto res = cli_.Get("/streamed-with-range",
  7659. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7662. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7663. EXPECT_EQ(false, res->has_header("Content-Range"));
  7664. EXPECT_EQ(267U, res->body.size());
  7665. // Check that both range contents are present
  7666. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7667. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7668. // Check that Content-Range headers are present for both ranges
  7669. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7670. std::string::npos);
  7671. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7672. std::string::npos);
  7673. }
  7674. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7675. Ranges ranges;
  7676. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7677. ranges.emplace_back(0, -1);
  7678. }
  7679. auto res = cli_.Get("/streamed-with-range?error",
  7680. Headers{{make_range_header(ranges)}});
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7683. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7684. EXPECT_EQ(false, res->has_header("Content-Range"));
  7685. EXPECT_EQ(0U, res->body.size());
  7686. }
  7687. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7688. auto res = cli_.Get("/streamed-with-range",
  7689. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7692. EXPECT_EQ(5U, res->body.size());
  7693. // Check that overlapping ranges are coalesced into a single range
  7694. EXPECT_EQ("bcdef", res->body);
  7695. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7696. // Should be single range, not multipart
  7697. EXPECT_TRUE(res->has_header("Content-Range"));
  7698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7699. }
  7700. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7701. auto res = cli_.Get("/streamed-with-range",
  7702. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7705. EXPECT_EQ(268U, res->body.size());
  7706. // Check that both range contents are present
  7707. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7708. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7709. // Check that Content-Range headers are present for both ranges
  7710. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7711. std::string::npos);
  7712. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7713. std::string::npos);
  7714. }
  7715. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7716. auto res = cli_.Get("/streamed-with-range",
  7717. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7720. EXPECT_EQ(269U, res->body.size());
  7721. // Check that both duplicate range contents are present
  7722. size_t first_abc = res->body.find("abc\r\n");
  7723. EXPECT_TRUE(first_abc != std::string::npos);
  7724. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7725. EXPECT_TRUE(second_abc != std::string::npos);
  7726. // Check that Content-Range headers are present for both ranges
  7727. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7728. EXPECT_TRUE(first_range != std::string::npos);
  7729. size_t second_range =
  7730. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7731. EXPECT_TRUE(second_range != std::string::npos);
  7732. }
  7733. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7734. auto res =
  7735. cli_.Get("/streamed-with-range?error",
  7736. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7739. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7740. EXPECT_EQ(false, res->has_header("Content-Range"));
  7741. EXPECT_EQ(0U, res->body.size());
  7742. }
  7743. TEST_F(ServerTest, GetStreamedEndless) {
  7744. uint64_t offset = 0;
  7745. auto res = cli_.Get("/streamed-cancel",
  7746. [&](const char * /*data*/, uint64_t data_length) {
  7747. if (offset < 100) {
  7748. offset += data_length;
  7749. return true;
  7750. }
  7751. return false;
  7752. });
  7753. ASSERT_TRUE(!res);
  7754. EXPECT_EQ(Error::Canceled, res.error());
  7755. }
  7756. TEST_F(ServerTest, ClientStop) {
  7757. std::atomic_size_t count{4};
  7758. std::vector<std::thread> threads;
  7759. for (auto i = count.load(); i != 0; --i) {
  7760. threads.emplace_back([&]() {
  7761. auto res = cli_.Get("/streamed-cancel",
  7762. [&](const char *, uint64_t) { return true; });
  7763. --count;
  7764. ASSERT_TRUE(!res);
  7765. EXPECT_TRUE(res.error() == Error::Canceled ||
  7766. res.error() == Error::Read || res.error() == Error::Write);
  7767. });
  7768. }
  7769. std::this_thread::sleep_for(std::chrono::seconds(2));
  7770. while (count != 0) {
  7771. cli_.stop();
  7772. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7773. }
  7774. for (auto &t : threads) {
  7775. t.join();
  7776. }
  7777. }
  7778. TEST_F(ServerTest, GetWithRange1) {
  7779. auto res = cli_.Get("/with-range", Headers{
  7780. make_range_header({{3, 5}}),
  7781. {"Accept-Encoding", ""},
  7782. });
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7785. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7786. EXPECT_EQ(true, res->has_header("Content-Range"));
  7787. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7788. EXPECT_EQ(std::string("def"), res->body);
  7789. }
  7790. TEST_F(ServerTest, GetWithRange2) {
  7791. auto res = cli_.Get("/with-range", Headers{
  7792. make_range_header({{1, -1}}),
  7793. {"Accept-Encoding", ""},
  7794. });
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7797. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7798. EXPECT_EQ(true, res->has_header("Content-Range"));
  7799. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7800. EXPECT_EQ(std::string("bcdefg"), res->body);
  7801. }
  7802. TEST_F(ServerTest, GetWithRange3) {
  7803. auto res = cli_.Get("/with-range", Headers{
  7804. make_range_header({{0, 0}}),
  7805. {"Accept-Encoding", ""},
  7806. });
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7809. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7810. EXPECT_EQ(true, res->has_header("Content-Range"));
  7811. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7812. EXPECT_EQ(std::string("a"), res->body);
  7813. }
  7814. TEST_F(ServerTest, GetWithRange4) {
  7815. auto res = cli_.Get("/with-range", Headers{
  7816. make_range_header({{-1, 2}}),
  7817. {"Accept-Encoding", ""},
  7818. });
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7821. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(true, res->has_header("Content-Range"));
  7823. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7824. EXPECT_EQ(std::string("fg"), res->body);
  7825. }
  7826. TEST_F(ServerTest, GetWithRange5) {
  7827. auto res = cli_.Get("/with-range", Headers{
  7828. make_range_header({{0, 5}}),
  7829. {"Accept-Encoding", ""},
  7830. });
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7833. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7834. EXPECT_EQ(true, res->has_header("Content-Range"));
  7835. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7836. EXPECT_EQ(std::string("abcdef"), res->body);
  7837. }
  7838. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7839. auto res =
  7840. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7843. }
  7844. TEST_F(ServerTest, GetWithRangeMultipart) {
  7845. auto res =
  7846. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7849. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7850. EXPECT_EQ(false, res->has_header("Content-Range"));
  7851. EXPECT_EQ(267U, res->body.size());
  7852. }
  7853. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7854. auto res = cli_.Get("/with-range",
  7855. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7857. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7858. }
  7859. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7860. auto res = cli_.Get("/with-range-customized-response",
  7861. Headers{{make_range_header({{1, 2}})}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7864. EXPECT_EQ(true, res->has_header("Content-Length"));
  7865. EXPECT_EQ(false, res->has_header("Content-Range"));
  7866. EXPECT_EQ(JSON_DATA, res->body);
  7867. }
  7868. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7869. auto res = cli_.Get("/with-range-customized-response",
  7870. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7873. EXPECT_EQ(true, res->has_header("Content-Length"));
  7874. EXPECT_EQ(false, res->has_header("Content-Range"));
  7875. EXPECT_EQ(JSON_DATA, res->body);
  7876. }
  7877. TEST_F(ServerTest, Issue1772) {
  7878. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7881. }
  7882. TEST_F(ServerTest, Issue609) {
  7883. auto res = cli_.Delete("/issue609");
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_EQ(std::string("ok"), res->body);
  7887. }
  7888. TEST_F(ServerTest, GetStreamedChunked) {
  7889. auto res = cli_.Get("/streamed-chunked");
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. EXPECT_EQ(StatusCode::OK_200, res->status);
  7892. EXPECT_EQ(std::string("123456789"), res->body);
  7893. }
  7894. TEST_F(ServerTest, GetStreamedChunked2) {
  7895. auto res = cli_.Get("/streamed-chunked2");
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ(StatusCode::OK_200, res->status);
  7898. EXPECT_EQ(std::string("123456789"), res->body);
  7899. }
  7900. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7901. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7903. EXPECT_EQ(StatusCode::OK_200, res->status);
  7904. EXPECT_EQ(std::string("123456789"), res->body);
  7905. EXPECT_TRUE(res->has_header("Trailer"));
  7906. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7907. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7908. // Trailers are now stored separately from headers (security fix)
  7909. EXPECT_EQ(2U, res->trailers.size());
  7910. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7911. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7912. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7913. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7914. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7915. // Verify trailers are NOT in headers (security verification)
  7916. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7917. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7918. }
  7919. TEST_F(ServerTest, LargeChunkedPost) {
  7920. Request req;
  7921. req.method = "POST";
  7922. req.path = "/large-chunked";
  7923. std::string host_and_port;
  7924. host_and_port += HOST;
  7925. host_and_port += ":";
  7926. host_and_port += std::to_string(PORT);
  7927. req.headers.emplace("Host", host_and_port.c_str());
  7928. req.headers.emplace("Accept", "*/*");
  7929. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7930. req.headers.emplace("Content-Type", "text/plain");
  7931. req.headers.emplace("Content-Length", "0");
  7932. req.headers.emplace("Transfer-Encoding", "chunked");
  7933. std::string long_string(30 * 1024u, 'a');
  7934. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7935. // Attempt to make a large enough post to exceed OS buffers, to test that
  7936. // the server handles short reads if the full chunk data isn't available.
  7937. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7938. auto res = std::make_shared<Response>();
  7939. auto error = Error::Success;
  7940. auto ret = cli_.send(req, *res, error);
  7941. ASSERT_TRUE(ret);
  7942. EXPECT_EQ(StatusCode::OK_200, res->status);
  7943. }
  7944. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7945. auto res = cli_.Get("/remote_addr");
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7949. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7950. }
  7951. TEST_F(ServerTest, GetMethodLocalAddr) {
  7952. auto res = cli_.Get("/local_addr");
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. EXPECT_EQ(StatusCode::OK_200, res->status);
  7955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7956. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7957. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7958. }
  7959. TEST_F(ServerTest, HTTPResponseSplitting) {
  7960. auto res = cli_.Get("/http_response_splitting");
  7961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7962. EXPECT_EQ(StatusCode::OK_200, res->status);
  7963. }
  7964. TEST_F(ServerTest, SlowRequest) {
  7965. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7966. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7967. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7968. }
  7969. #if 0
  7970. TEST_F(ServerTest, SlowPost) {
  7971. char buffer[64 * 1024];
  7972. memset(buffer, 0x42, sizeof(buffer));
  7973. auto res = cli_.Post(
  7974. "/slowpost", 64 * 1024 * 1024,
  7975. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7976. auto ret = sink.write(buffer, sizeof(buffer));
  7977. EXPECT_TRUE(ret);
  7978. return true;
  7979. },
  7980. "text/plain");
  7981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7982. EXPECT_EQ(StatusCode::OK_200, res->status);
  7983. }
  7984. TEST_F(ServerTest, SlowPostFail) {
  7985. char buffer[64 * 1024];
  7986. memset(buffer, 0x42, sizeof(buffer));
  7987. cli_.set_write_timeout(std::chrono::seconds(0));
  7988. auto res = cli_.Post(
  7989. "/slowpost", 64 * 1024 * 1024,
  7990. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7991. sink.write(buffer, sizeof(buffer));
  7992. return true;
  7993. },
  7994. "text/plain");
  7995. ASSERT_TRUE(!res);
  7996. EXPECT_EQ(Error::Write, res.error());
  7997. }
  7998. #endif
  7999. TEST_F(ServerTest, Put) {
  8000. auto res = cli_.Put("/put", "PUT", "text/plain");
  8001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. EXPECT_EQ("PUT", res->body);
  8004. }
  8005. TEST_F(ServerTest, PutWithContentProvider) {
  8006. auto res = cli_.Put(
  8007. "/put", 3,
  8008. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8009. sink.os << "PUT";
  8010. return true;
  8011. },
  8012. "text/plain");
  8013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. EXPECT_EQ("PUT", res->body);
  8016. }
  8017. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8018. auto res = cli_.Post(
  8019. "/post", 42,
  8020. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8021. return false;
  8022. },
  8023. "text/plain");
  8024. ASSERT_TRUE(!res);
  8025. EXPECT_EQ(Error::Canceled, res.error());
  8026. }
  8027. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8028. auto res = cli_.Put(
  8029. "/put",
  8030. [](size_t /*offset*/, DataSink &sink) {
  8031. sink.os << "PUT";
  8032. sink.done();
  8033. return true;
  8034. },
  8035. "text/plain");
  8036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. EXPECT_EQ("PUT", res->body);
  8039. }
  8040. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8041. auto res = cli_.Post(
  8042. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8043. "text/plain");
  8044. ASSERT_TRUE(!res);
  8045. EXPECT_EQ(Error::Canceled, res.error());
  8046. }
  8047. TEST_F(ServerTest, PostLoopBack) {
  8048. std::string body;
  8049. auto res = cli_.Post(
  8050. "/post-loopback", 9,
  8051. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8052. EXPECT_EQ(9u, length);
  8053. sink.write("123", 3);
  8054. sink.write("456", 3);
  8055. sink.write("789", 3);
  8056. return true;
  8057. },
  8058. "text/plain",
  8059. [&body](const char *data, size_t data_length) {
  8060. body.append(data, data_length);
  8061. return true;
  8062. });
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ(StatusCode::OK_200, res->status);
  8065. EXPECT_EQ("123456789", body);
  8066. }
  8067. TEST_F(ServerTest, PutLoopBack) {
  8068. std::string body;
  8069. auto res = cli_.Put(
  8070. "/put-loopback", 9,
  8071. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8072. EXPECT_EQ(9u, length);
  8073. sink.write("123", 3);
  8074. sink.write("456", 3);
  8075. sink.write("789", 3);
  8076. return true;
  8077. },
  8078. "text/plain",
  8079. [&body](const char *data, size_t data_length) {
  8080. body.append(data, data_length);
  8081. return true;
  8082. });
  8083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8084. EXPECT_EQ(StatusCode::OK_200, res->status);
  8085. EXPECT_EQ("123456789", body);
  8086. }
  8087. TEST_F(ServerTest, PatchLoopBack) {
  8088. std::string body;
  8089. auto res = cli_.Patch(
  8090. "/patch-loopback", 9,
  8091. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8092. EXPECT_EQ(9u, length);
  8093. sink.write("123", 3);
  8094. sink.write("456", 3);
  8095. sink.write("789", 3);
  8096. return true;
  8097. },
  8098. "text/plain",
  8099. [&body](const char *data, size_t data_length) {
  8100. body.append(data, data_length);
  8101. return true;
  8102. });
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ("123456789", body);
  8106. }
  8107. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8108. std::string body;
  8109. auto res = cli_.Post(
  8110. "/post-loopback",
  8111. [](size_t /*offset*/, DataSink &sink) {
  8112. sink.write("123", 3);
  8113. sink.write("456", 3);
  8114. sink.write("789", 3);
  8115. sink.done();
  8116. return true;
  8117. },
  8118. "text/plain",
  8119. [&body](const char *data, size_t data_length) {
  8120. body.append(data, data_length);
  8121. return true;
  8122. });
  8123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8124. EXPECT_EQ(StatusCode::OK_200, res->status);
  8125. EXPECT_EQ("123456789", body);
  8126. }
  8127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8128. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8129. cli_.set_compress(true);
  8130. auto res = cli_.Put(
  8131. "/put", 3,
  8132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8133. sink.os << "PUT";
  8134. return true;
  8135. },
  8136. "text/plain");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::OK_200, res->status);
  8139. EXPECT_EQ("PUT", res->body);
  8140. }
  8141. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8142. cli_.set_compress(true);
  8143. auto res = cli_.Post(
  8144. "/post", 42,
  8145. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8146. return false;
  8147. },
  8148. "text/plain");
  8149. ASSERT_TRUE(!res);
  8150. EXPECT_EQ(Error::Canceled, res.error());
  8151. }
  8152. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8153. cli_.set_compress(true);
  8154. auto res = cli_.Put(
  8155. "/put",
  8156. [](size_t /*offset*/, DataSink &sink) {
  8157. sink.os << "PUT";
  8158. sink.done();
  8159. return true;
  8160. },
  8161. "text/plain");
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ(StatusCode::OK_200, res->status);
  8164. EXPECT_EQ("PUT", res->body);
  8165. }
  8166. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8167. cli_.set_compress(true);
  8168. auto res = cli_.Post(
  8169. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8170. "text/plain");
  8171. ASSERT_TRUE(!res);
  8172. EXPECT_EQ(Error::Canceled, res.error());
  8173. }
  8174. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8175. cli_.set_compress(true);
  8176. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. EXPECT_EQ(LARGE_DATA, res->body);
  8180. }
  8181. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8182. #ifdef CPPHTTPLIB_SSL_ENABLED
  8183. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8184. Client cli(s.c_str());
  8185. cli.enable_server_certificate_verification(false);
  8186. #else
  8187. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8188. Client cli(s.c_str());
  8189. #endif
  8190. cli.set_compress(true);
  8191. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. EXPECT_EQ(LARGE_DATA, res->body);
  8195. // The compressed size should be less than a 10th of the original. May vary
  8196. // depending on the zlib library.
  8197. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8198. static_cast<uint64_t>(10 * 1024 * 1024));
  8199. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8200. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8201. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8202. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8203. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8204. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8205. #endif
  8206. }
  8207. TEST_F(ServerTest, PutContentWithDeflate) {
  8208. cli_.set_compress(false);
  8209. Headers headers;
  8210. headers.emplace("Content-Encoding", "deflate");
  8211. // PUT in deflate format:
  8212. auto res = cli_.Put("/put", headers,
  8213. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::OK_200, res->status);
  8216. EXPECT_EQ("PUT", res->body);
  8217. }
  8218. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8219. Headers headers;
  8220. headers.emplace("Accept-Encoding", "gzip, deflate");
  8221. auto res = cli_.Get("/streamed-chunked", headers);
  8222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8223. EXPECT_EQ(StatusCode::OK_200, res->status);
  8224. EXPECT_EQ(std::string("123456789"), res->body);
  8225. }
  8226. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8227. Headers headers;
  8228. headers.emplace("Accept-Encoding", "gzip, deflate");
  8229. auto res = cli_.Get("/streamed-chunked2", headers);
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::OK_200, res->status);
  8232. EXPECT_EQ(std::string("123456789"), res->body);
  8233. }
  8234. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8235. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8237. EXPECT_EQ(StatusCode::OK_200, res->status);
  8238. }
  8239. TEST(GzipDecompressor, ChunkedDecompression) {
  8240. std::string data;
  8241. for (size_t i = 0; i < 32 * 1024; ++i) {
  8242. data.push_back(static_cast<char>('a' + i % 26));
  8243. }
  8244. std::string compressed_data;
  8245. {
  8246. httplib::detail::gzip_compressor compressor;
  8247. bool result = compressor.compress(
  8248. data.data(), data.size(),
  8249. /*last=*/true,
  8250. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8251. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8252. compressed_data_size);
  8253. return true;
  8254. });
  8255. ASSERT_TRUE(result);
  8256. }
  8257. std::string decompressed_data;
  8258. {
  8259. httplib::detail::gzip_decompressor decompressor;
  8260. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8261. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8262. size_t chunk_size = 130;
  8263. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8264. chunk_begin += chunk_size) {
  8265. size_t current_chunk_size =
  8266. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8267. bool result = decompressor.decompress(
  8268. compressed_data.data() + chunk_begin, current_chunk_size,
  8269. [&](const char *decompressed_data_chunk,
  8270. size_t decompressed_data_chunk_size) {
  8271. decompressed_data.insert(decompressed_data.size(),
  8272. decompressed_data_chunk,
  8273. decompressed_data_chunk_size);
  8274. return true;
  8275. });
  8276. ASSERT_TRUE(result);
  8277. }
  8278. }
  8279. ASSERT_EQ(data, decompressed_data);
  8280. }
  8281. TEST(GzipDecompressor, DeflateDecompression) {
  8282. std::string original_text = "Raw deflate without gzip";
  8283. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8284. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8285. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8286. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8287. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8288. std::string decompressed_data;
  8289. {
  8290. httplib::detail::gzip_decompressor decompressor;
  8291. bool result = decompressor.decompress(
  8292. compressed_data.data(), compressed_data.size(),
  8293. [&](const char *decompressed_data_chunk,
  8294. size_t decompressed_data_chunk_size) {
  8295. decompressed_data.insert(decompressed_data.size(),
  8296. decompressed_data_chunk,
  8297. decompressed_data_chunk_size);
  8298. return true;
  8299. });
  8300. ASSERT_TRUE(result);
  8301. }
  8302. ASSERT_EQ(original_text, decompressed_data);
  8303. }
  8304. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8305. std::string original_text = "Raw deflate without gzip";
  8306. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8307. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8308. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8309. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8310. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8311. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8312. std::string decompressed_data;
  8313. {
  8314. httplib::detail::gzip_decompressor decompressor;
  8315. bool result = decompressor.decompress(
  8316. compressed_data.data(), compressed_data.size(),
  8317. [&](const char *decompressed_data_chunk,
  8318. size_t decompressed_data_chunk_size) {
  8319. decompressed_data.insert(decompressed_data.size(),
  8320. decompressed_data_chunk,
  8321. decompressed_data_chunk_size);
  8322. return true;
  8323. });
  8324. ASSERT_TRUE(result);
  8325. }
  8326. ASSERT_EQ(original_text, decompressed_data);
  8327. }
  8328. #endif
  8329. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8330. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8331. Headers headers;
  8332. headers.emplace("Accept-Encoding", "br");
  8333. auto res = cli_.Get("/streamed-chunked", headers);
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ(StatusCode::OK_200, res->status);
  8336. EXPECT_EQ(std::string("123456789"), res->body);
  8337. }
  8338. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8339. Headers headers;
  8340. headers.emplace("Accept-Encoding", "br");
  8341. auto res = cli_.Get("/streamed-chunked2", headers);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::OK_200, res->status);
  8344. EXPECT_EQ(std::string("123456789"), res->body);
  8345. }
  8346. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8347. cli_.set_compress(true);
  8348. auto res = cli_.Put(
  8349. "/put", 3,
  8350. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8351. sink.os << "PUT";
  8352. return true;
  8353. },
  8354. "text/plain");
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("PUT", res->body);
  8358. }
  8359. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8360. cli_.set_compress(true);
  8361. auto res = cli_.Put(
  8362. "/put",
  8363. [](size_t /*offset*/, DataSink &sink) {
  8364. sink.os << "PUT";
  8365. sink.done();
  8366. return true;
  8367. },
  8368. "text/plain");
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. EXPECT_EQ("PUT", res->body);
  8372. }
  8373. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8374. cli_.set_compress(true);
  8375. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. EXPECT_EQ(LARGE_DATA, res->body);
  8379. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8380. }
  8381. #endif
  8382. TEST_F(ServerTest, Patch) {
  8383. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. EXPECT_EQ("PATCH", res->body);
  8387. }
  8388. TEST_F(ServerTest, Delete) {
  8389. auto res = cli_.Delete("/delete");
  8390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8391. EXPECT_EQ(StatusCode::OK_200, res->status);
  8392. EXPECT_EQ("DELETE", res->body);
  8393. }
  8394. TEST_F(ServerTest, DeleteContentReceiver) {
  8395. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_EQ(StatusCode::OK_200, res->status);
  8398. EXPECT_EQ("content", res->body);
  8399. }
  8400. TEST_F(ServerTest, Options) {
  8401. auto res = cli_.Options("*");
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8405. EXPECT_TRUE(res->body.empty());
  8406. }
  8407. TEST_F(ServerTest, URL) {
  8408. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. }
  8412. TEST_F(ServerTest, ArrayParam) {
  8413. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::OK_200, res->status);
  8416. }
  8417. TEST_F(ServerTest, ArrayParamValues) {
  8418. auto res =
  8419. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. }
  8423. TEST_F(ServerTest, NoMultipleHeaders) {
  8424. Headers headers = {{"Content-Length", "5"}};
  8425. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8426. "text/plain");
  8427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8428. EXPECT_EQ(StatusCode::OK_200, res->status);
  8429. }
  8430. TEST_F(ServerTest, PostContentReceiver) {
  8431. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. ASSERT_EQ(StatusCode::OK_200, res->status);
  8434. ASSERT_EQ("content", res->body);
  8435. }
  8436. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8437. UploadFormDataItems items = {
  8438. {"text1", "text default", "", ""},
  8439. {"text2", "aωb", "", ""},
  8440. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8441. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8442. {"file3", "", "", "application/octet-stream"},
  8443. };
  8444. auto res = cli_.Post("/content_receiver", items);
  8445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8449. UploadFormDataItems items = {
  8450. {"text1", "text default", "", ""},
  8451. {"text2", "aωb", "", ""},
  8452. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8453. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8454. {"file3", "", "", "application/octet-stream"},
  8455. };
  8456. auto boundary = std::string("+++++");
  8457. std::string body;
  8458. for (const auto &item : items) {
  8459. body += "--" + boundary + "\r\n";
  8460. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8461. if (!item.filename.empty()) {
  8462. body += "; filename=\"" + item.filename + "\"";
  8463. }
  8464. body += "\r\n";
  8465. if (!item.content_type.empty()) {
  8466. body += "Content-Type: " + item.content_type + "\r\n";
  8467. }
  8468. body += "\r\n";
  8469. body += item.content + "\r\n";
  8470. }
  8471. body += "--" + boundary + "--\r\n";
  8472. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8473. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8475. EXPECT_EQ(StatusCode::OK_200, res->status);
  8476. }
  8477. TEST(MultipartFormDataTest, FieldEscaping) {
  8478. Server svr;
  8479. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8480. const ContentReader &content_reader) {
  8481. ASSERT_TRUE(req.is_multipart_form_data());
  8482. std::vector<FormData> received;
  8483. content_reader(
  8484. [&](const FormData &file) {
  8485. received.push_back(file);
  8486. return true;
  8487. },
  8488. [&](const char *data, size_t data_length) {
  8489. received.back().content.append(data, data_length);
  8490. return true;
  8491. });
  8492. // '"', CR and LF in names and filenames are escaped following the
  8493. // WHATWG HTML standard, so each part still parses as a single part
  8494. // with no injected headers. Content types get CR/LF escaped too,
  8495. // while '"' (legal there, e.g. quoted charset) is preserved.
  8496. ASSERT_EQ(4U, received.size());
  8497. EXPECT_EQ("na%22me", received[0].name);
  8498. EXPECT_EQ("quoted name", received[0].content);
  8499. EXPECT_EQ("file", received[1].name);
  8500. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8501. received[1].filename);
  8502. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8503. EXPECT_EQ("injected", received[1].content);
  8504. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8505. EXPECT_EQ("my%22file.txt", received[2].filename);
  8506. EXPECT_EQ("cr lf name", received[2].content);
  8507. EXPECT_EQ("typed", received[3].name);
  8508. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8509. received[3].content_type);
  8510. EXPECT_EQ("typed content", received[3].content);
  8511. });
  8512. auto port = svr.bind_to_any_port("localhost");
  8513. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8514. auto se = detail::scope_exit([&] {
  8515. svr.stop();
  8516. t.join();
  8517. ASSERT_FALSE(svr.is_running());
  8518. });
  8519. svr.wait_until_ready();
  8520. Client cli("localhost", port);
  8521. UploadFormDataItems items = {
  8522. {"na\"me", "quoted name", "", ""},
  8523. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8524. "application/octet-stream"},
  8525. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8526. {"typed", "typed content", "",
  8527. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8528. };
  8529. auto res = cli.Post("/post", items);
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8534. const UploadFormDataItems items = {
  8535. {"name1", "Content 1", "", ""},
  8536. {"name2", "Content 2", "file2.txt", "text/plain"},
  8537. };
  8538. Server svr;
  8539. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8540. const ContentReader &content_reader) {
  8541. ASSERT_TRUE(req.is_multipart_form_data());
  8542. std::vector<FormData> received;
  8543. content_reader(
  8544. [&](const FormData &file) {
  8545. received.push_back(file);
  8546. return true;
  8547. },
  8548. [&](const char *data, size_t data_length) {
  8549. received.back().content.append(data, data_length);
  8550. return true;
  8551. });
  8552. ASSERT_EQ(2U, received.size());
  8553. EXPECT_EQ("name1", received[0].name);
  8554. EXPECT_EQ("Content 1", received[0].content);
  8555. EXPECT_EQ("name2", received[1].name);
  8556. EXPECT_EQ("Content 2", received[1].content);
  8557. EXPECT_EQ("file2.txt", received[1].filename);
  8558. EXPECT_EQ("text/plain", received[1].content_type);
  8559. });
  8560. auto port = svr.bind_to_any_port("localhost");
  8561. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. t.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. });
  8567. svr.wait_until_ready();
  8568. Client cli("localhost", port);
  8569. // Whole-body serialization with a generated boundary
  8570. {
  8571. MultipartFormDataWriter writer;
  8572. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8573. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8574. writer.content_type());
  8575. auto body = writer.serialize(items);
  8576. EXPECT_EQ(body.size(), writer.content_length(items));
  8577. auto res = cli.Post("/post", body, writer.content_type());
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. // Per-part framing with a custom boundary via a content provider
  8582. {
  8583. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8584. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8585. MultipartFormDataWriter writer("custom-boundary_123");
  8586. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8587. std::string body;
  8588. for (const auto &item : items) {
  8589. body += writer.item_begin(item);
  8590. body += item.content;
  8591. body += MultipartFormDataWriter::item_end();
  8592. }
  8593. body += writer.finish();
  8594. EXPECT_EQ(body.size(), writer.content_length(items));
  8595. auto res = cli.Post(
  8596. "/post", body.size(),
  8597. [&](size_t offset, size_t length, DataSink &sink) {
  8598. sink.write(body.data() + offset, length);
  8599. return true;
  8600. },
  8601. writer.content_type());
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. }
  8605. }
  8606. TEST_F(ServerTest, PostContentReceiverGzip) {
  8607. cli_.set_compress(true);
  8608. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. ASSERT_EQ(StatusCode::OK_200, res->status);
  8611. ASSERT_EQ("content", res->body);
  8612. }
  8613. TEST_F(ServerTest, PutContentReceiver) {
  8614. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. ASSERT_EQ(StatusCode::OK_200, res->status);
  8617. ASSERT_EQ("content", res->body);
  8618. }
  8619. TEST_F(ServerTest, PatchContentReceiver) {
  8620. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. ASSERT_EQ(StatusCode::OK_200, res->status);
  8623. ASSERT_EQ("content", res->body);
  8624. }
  8625. template <typename ClientType>
  8626. void TestWithHeadersAndContentReceiver(
  8627. ClientType &cli,
  8628. std::function<Result(ClientType &, const std::string &, const Headers &,
  8629. const std::string &, const std::string &,
  8630. ContentReceiver, DownloadProgress)>
  8631. request_func) {
  8632. Headers headers;
  8633. headers.emplace("X-Custom-Header", "test-value");
  8634. std::string received_body;
  8635. auto res = request_func(
  8636. cli, "/content_receiver", headers, "content", "application/json",
  8637. [&](const char *data, size_t data_length) {
  8638. received_body.append(data, data_length);
  8639. return true;
  8640. },
  8641. nullptr);
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ("content", received_body);
  8645. }
  8646. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8647. #ifdef CPPHTTPLIB_SSL_ENABLED
  8648. using ClientT = SSLClient;
  8649. #else
  8650. using ClientT = Client;
  8651. #endif
  8652. TestWithHeadersAndContentReceiver<ClientT>(
  8653. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8654. const std::string &body, const std::string &content_type,
  8655. ContentReceiver receiver, DownloadProgress progress) {
  8656. return cli.Post(path, headers, body, content_type, receiver, progress);
  8657. });
  8658. }
  8659. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8660. #ifdef CPPHTTPLIB_SSL_ENABLED
  8661. using ClientT = SSLClient;
  8662. #else
  8663. using ClientT = Client;
  8664. #endif
  8665. TestWithHeadersAndContentReceiver<ClientT>(
  8666. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8667. const std::string &body, const std::string &content_type,
  8668. ContentReceiver receiver, DownloadProgress progress) {
  8669. return cli.Put(path, headers, body, content_type, receiver, progress);
  8670. });
  8671. }
  8672. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8673. #ifdef CPPHTTPLIB_SSL_ENABLED
  8674. using ClientT = SSLClient;
  8675. #else
  8676. using ClientT = Client;
  8677. #endif
  8678. TestWithHeadersAndContentReceiver<ClientT>(
  8679. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8680. const std::string &body, const std::string &content_type,
  8681. ContentReceiver receiver, DownloadProgress progress) {
  8682. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8683. });
  8684. }
  8685. template <typename ClientType>
  8686. void TestWithHeadersAndContentReceiverWithProgress(
  8687. ClientType &cli,
  8688. std::function<Result(ClientType &, const std::string &, const Headers &,
  8689. const std::string &, const std::string &,
  8690. ContentReceiver, DownloadProgress)>
  8691. request_func) {
  8692. Headers headers;
  8693. headers.emplace("X-Test-Header", "progress-test");
  8694. std::string received_body;
  8695. auto progress_called = false;
  8696. auto res = request_func(
  8697. cli, "/content_receiver", headers, "content", "text/plain",
  8698. [&](const char *data, size_t data_length) {
  8699. received_body.append(data, data_length);
  8700. return true;
  8701. },
  8702. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8703. progress_called = true;
  8704. return true;
  8705. });
  8706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8707. EXPECT_EQ(StatusCode::OK_200, res->status);
  8708. EXPECT_EQ("content", received_body);
  8709. EXPECT_TRUE(progress_called);
  8710. }
  8711. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8712. #ifdef CPPHTTPLIB_SSL_ENABLED
  8713. using ClientT = SSLClient;
  8714. #else
  8715. using ClientT = Client;
  8716. #endif
  8717. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8719. const std::string &body, const std::string &content_type,
  8720. ContentReceiver receiver, DownloadProgress progress) {
  8721. return cli.Post(path, headers, body, content_type, receiver, progress);
  8722. });
  8723. }
  8724. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8725. #ifdef CPPHTTPLIB_SSL_ENABLED
  8726. using ClientT = SSLClient;
  8727. #else
  8728. using ClientT = Client;
  8729. #endif
  8730. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8732. const std::string &body, const std::string &content_type,
  8733. ContentReceiver receiver, DownloadProgress progress) {
  8734. return cli.Put(path, headers, body, content_type, receiver, progress);
  8735. });
  8736. }
  8737. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8738. #ifdef CPPHTTPLIB_SSL_ENABLED
  8739. using ClientT = SSLClient;
  8740. #else
  8741. using ClientT = Client;
  8742. #endif
  8743. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8744. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8745. const std::string &body, const std::string &content_type,
  8746. ContentReceiver receiver, DownloadProgress progress) {
  8747. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8748. });
  8749. }
  8750. template <typename ClientType>
  8751. void TestWithHeadersAndContentReceiverError(
  8752. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8753. const Headers &, const std::string &,
  8754. const std::string &, ContentReceiver)>
  8755. request_func) {
  8756. Headers headers;
  8757. headers.emplace("X-Error-Test", "true");
  8758. std::string received_body;
  8759. auto receiver_failed = false;
  8760. auto res =
  8761. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8762. [&](const char *data, size_t data_length) {
  8763. received_body.append(data, data_length);
  8764. receiver_failed = true;
  8765. return false;
  8766. });
  8767. ASSERT_FALSE(res);
  8768. EXPECT_TRUE(receiver_failed);
  8769. }
  8770. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8771. #ifdef CPPHTTPLIB_SSL_ENABLED
  8772. using ClientT = SSLClient;
  8773. #else
  8774. using ClientT = Client;
  8775. #endif
  8776. TestWithHeadersAndContentReceiverError<ClientT>(
  8777. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8778. const std::string &body, const std::string &content_type,
  8779. ContentReceiver receiver) {
  8780. return cli.Post(path, headers, body, content_type, receiver);
  8781. });
  8782. }
  8783. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8784. #ifdef CPPHTTPLIB_SSL_ENABLED
  8785. using ClientT = SSLClient;
  8786. #else
  8787. using ClientT = Client;
  8788. #endif
  8789. TestWithHeadersAndContentReceiverError<ClientT>(
  8790. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8791. const std::string &body, const std::string &content_type,
  8792. ContentReceiver receiver) {
  8793. return cli.Put(path, headers, body, content_type, receiver);
  8794. });
  8795. }
  8796. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8797. #ifdef CPPHTTPLIB_SSL_ENABLED
  8798. using ClientT = SSLClient;
  8799. #else
  8800. using ClientT = Client;
  8801. #endif
  8802. TestWithHeadersAndContentReceiverError<ClientT>(
  8803. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8804. const std::string &body, const std::string &content_type,
  8805. ContentReceiver receiver) {
  8806. return cli.Patch(path, headers, body, content_type, receiver);
  8807. });
  8808. }
  8809. TEST_F(ServerTest, PostQueryStringAndBody) {
  8810. auto res =
  8811. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8813. ASSERT_EQ(StatusCode::OK_200, res->status);
  8814. }
  8815. TEST_F(ServerTest, HTTP2Magic) {
  8816. Request req;
  8817. req.method = "PRI";
  8818. req.path = "*";
  8819. req.body = "SM";
  8820. auto res = std::make_shared<Response>();
  8821. auto error = Error::Success;
  8822. auto ret = cli_.send(req, *res, error);
  8823. ASSERT_TRUE(ret);
  8824. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8825. }
  8826. TEST_F(ServerTest, KeepAlive) {
  8827. auto res = cli_.Get("/hi");
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ(StatusCode::OK_200, res->status);
  8830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8831. EXPECT_EQ("Hello World!", res->body);
  8832. res = cli_.Get("/hi");
  8833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8834. EXPECT_EQ(StatusCode::OK_200, res->status);
  8835. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8836. EXPECT_EQ("Hello World!", res->body);
  8837. res = cli_.Get("/hi");
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8841. EXPECT_EQ("Hello World!", res->body);
  8842. res = cli_.Get("/not-exist");
  8843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8845. res = cli_.Post("/empty", "", "text/plain");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("empty", res->body);
  8850. EXPECT_EQ("close", res->get_header_value("Connection"));
  8851. res = cli_.Post(
  8852. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8853. "text/plain");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ(StatusCode::OK_200, res->status);
  8856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8857. EXPECT_EQ("empty", res->body);
  8858. cli_.set_keep_alive(false);
  8859. res = cli_.Get("/last-request");
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ(StatusCode::OK_200, res->status);
  8862. EXPECT_EQ("close", res->get_header_value("Connection"));
  8863. }
  8864. TEST_F(ServerTest, TooManyRedirect) {
  8865. cli_.set_follow_location(true);
  8866. auto res = cli_.Get("/redirect/0");
  8867. ASSERT_TRUE(!res);
  8868. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8869. }
  8870. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8871. Request req;
  8872. req.method = "FOOBAR";
  8873. req.path = "/hi";
  8874. cli_.set_keep_alive(true);
  8875. auto res = cli_.send(req);
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8878. EXPECT_EQ("close", res->get_header_value("Connection"));
  8879. EXPECT_FALSE(cli_.is_socket_open());
  8880. }
  8881. TEST_F(ServerTest, CustomRouteReadsBody) {
  8882. const std::string xml =
  8883. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8884. Request req;
  8885. req.method = "PROPFIND";
  8886. req.path = "/dav/dir";
  8887. req.set_header("Depth", "1");
  8888. req.body = xml;
  8889. auto res = cli_.send(req);
  8890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8891. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8892. EXPECT_EQ(xml, res->body);
  8893. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8894. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8895. }
  8896. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8897. Request req;
  8898. req.method = "PROPFIND";
  8899. req.path = "/dav/42";
  8900. auto res = cli_.send(req);
  8901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8902. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8903. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8904. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8905. }
  8906. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8907. Request req;
  8908. req.method = "PROPFIND";
  8909. req.path = "/dav-re/123";
  8910. auto res = cli_.send(req);
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8913. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8914. }
  8915. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8916. Request req;
  8917. req.method = "MKCOL";
  8918. req.path = "/dav-mkcol";
  8919. auto res = cli_.send(req);
  8920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8921. EXPECT_EQ(StatusCode::Created_201, res->status);
  8922. }
  8923. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8924. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8925. Request req;
  8926. req.method = "REPORT";
  8927. req.path = "/dav-report";
  8928. req.body = xml;
  8929. auto res = cli_.send(req);
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8932. EXPECT_EQ(xml, res->body);
  8933. }
  8934. // A content reader route must fire even when the request carries no body,
  8935. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8936. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8937. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8938. Request req;
  8939. req.method = "REPORT";
  8940. req.path = "/dav-report";
  8941. auto res = cli_.send(req);
  8942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8943. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8944. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8945. }
  8946. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8947. Request req;
  8948. req.method = "PROPFIND";
  8949. req.path = "/not-dav";
  8950. auto res = cli_.send(req);
  8951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8953. }
  8954. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8955. Request req;
  8956. req.method = "UNLOCK";
  8957. req.path = "/dav/dir";
  8958. cli_.set_keep_alive(true);
  8959. auto res = cli_.send(req);
  8960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8962. EXPECT_EQ("close", res->get_header_value("Connection"));
  8963. EXPECT_FALSE(cli_.is_socket_open());
  8964. }
  8965. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8966. // The mount point serves this path, but only for GET and HEAD.
  8967. auto get_res = cli_.Get("/dir/index.html");
  8968. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8969. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8970. Request req;
  8971. req.method = "PROPFIND";
  8972. req.path = "/dir/index.html";
  8973. auto res = cli_.send(req);
  8974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8975. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8976. }
  8977. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8978. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8979. cli_.set_keep_alive(true);
  8980. for (auto i = 0; i < 2; i++) {
  8981. Request req;
  8982. req.method = "PROPFIND";
  8983. req.path = "/dav/dir";
  8984. req.body = xml;
  8985. auto res = cli_.send(req);
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8988. EXPECT_EQ(xml, res->body);
  8989. EXPECT_TRUE(cli_.is_socket_open());
  8990. }
  8991. // A built-in method must still be served on the same connection.
  8992. cli_.set_keep_alive(false);
  8993. auto res = cli_.Get("/hi");
  8994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8995. EXPECT_EQ(StatusCode::OK_200, res->status);
  8996. EXPECT_EQ("close", res->get_header_value("Connection"));
  8997. }
  8998. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8999. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9000. Request req;
  9001. req.method = "PROPFIND";
  9002. req.path = "/dav/dir";
  9003. req.set_header("Expect", "100-continue");
  9004. req.body = xml;
  9005. auto res = cli_.send(req);
  9006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9007. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9008. EXPECT_EQ(xml, res->body);
  9009. }
  9010. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9011. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9012. TEST_F(ServerTest, Gzip) {
  9013. Headers headers;
  9014. headers.emplace("Accept-Encoding", "gzip, deflate");
  9015. auto res = cli_.Get("/compress", headers);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9019. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9020. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9021. "7890123456789012345678901234567890",
  9022. res->body);
  9023. EXPECT_EQ(StatusCode::OK_200, res->status);
  9024. }
  9025. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9026. Headers headers;
  9027. headers.emplace("Accept-Encoding", "gzip, deflate");
  9028. auto res = cli_.Get("/compress-with-charset", headers);
  9029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9031. EXPECT_EQ("application/json; charset=utf-8",
  9032. res->get_header_value("Content-Type"));
  9033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9034. "7890123456789012345678901234567890",
  9035. res->body);
  9036. EXPECT_EQ(StatusCode::OK_200, res->status);
  9037. }
  9038. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9039. Headers headers;
  9040. headers.emplace("Accept-Encoding", "");
  9041. auto res = cli_.Get("/compress", headers);
  9042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9043. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9047. "7890123456789012345678901234567890",
  9048. res->body);
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. }
  9051. TEST_F(ServerTest, GzipWithContentReceiver) {
  9052. Headers headers;
  9053. headers.emplace("Accept-Encoding", "gzip, deflate");
  9054. std::string body;
  9055. auto res =
  9056. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9057. EXPECT_EQ(100U, data_length);
  9058. body.append(data, data_length);
  9059. return true;
  9060. });
  9061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9062. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9063. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9064. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9065. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9066. "7890123456789012345678901234567890",
  9067. body);
  9068. EXPECT_EQ(StatusCode::OK_200, res->status);
  9069. }
  9070. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9071. Headers headers;
  9072. headers.emplace("Accept-Encoding", "gzip, deflate");
  9073. cli_.set_decompress(false);
  9074. auto res = cli_.Get("/compress", headers);
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9078. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9079. EXPECT_EQ(33U, res->body.size());
  9080. EXPECT_EQ(StatusCode::OK_200, res->status);
  9081. }
  9082. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9083. Headers headers;
  9084. headers.emplace("Accept-Encoding", "");
  9085. std::string body;
  9086. auto res =
  9087. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9088. EXPECT_EQ(100U, data_length);
  9089. body.append(data, data_length);
  9090. return true;
  9091. });
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9095. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9096. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9097. "7890123456789012345678901234567890",
  9098. body);
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. }
  9101. TEST_F(ServerTest, NoGzip) {
  9102. Headers headers;
  9103. headers.emplace("Accept-Encoding", "gzip, deflate");
  9104. auto res = cli_.Get("/nocompress", headers);
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9107. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9108. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9109. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9110. "7890123456789012345678901234567890",
  9111. res->body);
  9112. EXPECT_EQ(StatusCode::OK_200, res->status);
  9113. }
  9114. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9115. Headers headers;
  9116. headers.emplace("Accept-Encoding", "gzip, deflate");
  9117. std::string body;
  9118. auto res = cli_.Get("/nocompress", headers,
  9119. [&](const char *data, size_t data_length) {
  9120. EXPECT_EQ(100U, data_length);
  9121. body.append(data, data_length);
  9122. return true;
  9123. });
  9124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9125. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9126. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9127. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9128. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9129. "7890123456789012345678901234567890",
  9130. body);
  9131. EXPECT_EQ(StatusCode::OK_200, res->status);
  9132. }
  9133. TEST_F(ServerTest, MultipartFormDataGzip) {
  9134. UploadFormDataItems items = {
  9135. {"key1", "test", "", ""},
  9136. {"key2", "--abcdefg123", "", ""},
  9137. };
  9138. cli_.set_compress(true);
  9139. auto res = cli_.Post("/compress-multipart", items);
  9140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. }
  9143. #endif
  9144. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9145. // Static file compression is opt-in, so these run their own server rather than
  9146. // flipping it on for the shared ServerTest fixture, which would silently
  9147. // rewrite what every other static file test is asserting.
  9148. class StaticFileCompressionTest : public ::testing::Test {
  9149. protected:
  9150. void TearDown() override {
  9151. if (t_.joinable()) {
  9152. svr_.stop();
  9153. t_.join();
  9154. }
  9155. }
  9156. int start(const std::function<void(Server &)> &configure = nullptr) {
  9157. // Serves the same tree as a directory of build-time compressed assets
  9158. // would be served: the mount point names the coding the files are already
  9159. // stored in. Registered before "/" so it is the one that matches.
  9160. svr_.set_mount_point("/pre-encoded", "./www",
  9161. {{"Content-Encoding", "gzip"}});
  9162. svr_.set_mount_point("/", "./www");
  9163. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9164. res.set_file_content("./www/dir/index.html", "text/html");
  9165. });
  9166. svr_.Get("/pre-encoded-file-content",
  9167. [](const Request & /*req*/, Response &res) {
  9168. res.set_header("Content-Encoding", "gzip");
  9169. res.set_file_content("./www/dir/index.html", "text/html");
  9170. });
  9171. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9172. res.set_content_provider(
  9173. 6, "text/plain",
  9174. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9175. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9176. return true;
  9177. });
  9178. });
  9179. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9180. res.set_content_provider(
  9181. 1000, "text/plain",
  9182. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9183. if (offset < 100) {
  9184. std::string data(100, 'A');
  9185. sink.write(data.data(), data.size());
  9186. return true;
  9187. }
  9188. std::this_thread::sleep_for(std::chrono::seconds(2));
  9189. std::string data(900, 'B');
  9190. sink.write(data.data(), data.size());
  9191. return true;
  9192. });
  9193. });
  9194. if (configure) { configure(svr_); }
  9195. auto port = svr_.bind_to_any_port(HOST);
  9196. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9197. svr_.wait_until_ready();
  9198. return port;
  9199. }
  9200. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9201. // Every file under ./www except 1MB.txt is smaller than the default
  9202. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9203. // it out of the way.
  9204. static void enable_without_floor(Server &svr) {
  9205. svr.set_static_file_compression(true);
  9206. svr.set_static_file_compression_min_length(0);
  9207. }
  9208. Server svr_;
  9209. std::thread t_;
  9210. };
  9211. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9212. auto port = start();
  9213. Client cli(HOST, port);
  9214. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9216. EXPECT_EQ(StatusCode::OK_200, res->status);
  9217. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9218. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9219. EXPECT_EQ(1048576U, res->body.size());
  9220. }
  9221. TEST_F(StaticFileCompressionTest, MountPoint) {
  9222. auto port = start(enable);
  9223. Client cli(HOST, port);
  9224. cli.set_decompress(false);
  9225. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. EXPECT_EQ(StatusCode::OK_200, res->status);
  9228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9229. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9230. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9231. // The response stays self-delimiting: a length, not a chunked body.
  9232. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9233. EXPECT_EQ(std::to_string(res->body.size()),
  9234. res->get_header_value("Content-Length"));
  9235. EXPECT_LT(res->body.size(), 1048576U);
  9236. EXPECT_FALSE(res->body.empty());
  9237. }
  9238. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9239. auto port = start(enable);
  9240. Client cli(HOST, port);
  9241. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9243. EXPECT_EQ(StatusCode::OK_200, res->status);
  9244. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9245. EXPECT_EQ(1048576U, res->body.size());
  9246. }
  9247. TEST_F(StaticFileCompressionTest, FileContent) {
  9248. auto port = start(enable_without_floor);
  9249. Client cli(HOST, port);
  9250. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9252. EXPECT_EQ(StatusCode::OK_200, res->status);
  9253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9254. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9255. EXPECT_EQ(104U, res->body.size());
  9256. }
  9257. // A handler that serves an already-encoded file names the coding itself. The
  9258. // file-backed path decided its coding from Accept-Encoding and the content
  9259. // type alone, so it compressed the stored bytes a second time and appended a
  9260. // second Content-Encoding field line.
  9261. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9262. auto port = start(enable_without_floor);
  9263. Client cli(HOST, port);
  9264. cli.set_decompress(false);
  9265. auto res = cli.Get("/pre-encoded-file-content",
  9266. Headers{{"Accept-Encoding", "gzip"}});
  9267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9268. EXPECT_EQ(StatusCode::OK_200, res->status);
  9269. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9270. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9271. // Vary belongs to a coding the server chose, and it chose none here.
  9272. EXPECT_FALSE(res->has_header("Vary"));
  9273. // The file travels exactly as it is stored on disk.
  9274. EXPECT_EQ(104U, res->body.size());
  9275. }
  9276. // The 1MB file clears the default floor, so this one runs the configuration a
  9277. // deployment would actually have.
  9278. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9279. auto port = start(enable);
  9280. Client cli(HOST, port);
  9281. cli.set_decompress(false);
  9282. auto res =
  9283. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9285. EXPECT_EQ(StatusCode::OK_200, res->status);
  9286. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9288. EXPECT_FALSE(res->has_header("Vary"));
  9289. EXPECT_EQ(1048576U, res->body.size());
  9290. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9291. }
  9292. TEST_F(StaticFileCompressionTest, Head) {
  9293. auto port = start(enable);
  9294. Client cli(HOST, port);
  9295. cli.set_decompress(false);
  9296. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9297. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9298. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9300. EXPECT_EQ(StatusCode::OK_200, res->status);
  9301. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9302. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9303. // HEAD still reports the size a GET would return.
  9304. EXPECT_EQ(get->get_header_value("Content-Length"),
  9305. res->get_header_value("Content-Length"));
  9306. EXPECT_TRUE(res->body.empty());
  9307. }
  9308. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9309. auto port = start(enable);
  9310. Client cli(HOST, port);
  9311. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9312. {"Accept-Encoding", "gzip"}});
  9313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9315. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9316. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9317. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9318. EXPECT_EQ("cd", res->body);
  9319. }
  9320. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9321. auto port = start(enable);
  9322. Client cli(HOST, port);
  9323. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9325. EXPECT_EQ(StatusCode::OK_200, res->status);
  9326. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9327. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9328. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9329. }
  9330. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9331. auto port = start(enable);
  9332. Client cli(HOST, port);
  9333. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9335. EXPECT_EQ(StatusCode::OK_200, res->status);
  9336. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9337. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9338. EXPECT_TRUE(res->body.empty());
  9339. }
  9340. TEST_F(StaticFileCompressionTest, MinLength) {
  9341. auto port = start(enable);
  9342. Client cli(HOST, port);
  9343. // 104 bytes, well under the default floor. Compressing it would add the
  9344. // gzip header and trailer to a body that already fits in one packet.
  9345. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9347. EXPECT_EQ(StatusCode::OK_200, res->status);
  9348. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9349. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9350. }
  9351. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9352. auto port = start([](Server &svr) {
  9353. svr.set_static_file_compression(true);
  9354. svr.set_static_file_compression_min_length(1);
  9355. });
  9356. Client cli(HOST, port);
  9357. cli.set_decompress(false);
  9358. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9360. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9361. // A 9-byte file comes back larger than it went in, because gzip's header and
  9362. // trailer outweigh anything deflate can save. That is the end of the range
  9363. // the floor exists to keep out.
  9364. EXPECT_GT(res->body.size(), 9U);
  9365. }
  9366. TEST_F(StaticFileCompressionTest, MaxLength) {
  9367. auto port = start([](Server &svr) {
  9368. svr.set_static_file_compression(true);
  9369. svr.set_static_file_compression_min_length(0);
  9370. svr.set_static_file_compression_max_length(1024);
  9371. });
  9372. Client cli(HOST, port);
  9373. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9374. // defines `small` as a macro on Windows.
  9375. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9376. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9377. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9378. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9379. // Under it: compressed.
  9380. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9381. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9382. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9383. }
  9384. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9385. auto port = start(enable_without_floor);
  9386. Client cli(HOST, port);
  9387. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9388. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9389. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9390. auto identity_etag = identity->get_header_value("ETag");
  9391. ASSERT_FALSE(identity_etag.empty());
  9392. auto gzipped =
  9393. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9394. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9395. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9396. auto gzip_etag = gzipped->get_header_value("ETag");
  9397. ASSERT_FALSE(gzip_etag.empty());
  9398. // Two representations, two validators.
  9399. EXPECT_NE(identity_etag, gzip_etag);
  9400. // Each one revalidates against the request that would produce it...
  9401. auto fresh =
  9402. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9403. {"If-None-Match", gzip_etag}});
  9404. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9405. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9406. auto fresh_identity =
  9407. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9408. {"If-None-Match", identity_etag}});
  9409. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9410. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9411. // ...and not against the other representation.
  9412. auto crossed =
  9413. cli.Get("/dir/index.html",
  9414. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9415. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9416. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9417. }
  9418. // The opt-in covers responses the server reads off disk itself. A caller's own
  9419. // known-length provider keeps its Content-Length and, more importantly, keeps
  9420. // delivering incrementally: routing it through a compressor would hold every
  9421. // write back until zlib's window filled.
  9422. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9423. auto port = start(enable);
  9424. Client cli(HOST, port);
  9425. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9429. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9430. EXPECT_EQ("aaabbb", res->body);
  9431. }
  9432. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9433. auto port = start(enable);
  9434. Client cli(HOST, port);
  9435. cli.set_read_timeout(1, 0);
  9436. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9437. Headers{{"Accept-Encoding", "gzip"}});
  9438. ASSERT_TRUE(handle.is_valid());
  9439. // The provider writes 100 bytes and then stalls for longer than the read
  9440. // timeout. Those first bytes have to arrive anyway: run the response through
  9441. // a compressor and zlib holds them until its window fills, so the read would
  9442. // come back empty instead.
  9443. char buf[256];
  9444. auto n = handle.read(buf, sizeof(buf));
  9445. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9446. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9447. }
  9448. #endif
  9449. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9450. TEST_F(ServerTest, Brotli) {
  9451. Headers headers;
  9452. headers.emplace("Accept-Encoding", "br");
  9453. auto res = cli_.Get("/compress", headers);
  9454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9455. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9457. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9458. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9459. "7890123456789012345678901234567890",
  9460. res->body);
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. }
  9463. #endif
  9464. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9465. TEST_F(ServerTest, Zstd) {
  9466. Headers headers;
  9467. headers.emplace("Accept-Encoding", "zstd");
  9468. auto res = cli_.Get("/compress", headers);
  9469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9470. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9472. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9473. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9474. "7890123456789012345678901234567890",
  9475. res->body);
  9476. EXPECT_EQ(StatusCode::OK_200, res->status);
  9477. }
  9478. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9479. Headers headers;
  9480. headers.emplace("Accept-Encoding", "");
  9481. auto res = cli_.Get("/compress", headers);
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9484. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9485. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9486. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9487. "7890123456789012345678901234567890",
  9488. res->body);
  9489. EXPECT_EQ(StatusCode::OK_200, res->status);
  9490. }
  9491. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9492. Headers headers;
  9493. headers.emplace("Accept-Encoding", "zstd");
  9494. std::string body;
  9495. auto res =
  9496. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9497. EXPECT_EQ(100U, data_length);
  9498. body.append(data, data_length);
  9499. return true;
  9500. });
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9503. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9504. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9505. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9506. "7890123456789012345678901234567890",
  9507. body);
  9508. EXPECT_EQ(StatusCode::OK_200, res->status);
  9509. }
  9510. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9511. Headers headers;
  9512. headers.emplace("Accept-Encoding", "zstd");
  9513. cli_.set_decompress(false);
  9514. auto res = cli_.Get("/compress", headers);
  9515. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9516. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9517. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9518. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9520. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9522. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9523. EXPECT_EQ(StatusCode::OK_200, res->status);
  9524. ASSERT_EQ(26U, res->body.size());
  9525. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9526. 0);
  9527. }
  9528. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9529. Headers headers;
  9530. headers.emplace("Accept-Encoding", "");
  9531. std::string body;
  9532. auto res =
  9533. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9534. EXPECT_EQ(100U, data_length);
  9535. body.append(data, data_length);
  9536. return true;
  9537. });
  9538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9539. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9541. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9542. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9543. "7890123456789012345678901234567890",
  9544. body);
  9545. EXPECT_EQ(StatusCode::OK_200, res->status);
  9546. }
  9547. TEST_F(ServerTest, NoZstd) {
  9548. Headers headers;
  9549. headers.emplace("Accept-Encoding", "zstd");
  9550. auto res = cli_.Get("/nocompress", headers);
  9551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9552. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9553. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9554. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9556. "7890123456789012345678901234567890",
  9557. res->body);
  9558. EXPECT_EQ(StatusCode::OK_200, res->status);
  9559. }
  9560. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9561. Headers headers;
  9562. headers.emplace("Accept-Encoding", "zstd");
  9563. std::string body;
  9564. auto res = cli_.Get("/nocompress", headers,
  9565. [&](const char *data, size_t data_length) {
  9566. EXPECT_EQ(100U, data_length);
  9567. body.append(data, data_length);
  9568. return true;
  9569. });
  9570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9571. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9572. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9573. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9574. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9575. "7890123456789012345678901234567890",
  9576. body);
  9577. EXPECT_EQ(StatusCode::OK_200, res->status);
  9578. }
  9579. // TODO: How to enable zstd ??
  9580. TEST_F(ServerTest, MultipartFormDataZstd) {
  9581. UploadFormDataItems items = {
  9582. {"key1", "test", "", ""},
  9583. {"key2", "--abcdefg123", "", ""},
  9584. };
  9585. Headers headers;
  9586. headers.emplace("Accept-Encoding", "zstd");
  9587. cli_.set_compress(true);
  9588. auto res = cli_.Post("/compress-multipart", headers, items);
  9589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9590. EXPECT_EQ(StatusCode::OK_200, res->status);
  9591. }
  9592. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9593. Headers headers;
  9594. headers.emplace("Accept-Encoding", "zstd");
  9595. cli_.set_compress(true);
  9596. auto res = cli_.Put(
  9597. "/put", headers, 3,
  9598. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9599. sink.os << "PUT";
  9600. return true;
  9601. },
  9602. "text/plain");
  9603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9604. EXPECT_EQ(StatusCode::OK_200, res->status);
  9605. EXPECT_EQ("PUT", res->body);
  9606. }
  9607. // Pre-compression logging tests
  9608. TEST_F(ServerTest, PreCompressionLogging) {
  9609. // Test data for compression (matches the actual /compress endpoint content)
  9610. const std::string test_content =
  9611. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9612. "3456789012345678901234567890";
  9613. // Variables to capture logging data
  9614. std::string pre_compression_body;
  9615. std::string pre_compression_content_type;
  9616. std::string pre_compression_content_encoding;
  9617. std::string post_compression_body;
  9618. std::string post_compression_content_type;
  9619. std::string post_compression_content_encoding;
  9620. // Set up pre-compression logger
  9621. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9622. const Response &res) {
  9623. pre_compression_body = res.body;
  9624. pre_compression_content_type = res.get_header_value("Content-Type");
  9625. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9626. });
  9627. // Set up post-compression logger
  9628. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9629. post_compression_body = res.body;
  9630. post_compression_content_type = res.get_header_value("Content-Type");
  9631. post_compression_content_encoding =
  9632. res.get_header_value("Content-Encoding");
  9633. });
  9634. // Test with gzip compression
  9635. Headers headers;
  9636. headers.emplace("Accept-Encoding", "gzip");
  9637. auto res = cli_.Get("/compress", headers);
  9638. // Verify response was compressed
  9639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9640. EXPECT_EQ(StatusCode::OK_200, res->status);
  9641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9642. // Verify pre-compression logger captured uncompressed content
  9643. EXPECT_EQ(test_content, pre_compression_body);
  9644. EXPECT_EQ("text/plain", pre_compression_content_type);
  9645. EXPECT_TRUE(pre_compression_content_encoding
  9646. .empty()); // No encoding header before compression
  9647. // Verify post-compression logger captured compressed content
  9648. EXPECT_NE(test_content,
  9649. post_compression_body); // Should be different after compression
  9650. EXPECT_EQ("text/plain", post_compression_content_type);
  9651. EXPECT_EQ("gzip", post_compression_content_encoding);
  9652. // Verify compressed content is smaller
  9653. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9654. }
  9655. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9656. const std::string test_content =
  9657. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9658. "3456789012345678901234567890";
  9659. std::string pre_compression_body;
  9660. std::string post_compression_body;
  9661. svr_.set_pre_compression_logger(
  9662. [&](const Request & /*req*/, const Response &res) {
  9663. pre_compression_body = res.body;
  9664. });
  9665. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9666. post_compression_body = res.body;
  9667. });
  9668. Headers headers;
  9669. headers.emplace("Accept-Encoding", "br");
  9670. auto res = cli_.Get("/compress", headers);
  9671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9672. EXPECT_EQ(StatusCode::OK_200, res->status);
  9673. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9674. // Verify pre-compression content is uncompressed
  9675. EXPECT_EQ(test_content, pre_compression_body);
  9676. // Verify post-compression content is compressed
  9677. EXPECT_NE(test_content, post_compression_body);
  9678. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9679. }
  9680. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9681. const std::string test_content =
  9682. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9683. "3456789012345678901234567890";
  9684. std::string pre_compression_body;
  9685. std::string post_compression_body;
  9686. svr_.set_pre_compression_logger(
  9687. [&](const Request & /*req*/, const Response &res) {
  9688. pre_compression_body = res.body;
  9689. });
  9690. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9691. post_compression_body = res.body;
  9692. });
  9693. // Request without compression (use /nocompress endpoint)
  9694. Headers headers;
  9695. auto res = cli_.Get("/nocompress", headers);
  9696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9697. EXPECT_EQ(StatusCode::OK_200, res->status);
  9698. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9699. // Pre-compression logger should not be called when no compression is applied
  9700. EXPECT_TRUE(
  9701. pre_compression_body.empty()); // Pre-compression logger not called
  9702. EXPECT_EQ(
  9703. test_content,
  9704. post_compression_body); // Post-compression logger captures final content
  9705. }
  9706. TEST_F(ServerTest, LoggerSeesContentLength) {
  9707. size_t logged_content_length = 0;
  9708. std::string logged_content_length_header;
  9709. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9710. logged_content_length = res.content_length_;
  9711. logged_content_length_header = res.get_header_value("Content-Length");
  9712. });
  9713. auto res = cli_.Get("/nocompress");
  9714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9715. EXPECT_EQ(StatusCode::OK_200, res->status);
  9716. EXPECT_EQ(res->body.size(), logged_content_length);
  9717. EXPECT_EQ(std::to_string(logged_content_length),
  9718. logged_content_length_header);
  9719. }
  9720. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9721. const std::string test_content =
  9722. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9723. "3456789012345678901234567890";
  9724. std::string pre_compression_body;
  9725. bool pre_logger_called = false;
  9726. // Set only pre-compression logger
  9727. svr_.set_pre_compression_logger(
  9728. [&](const Request & /*req*/, const Response &res) {
  9729. pre_compression_body = res.body;
  9730. pre_logger_called = true;
  9731. });
  9732. Headers headers;
  9733. headers.emplace("Accept-Encoding", "gzip");
  9734. auto res = cli_.Get("/compress", headers);
  9735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9736. EXPECT_EQ(StatusCode::OK_200, res->status);
  9737. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9738. // Verify pre-compression logger was called
  9739. EXPECT_TRUE(pre_logger_called);
  9740. EXPECT_EQ(test_content, pre_compression_body);
  9741. }
  9742. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9743. {
  9744. // Test with Expect: 100-continue header - success case
  9745. // Server returns 100 Continue, client sends body, server returns 200 OK
  9746. Request req;
  9747. req.method = "POST";
  9748. req.path = "/post-large";
  9749. req.set_header("Expect", "100-continue");
  9750. req.body = LARGE_DATA;
  9751. Response res;
  9752. auto error = Error::Success;
  9753. cli_.set_keep_alive(true);
  9754. auto ret = cli_.send(req, res, error);
  9755. EXPECT_TRUE(ret);
  9756. EXPECT_EQ(StatusCode::OK_200, res.status);
  9757. EXPECT_EQ(LARGE_DATA, res.body);
  9758. }
  9759. {
  9760. // Test with Expect: 100-continue header - error case
  9761. // Client should not send the body when server returns an error
  9762. Request req;
  9763. req.method = "POST";
  9764. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9765. req.set_header("Expect", "100-continue");
  9766. req.body = LARGE_DATA;
  9767. Response res;
  9768. auto error = Error::Success;
  9769. auto start = std::chrono::high_resolution_clock::now();
  9770. cli_.set_keep_alive(true);
  9771. auto ret = cli_.send(req, res, error);
  9772. auto end = std::chrono::high_resolution_clock::now();
  9773. auto elapsed =
  9774. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9775. .count();
  9776. // With Expect: 100-continue, request completes successfully but with error
  9777. EXPECT_TRUE(ret);
  9778. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9779. EXPECT_EQ("close", res.get_header_value("Connection"));
  9780. EXPECT_FALSE(cli_.is_socket_open());
  9781. EXPECT_LE(elapsed, 2000);
  9782. }
  9783. {
  9784. // Send an extra GET request to ensure error recovery without hanging
  9785. Request req;
  9786. req.method = "GET";
  9787. req.path = "/hi";
  9788. auto start = std::chrono::high_resolution_clock::now();
  9789. auto res = cli_.send(req);
  9790. auto end = std::chrono::high_resolution_clock::now();
  9791. auto elapsed =
  9792. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9793. .count();
  9794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9795. EXPECT_EQ(StatusCode::OK_200, res->status);
  9796. EXPECT_EQ("Hello World!", res->body);
  9797. EXPECT_LE(elapsed, 500);
  9798. }
  9799. }
  9800. TEST(ZstdDecompressor, ChunkedDecompression) {
  9801. std::string data;
  9802. for (size_t i = 0; i < 32 * 1024; ++i) {
  9803. data.push_back(static_cast<char>('a' + i % 26));
  9804. }
  9805. std::string compressed_data;
  9806. {
  9807. httplib::detail::zstd_compressor compressor;
  9808. bool result = compressor.compress(
  9809. data.data(), data.size(),
  9810. /*last=*/true,
  9811. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9812. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9813. compressed_data_size);
  9814. return true;
  9815. });
  9816. ASSERT_TRUE(result);
  9817. }
  9818. std::string decompressed_data;
  9819. {
  9820. httplib::detail::zstd_decompressor decompressor;
  9821. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9822. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9823. size_t chunk_size = 130;
  9824. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9825. chunk_begin += chunk_size) {
  9826. size_t current_chunk_size =
  9827. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9828. bool result = decompressor.decompress(
  9829. compressed_data.data() + chunk_begin, current_chunk_size,
  9830. [&](const char *decompressed_data_chunk,
  9831. size_t decompressed_data_chunk_size) {
  9832. decompressed_data.insert(decompressed_data.size(),
  9833. decompressed_data_chunk,
  9834. decompressed_data_chunk_size);
  9835. return true;
  9836. });
  9837. ASSERT_TRUE(result);
  9838. }
  9839. }
  9840. ASSERT_EQ(data, decompressed_data);
  9841. }
  9842. TEST(ZstdDecompressor, Decompress) {
  9843. std::string original_text = "Compressed with ZSTD";
  9844. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9845. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9846. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9847. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9848. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9849. std::string decompressed_data;
  9850. {
  9851. httplib::detail::zstd_decompressor decompressor;
  9852. bool result = decompressor.decompress(
  9853. compressed_data.data(), compressed_data.size(),
  9854. [&](const char *decompressed_data_chunk,
  9855. size_t decompressed_data_chunk_size) {
  9856. decompressed_data.insert(decompressed_data.size(),
  9857. decompressed_data_chunk,
  9858. decompressed_data_chunk_size);
  9859. return true;
  9860. });
  9861. ASSERT_TRUE(result);
  9862. }
  9863. ASSERT_EQ(original_text, decompressed_data);
  9864. }
  9865. #endif
  9866. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9867. // separate chunks so that the server sees each part in its own read(). Used to
  9868. // place a read boundary at a specific offset of a request body.
  9869. static bool send_request_in_parts(time_t read_timeout_sec,
  9870. const std::vector<std::string> &parts,
  9871. std::string *resp = nullptr,
  9872. int port = PORT) {
  9873. auto error = Error::Success;
  9874. auto client_sock = detail::create_client_socket(
  9875. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9876. /*connection_timeout_sec=*/5, 0,
  9877. /*read_timeout_sec=*/5, 0,
  9878. /*write_timeout_sec=*/5, 0, std::string(), error);
  9879. if (client_sock == INVALID_SOCKET) { return false; }
  9880. auto ret = detail::process_client_socket(
  9881. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9882. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9883. for (size_t i = 0; i < parts.size(); i++) {
  9884. const auto &part = parts[i];
  9885. if (part.size() !=
  9886. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9887. return false;
  9888. }
  9889. if (i + 1 < parts.size()) {
  9890. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9891. }
  9892. }
  9893. char buf[512];
  9894. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9895. while (line_reader.getline()) {
  9896. if (resp) { *resp += line_reader.ptr(); }
  9897. }
  9898. return true;
  9899. });
  9900. detail::close_socket(client_sock);
  9901. return ret;
  9902. }
  9903. // Sends a raw request to a server listening at HOST:PORT.
  9904. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9905. std::string *resp = nullptr, int port = PORT) {
  9906. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9907. }
  9908. #ifdef CPPHTTPLIB_SSL_ENABLED
  9909. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9911. ASSERT_TRUE(svr.is_valid());
  9912. svr.set_read_timeout(1, 0);
  9913. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9914. auto se = detail::scope_exit([&] {
  9915. svr.stop();
  9916. t.join();
  9917. ASSERT_FALSE(svr.is_running());
  9918. });
  9919. svr.wait_until_ready();
  9920. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9921. // keeps each wait well within the read timeout. The server gives up a
  9922. // second in, so the bytes sent after that fail.
  9923. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9924. parts.resize(26, std::string(1, '\0'));
  9925. EXPECT_FALSE(send_request_in_parts(5, parts));
  9926. }
  9927. #endif
  9928. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9929. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9930. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9931. const std::vector<std::string> &parts,
  9932. std::string *resp = nullptr,
  9933. int port = PORT) {
  9934. auto error = Error::Success;
  9935. auto sock = detail::create_client_socket(
  9936. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9937. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9938. /*write_timeout_sec=*/5, 0, std::string(), error);
  9939. if (sock == INVALID_SOCKET) { return false; }
  9940. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9941. auto ctx = SSL_CTX_new(TLS_client_method());
  9942. auto ssl = SSL_new(ctx);
  9943. auto ssl_se = detail::scope_exit([&] {
  9944. SSL_free(ssl);
  9945. SSL_CTX_free(ctx);
  9946. });
  9947. SSL_set_fd(ssl, static_cast<int>(sock));
  9948. if (SSL_connect(ssl) != 1) { return false; }
  9949. for (size_t i = 0; i < parts.size(); i++) {
  9950. const auto &part = parts[i];
  9951. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9952. static_cast<int>(part.size())) {
  9953. return false;
  9954. }
  9955. if (i + 1 < parts.size()) {
  9956. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9957. }
  9958. }
  9959. char buf[512];
  9960. int n;
  9961. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9962. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9963. }
  9964. return true;
  9965. }
  9966. #endif
  9967. // The request line, then a header value a byte at a time.
  9968. static std::vector<std::string> slow_request_head_parts() {
  9969. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9970. parts.resize(26, "a");
  9971. parts.emplace_back("\r\n\r\n");
  9972. return parts;
  9973. }
  9974. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9975. // within the one-second read timeout. The server gives up a second in, before
  9976. // the head is complete.
  9977. static void
  9978. expect_slow_request_head_dropped(Server &svr,
  9979. const std::function<std::string()> &send) {
  9980. std::atomic<bool> handled(false);
  9981. svr.Get("/", [&](const Request &, Response &res) {
  9982. handled = true;
  9983. res.set_content("ok", "text/plain");
  9984. });
  9985. svr.set_read_timeout(1, 0);
  9986. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9987. auto se = detail::scope_exit([&] {
  9988. svr.stop();
  9989. t.join();
  9990. ASSERT_FALSE(svr.is_running());
  9991. });
  9992. svr.wait_until_ready();
  9993. auto resp = send();
  9994. EXPECT_FALSE(handled);
  9995. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9996. }
  9997. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9998. Server svr;
  9999. expect_slow_request_head_dropped(svr, [] {
  10000. std::string resp;
  10001. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10002. return resp;
  10003. });
  10004. }
  10005. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10006. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10008. ASSERT_TRUE(svr.is_valid());
  10009. expect_slow_request_head_dropped(svr, [] {
  10010. std::string resp;
  10011. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10012. return resp;
  10013. });
  10014. }
  10015. #endif
  10016. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10017. Server svr;
  10018. std::string header_value;
  10019. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10020. header_value = req.get_header_value("foo");
  10021. res.set_content("ok", "text/plain");
  10022. });
  10023. thread t = thread([&] { svr.listen(HOST, PORT); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. t.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.wait_until_ready();
  10030. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10031. // like characters are not treated the same - use vertical tab and escape.
  10032. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10033. "foo: \t \v bar \x1B\t \r\n"
  10034. "Connection: close\r\n"
  10035. "\r\n";
  10036. std::string res;
  10037. ASSERT_TRUE(send_request(5, req, &res));
  10038. EXPECT_EQ(header_value, "");
  10039. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10040. }
  10041. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10042. Server svr;
  10043. std::string received;
  10044. svr.Get("/order", [&](const Request &req, Response &res) {
  10045. received = entries_to_string(req.headers);
  10046. res.set_content("ok", "text/plain");
  10047. });
  10048. auto port = svr.bind_to_any_port(HOST);
  10049. thread t = thread([&] { svr.listen_after_bind(); });
  10050. auto se = detail::scope_exit([&] {
  10051. svr.stop();
  10052. t.join();
  10053. ASSERT_FALSE(svr.is_running());
  10054. });
  10055. svr.wait_until_ready();
  10056. const std::string req = "GET /order HTTP/1.1\r\n"
  10057. "Host: localhost\r\n"
  10058. "X-First: 1\r\n"
  10059. "X-Dup: a\r\n"
  10060. "X-Second: 2\r\n"
  10061. "X-Dup: b\r\n"
  10062. "Connection: close\r\n"
  10063. "\r\n";
  10064. std::string res;
  10065. ASSERT_TRUE(send_request(5, req, &res, port));
  10066. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10067. EXPECT_EQ(
  10068. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10069. received);
  10070. }
  10071. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10072. Server svr;
  10073. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10074. res.set_header("Set-Cookie", "first=1");
  10075. res.set_header("X-Between", "y");
  10076. res.set_header("Set-Cookie", "second=2");
  10077. res.set_content("ok", "text/plain");
  10078. });
  10079. auto port = svr.bind_to_any_port(HOST);
  10080. thread t = thread([&] { svr.listen_after_bind(); });
  10081. auto se = detail::scope_exit([&] {
  10082. svr.stop();
  10083. t.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. svr.wait_until_ready();
  10087. Client cli(HOST, port);
  10088. auto res = cli.Get("/cookies");
  10089. ASSERT_TRUE(res);
  10090. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10091. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10092. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10093. }
  10094. // A stream may send a byte at a time with a small extension on each chunk,
  10095. // however long it runs
  10096. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10097. Server svr;
  10098. svr.Post("/count", [](const Request &req, Response &res) {
  10099. res.set_content(std::to_string(req.body.size()), "text/plain");
  10100. });
  10101. auto port = svr.bind_to_any_port(HOST);
  10102. ASSERT_LT(0, port);
  10103. thread t = thread([&] { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. t.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10111. "\r\nTransfer-Encoding: chunked\r\n"
  10112. "Connection: close\r\n\r\n";
  10113. for (auto i = 0; i < 4096; i++) {
  10114. req += "1;a=b\r\nx\r\n";
  10115. }
  10116. req += "0\r\n\r\n";
  10117. std::string res;
  10118. ASSERT_TRUE(send_request(5, req, &res, port));
  10119. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10120. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10121. }
  10122. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10123. Server svr;
  10124. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10125. auto i = new int(0);
  10126. res.set_header("Trailer", "X-Safe, X-Reflected");
  10127. res.set_chunked_content_provider(
  10128. "text/plain",
  10129. [i](size_t /*offset*/, DataSink &sink) {
  10130. if (*i == 0) {
  10131. sink.os << "body";
  10132. } else {
  10133. Headers trailer;
  10134. // A valid trailer that must survive.
  10135. trailer.emplace("X-Safe", "safe");
  10136. // Attacker-controlled value carrying CR/LF (response splitting).
  10137. trailer.emplace("X-Reflected",
  10138. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10139. // Attacker-controlled name carrying CR/LF.
  10140. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10141. sink.done_with_trailer(trailer);
  10142. }
  10143. (*i)++;
  10144. return true;
  10145. },
  10146. [i](bool /*success*/) { delete i; });
  10147. });
  10148. thread t = thread([&] { svr.listen(HOST, PORT); });
  10149. auto se = detail::scope_exit([&] {
  10150. svr.stop();
  10151. t.join();
  10152. ASSERT_FALSE(svr.is_running());
  10153. });
  10154. svr.wait_until_ready();
  10155. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10156. "Host: " + HOST +
  10157. "\r\n"
  10158. "Connection: close\r\n"
  10159. "\r\n";
  10160. std::string res;
  10161. ASSERT_TRUE(send_request(5, req, &res));
  10162. // The injected fields must not appear anywhere in the raw response.
  10163. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10164. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10165. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10166. // Invalid trailers are dropped entirely, matching set_header().
  10167. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10168. // The valid trailer still passes through.
  10169. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10170. }
  10171. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10172. // A custom header writer gets only the fields the default one writes
  10173. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10174. std::string s;
  10175. for (const auto &h : hdrs) {
  10176. s += h.first + ": " + h.second + "\r\n";
  10177. }
  10178. s += "\r\n";
  10179. return strm.write(s.data(), s.size());
  10180. };
  10181. for (auto custom_writer : {false, true}) {
  10182. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10183. Server svr;
  10184. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10185. svr.set_post_routing_handler([](const Request &, Response &res) {
  10186. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10187. });
  10188. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10189. // res.headers is a public field an application can populate directly,
  10190. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10191. // A valid header that must survive.
  10192. res.headers.emplace("X-Safe", "safe");
  10193. // Attacker-controlled value carrying CR/LF (response splitting).
  10194. res.headers.emplace("X-Reflected",
  10195. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10196. // Attacker-controlled name carrying CR/LF.
  10197. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10198. res.set_content("body", "text/plain");
  10199. });
  10200. thread t = thread([&] { svr.listen(HOST, PORT); });
  10201. auto se = detail::scope_exit([&] {
  10202. svr.stop();
  10203. t.join();
  10204. ASSERT_FALSE(svr.is_running());
  10205. });
  10206. svr.wait_until_ready();
  10207. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10208. "Host: " + HOST +
  10209. "\r\n"
  10210. "Connection: close\r\n"
  10211. "\r\n";
  10212. std::string res;
  10213. ASSERT_TRUE(send_request(5, req, &res));
  10214. // The injected fields must not appear anywhere in the raw response.
  10215. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10216. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10217. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10218. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10219. // Invalid headers are dropped entirely, matching set_header().
  10220. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10221. // The valid header still passes through.
  10222. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10223. }
  10224. }
  10225. // Forward declaration: in split builds split.py strips `inline` and moves the
  10226. // definition into httplib.cc, so detail::write_request_line is not visible from
  10227. // the public httplib.h. Re-declaring it here lets the tests link against the
  10228. // symbol in both header-only and split builds.
  10229. namespace httplib {
  10230. namespace detail {
  10231. ssize_t write_request_line(Stream &strm, const std::string &method,
  10232. const std::string &path);
  10233. } // namespace detail
  10234. } // namespace httplib
  10235. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10236. // A well-formed target is written verbatim.
  10237. {
  10238. detail::BufferStream strm;
  10239. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10240. EXPECT_GT(n, 0);
  10241. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10242. }
  10243. // A target carrying CR/LF, SP or other control octets must be rejected
  10244. // before anything reaches the wire, otherwise it splits the request line and
  10245. // injects a header or a whole request.
  10246. const std::string evil_targets[] = {
  10247. "/a\r\nInjected: pwned",
  10248. "/a\rInjected",
  10249. "/a\nInjected",
  10250. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10251. "/a b",
  10252. "/a\tb",
  10253. "/a\x7f",
  10254. };
  10255. for (const auto &evil : evil_targets) {
  10256. detail::BufferStream strm;
  10257. auto n = detail::write_request_line(strm, "GET", evil);
  10258. EXPECT_LT(n, 0);
  10259. EXPECT_TRUE(strm.get_buffer().empty());
  10260. }
  10261. }
  10262. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10263. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10264. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10265. // target reaches write_request. The client must fail cleanly with
  10266. // Error::Write instead of putting a request-line-less, header-injecting
  10267. // request on the wire.
  10268. Server svr;
  10269. svr.Get("/a", [](const Request &, Response &res) {
  10270. res.set_content("ok", "text/plain");
  10271. });
  10272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10273. auto se = detail::scope_exit([&] {
  10274. svr.stop();
  10275. thread.join();
  10276. ASSERT_FALSE(svr.is_running());
  10277. });
  10278. svr.wait_until_ready();
  10279. {
  10280. Client cli(HOST, PORT);
  10281. cli.set_path_encode(false);
  10282. // The request is rejected before anything is written, so the connection
  10283. // stays silent and the subsequent response read would otherwise block for
  10284. // the full default read timeout. Shorten it -- the assertion is on the
  10285. // error, not the timeout.
  10286. cli.set_read_timeout(1, 0);
  10287. auto res = cli.Get("/a\r\nInjected: pwned");
  10288. EXPECT_FALSE(res);
  10289. EXPECT_EQ(Error::Write, res.error());
  10290. }
  10291. }
  10292. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10293. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10294. // including extension methods.
  10295. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10296. for (const auto &method : good_methods) {
  10297. detail::BufferStream strm;
  10298. auto n = detail::write_request_line(strm, method, "/");
  10299. EXPECT_GT(n, 0);
  10300. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10301. }
  10302. // A method carrying CR/LF would split the request line and smuggle a whole
  10303. // request ahead of the real one. A space or an empty method corrupts the
  10304. // request line. All must be rejected before anything reaches the wire.
  10305. const std::string evil_methods[] = {
  10306. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10307. "GET\r\nInjected: pwned",
  10308. "GET\r",
  10309. "GET\n",
  10310. "GE T",
  10311. "",
  10312. };
  10313. for (const auto &evil : evil_methods) {
  10314. detail::BufferStream strm;
  10315. auto n = detail::write_request_line(strm, evil, "/");
  10316. EXPECT_LT(n, 0);
  10317. EXPECT_TRUE(strm.get_buffer().empty());
  10318. }
  10319. }
  10320. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10321. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10322. // through Client::send must fail with Error::Write and no request, neither
  10323. // the smuggled one nor the real one, may reach the server.
  10324. Server svr;
  10325. std::atomic<int> request_count(0);
  10326. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10327. request_count++;
  10328. res.status = StatusCode::OK_200;
  10329. return Server::HandlerResponse::Handled;
  10330. });
  10331. auto port = svr.bind_to_any_port(HOST);
  10332. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10333. auto se = detail::scope_exit([&] {
  10334. svr.stop();
  10335. thread.join();
  10336. ASSERT_FALSE(svr.is_running());
  10337. });
  10338. svr.wait_until_ready();
  10339. {
  10340. Client cli(HOST, port);
  10341. const std::string evil_methods[] = {
  10342. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10343. "GE T",
  10344. "",
  10345. };
  10346. for (const auto &evil : evil_methods) {
  10347. Request req;
  10348. req.method = evil;
  10349. req.path = "/";
  10350. auto res = cli.send(req);
  10351. EXPECT_FALSE(res);
  10352. EXPECT_EQ(Error::Write, res.error());
  10353. }
  10354. auto handle =
  10355. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10356. EXPECT_FALSE(handle.is_valid());
  10357. EXPECT_EQ(Error::Write, handle.error);
  10358. // A valid request on the same client still goes through.
  10359. auto res = cli.Get("/");
  10360. ASSERT_TRUE(res);
  10361. EXPECT_EQ(StatusCode::OK_200, res->status);
  10362. }
  10363. EXPECT_EQ(1, request_count.load());
  10364. }
  10365. // Sends a raw request and verifies that there isn't a crash or exception.
  10366. static void test_raw_request(const std::string &req,
  10367. std::string *out = nullptr) {
  10368. Server svr;
  10369. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10370. res.set_content("ok", "text/plain");
  10371. });
  10372. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10373. res.set_content("ok", "text/plain");
  10374. });
  10375. svr.Get("/header_field_value_check",
  10376. [&](const Request & /*req*/, Response &res) {
  10377. res.set_content("ok", "text/plain");
  10378. });
  10379. svr.CustomRoute("PROPFIND", "/dav",
  10380. [&](const Request & /*req*/, Response &res) {
  10381. res.status = StatusCode::MultiStatus_207;
  10382. });
  10383. // Server read timeout must be longer than the client read timeout for the
  10384. // bug to reproduce, probably to force the server to process a request
  10385. // without a trailing blank line.
  10386. const time_t client_read_timeout_sec = 1;
  10387. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10388. bool listen_thread_ok = false;
  10389. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. t.join();
  10393. ASSERT_FALSE(svr.is_running());
  10394. EXPECT_TRUE(listen_thread_ok);
  10395. });
  10396. svr.wait_until_ready();
  10397. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10398. }
  10399. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10400. // A certain header line causes an exception if the header property is parsed
  10401. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10402. test_raw_request(
  10403. "GET /hi HTTP/1.1\r\n"
  10404. " : "
  10405. " "
  10406. " ");
  10407. }
  10408. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10409. // A certain header line causes an exception if the header property *name* is
  10410. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10411. // greedy matcher and requires backtracking when there are a lot of ":"
  10412. // characters.
  10413. // This occurs with libc++ but not libstdc++.
  10414. test_raw_request(
  10415. "GET /hi HTTP/1.1\r\n"
  10416. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10417. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10418. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10419. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10420. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10421. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10422. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10423. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10424. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10425. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10426. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10427. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10428. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10429. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10430. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10431. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10432. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10433. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10434. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10435. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10436. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10437. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10438. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10439. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10440. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10441. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10442. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10443. "&&&%%%");
  10444. }
  10445. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10446. // Make sure this doesn't crash the server.
  10447. // In a previous version of the header line regex, the "\r" rendered the line
  10448. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10449. // a new position where the leading white space ended and the field value
  10450. // began.
  10451. // The crash occurs with libc++ but not libstdc++.
  10452. test_raw_request("GET /hi HTTP/1.1\r\n"
  10453. "a:" +
  10454. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10455. "\r\n"
  10456. "\r\n");
  10457. }
  10458. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10459. const char *rejected[] = {
  10460. // RFC 9112 §3: one SP between the parts, and nothing else
  10461. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10462. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10463. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10464. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10465. // A request-target has no fragment
  10466. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10467. // An HTTP/1.1 request needs a Host
  10468. "GET /hi HTTP/1.1\r\n\r\n",
  10469. };
  10470. for (auto request : rejected) {
  10471. std::string out;
  10472. test_raw_request(request, &out);
  10473. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10474. }
  10475. std::string out;
  10476. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10477. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10478. }
  10479. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10480. // RFC 9112 §6.1
  10481. const char *requests[] = {
  10482. "PUT /put_hi HTTP/1.1\r\n"
  10483. "Host: localhost\r\n"
  10484. "Content-Length: 0\r\n"
  10485. "Transfer-Encoding: chunked\r\n"
  10486. "\r\n"
  10487. "0\r\n\r\n",
  10488. "PUT /put_hi HTTP/1.0\r\n"
  10489. "Connection: keep-alive\r\n"
  10490. "Transfer-Encoding: chunked\r\n"
  10491. "\r\n"
  10492. "0\r\n\r\n",
  10493. };
  10494. for (auto request : requests) {
  10495. std::string out;
  10496. test_raw_request(request, &out);
  10497. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10498. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10499. }
  10500. }
  10501. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10502. std::string out;
  10503. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10504. "Content-Type: text/plain\r\n"
  10505. "Transfer-Encoding: chunked\r\n"
  10506. "\r\n"
  10507. "nothex\r\n",
  10508. &out);
  10509. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10510. }
  10511. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10512. std::string out;
  10513. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10514. "Content-Type: text/plain\r\n"
  10515. "Transfer-Encoding: chunked\r\n"
  10516. "\r\n"
  10517. "3\r\n"
  10518. "xyz\r\n"
  10519. "NaN\r\n",
  10520. &out);
  10521. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10522. }
  10523. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10524. std::string out;
  10525. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10526. "Content-Type: text/plain\r\n"
  10527. "Transfer-Encoding: chunked\r\n"
  10528. "\r\n"
  10529. // Length is too large for 64 bits.
  10530. "1ffffffffffffffff\r\n"
  10531. "xyz\r\n",
  10532. &out);
  10533. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10534. }
  10535. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10536. test_raw_request("GET /hi HTTP/1.1\r\n"
  10537. "Content-Type: text/plain\r\n\r");
  10538. }
  10539. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10540. std::string out;
  10541. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10542. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10543. }
  10544. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10545. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10546. std::string out;
  10547. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10548. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10549. }
  10550. }
  10551. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10552. std::string out;
  10553. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10554. "Host: localhost\r\n"
  10555. "Connection: close\r\n\r\n",
  10556. &out);
  10557. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10558. }
  10559. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10560. Server svr;
  10561. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10562. EXPECT_TRUE(!req.remote_addr.empty());
  10563. });
  10564. thread t = thread([&] { svr.listen(HOST, PORT); });
  10565. auto se = detail::scope_exit([&] {
  10566. svr.stop();
  10567. t.join();
  10568. ASSERT_FALSE(svr.is_running());
  10569. });
  10570. svr.wait_until_ready();
  10571. // Send an invalid request line to trigger Bad Request
  10572. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10573. std::string out;
  10574. ASSERT_TRUE(send_request(5, bad_req, &out));
  10575. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10576. }
  10577. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10578. // answered right away rather than blocking on a read that waits for EOF.
  10579. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10580. std::string out;
  10581. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10582. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10583. }
  10584. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10585. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10586. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10587. for (const auto *method : methods) {
  10588. Server svr;
  10589. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10590. EXPECT_FALSE(svr.is_valid()) << method;
  10591. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10592. }
  10593. }
  10594. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10595. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10596. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10597. for (const auto *method : methods) {
  10598. Server svr;
  10599. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10600. EXPECT_FALSE(svr.is_valid()) << method;
  10601. }
  10602. }
  10603. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10604. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10605. "COPY", "MOVE", "LOCK",
  10606. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10607. Server svr;
  10608. for (const auto *method : methods) {
  10609. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10610. }
  10611. EXPECT_TRUE(svr.is_valid());
  10612. }
  10613. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10614. Server svr;
  10615. svr.CustomRoute("POST", "/x",
  10616. [](const Request &, Response &, const ContentReader &) {});
  10617. EXPECT_FALSE(svr.is_valid());
  10618. }
  10619. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10620. Server svr;
  10621. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10622. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10623. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10624. EXPECT_FALSE(svr.is_valid());
  10625. }
  10626. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10627. Server svr;
  10628. auto captured = Error::Success;
  10629. svr.set_error_logger(
  10630. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10631. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10632. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10633. }
  10634. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10635. std::string out;
  10636. std::string request(
  10637. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10638. test_raw_request(request, &out);
  10639. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10640. }
  10641. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10642. std::string out;
  10643. std::string request(
  10644. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10645. test_raw_request(request, &out);
  10646. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10647. }
  10648. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10649. std::string out;
  10650. std::string request(
  10651. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10652. test_raw_request(request, &out);
  10653. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10654. }
  10655. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10656. std::string out;
  10657. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10658. "Host: localhost\r\n"
  10659. "Test: \r\n\r\n",
  10660. &out);
  10661. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10662. }
  10663. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10664. Server svr;
  10665. std::string x_custom;
  10666. std::string cookie;
  10667. std::string xff;
  10668. std::string x_unicode;
  10669. std::string x_iis;
  10670. svr.Get("/check", [&](const Request &req, Response &res) {
  10671. x_custom = req.get_header_value("X-Custom");
  10672. cookie = req.get_header_value("Cookie");
  10673. xff = req.get_header_value("X-Forwarded-For");
  10674. x_unicode = req.get_header_value("X-Unicode");
  10675. x_iis = req.get_header_value("X-IIS");
  10676. res.set_content("ok", "text/plain");
  10677. });
  10678. thread t = thread([&] { svr.listen(HOST, PORT); });
  10679. auto se = detail::scope_exit([&] {
  10680. svr.stop();
  10681. t.join();
  10682. ASSERT_FALSE(svr.is_running());
  10683. });
  10684. svr.wait_until_ready();
  10685. const std::string req = "GET /check HTTP/1.1\r\n"
  10686. "Host: localhost\r\n"
  10687. "X-Custom: a%0D%0AInjected: b\r\n"
  10688. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10689. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10690. "X-Unicode: %E3%81%82\r\n"
  10691. "X-IIS: %u00E9\r\n"
  10692. "Connection: close\r\n"
  10693. "\r\n";
  10694. std::string res;
  10695. ASSERT_TRUE(send_request(5, req, &res));
  10696. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10697. // Every value must be returned verbatim (wire form), with no decoding.
  10698. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10699. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10700. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10701. EXPECT_EQ("%E3%81%82", x_unicode);
  10702. EXPECT_EQ("%u00E9", x_iis);
  10703. }
  10704. // Applications that previously relied on automatic percent-decoding can
  10705. // reproduce the old behavior by explicitly calling decode_path_component()
  10706. // or, for RFC 3986 conformance, decode_uri_component().
  10707. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10708. Server svr;
  10709. std::string decoded;
  10710. svr.Get("/check", [&](const Request &req, Response &res) {
  10711. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10712. res.set_content("ok", "text/plain");
  10713. });
  10714. thread t = thread([&] { svr.listen(HOST, PORT); });
  10715. auto se = detail::scope_exit([&] {
  10716. svr.stop();
  10717. t.join();
  10718. ASSERT_FALSE(svr.is_running());
  10719. });
  10720. svr.wait_until_ready();
  10721. const std::string req = "GET /check HTTP/1.1\r\n"
  10722. "Host: localhost\r\n"
  10723. "X-Custom: hello%20world\r\n"
  10724. "Connection: close\r\n"
  10725. "\r\n";
  10726. std::string res;
  10727. ASSERT_TRUE(send_request(5, req, &res));
  10728. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10729. EXPECT_EQ("hello world", decoded);
  10730. }
  10731. // Regression test for #2033. Browsers send Referer values that include
  10732. // percent-encoded characters such as %0A inside the URL. Decoding the
  10733. // header value would either trip the post-decode CR/LF/NUL guard (the
  10734. // original bug, returning 400) or, after that guard was relaxed, silently
  10735. // store a literal LF — both unacceptable. The wire form must round-trip.
  10736. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10737. Server svr;
  10738. std::string referer;
  10739. svr.Get("/check", [&](const Request &req, Response &res) {
  10740. referer = req.get_header_value("Referer");
  10741. res.set_content("ok", "text/plain");
  10742. });
  10743. thread t = thread([&] { svr.listen(HOST, PORT); });
  10744. auto se = detail::scope_exit([&] {
  10745. svr.stop();
  10746. t.join();
  10747. ASSERT_FALSE(svr.is_running());
  10748. });
  10749. svr.wait_until_ready();
  10750. const std::string req = "GET /check HTTP/1.1\r\n"
  10751. "Host: localhost\r\n"
  10752. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10753. "Connection: close\r\n"
  10754. "\r\n";
  10755. std::string res;
  10756. ASSERT_TRUE(send_request(5, req, &res));
  10757. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10758. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10759. }
  10760. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10761. Server svr;
  10762. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10763. res.set_header("Cache-Control", "no-cache");
  10764. res.set_chunked_content_provider(
  10765. "text/event-stream", [](size_t offset, DataSink &sink) {
  10766. std::string s = "data:";
  10767. s += std::to_string(offset);
  10768. s += "\n\n";
  10769. auto ret = sink.write(s.data(), s.size());
  10770. EXPECT_TRUE(ret);
  10771. std::this_thread::sleep_for(std::chrono::seconds(1));
  10772. return true;
  10773. });
  10774. });
  10775. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10776. svr.wait_until_ready();
  10777. Client client(HOST, PORT);
  10778. const Headers headers = {{"Accept", "text/event-stream"}};
  10779. auto get_thread = std::thread([&client, &headers]() {
  10780. auto res = client.Get(
  10781. "/events", headers,
  10782. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10783. });
  10784. auto se = detail::scope_exit([&] {
  10785. svr.stop();
  10786. get_thread.join();
  10787. listen_thread.join();
  10788. ASSERT_FALSE(svr.is_running());
  10789. });
  10790. // Give GET time to get a few messages.
  10791. std::this_thread::sleep_for(std::chrono::seconds(2));
  10792. }
  10793. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10794. httplib::Server svr;
  10795. svr.Post("/hi",
  10796. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10797. res.status = StatusCode::OK_200;
  10798. });
  10799. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10800. svr.wait_until_ready();
  10801. Client cli(HOST, PORT);
  10802. auto res = cli.Post("/hi", "data", "text/plain");
  10803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10804. EXPECT_EQ(StatusCode::OK_200, res->status);
  10805. svr.stop();
  10806. thread.join();
  10807. ASSERT_FALSE(svr.is_running());
  10808. res = cli.Post("/hi", "data", "text/plain");
  10809. ASSERT_FALSE(res);
  10810. }
  10811. TEST(ServerStopTest, ListenFailure) {
  10812. Server svr;
  10813. auto t = thread([&]() {
  10814. auto ret = svr.listen("????", PORT);
  10815. EXPECT_FALSE(ret);
  10816. });
  10817. svr.wait_until_ready();
  10818. svr.stop();
  10819. t.join();
  10820. }
  10821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10822. TEST(ServerStopTest, Decommision) {
  10823. Server svr;
  10824. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10825. for (int i = 0; i < 4; i++) {
  10826. auto is_even = !(i % 2);
  10827. std::thread t{[&] {
  10828. try {
  10829. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10830. if (is_even) {
  10831. throw std::runtime_error("Some thing that happens to go wrong.");
  10832. }
  10833. svr.listen(HOST, PORT);
  10834. } catch (...) { svr.decommission(); }
  10835. }};
  10836. svr.wait_until_ready();
  10837. // Server is up
  10838. {
  10839. Client cli(HOST, PORT);
  10840. auto res = cli.Get("/hi");
  10841. if (is_even) {
  10842. EXPECT_FALSE(res);
  10843. } else {
  10844. EXPECT_TRUE(res);
  10845. EXPECT_EQ("hi...", res->body);
  10846. }
  10847. }
  10848. svr.stop();
  10849. t.join();
  10850. // Server is down...
  10851. {
  10852. Client cli(HOST, PORT);
  10853. auto res = cli.Get("/hi");
  10854. EXPECT_FALSE(res);
  10855. }
  10856. }
  10857. }
  10858. #endif
  10859. // Helper function for string body upload progress tests
  10860. template <typename SetupHandler, typename ClientCall>
  10861. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10862. ClientCall &&client_call,
  10863. const string &body) {
  10864. Server svr;
  10865. setup_handler(svr);
  10866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10867. auto se = detail::scope_exit([&] {
  10868. svr.stop();
  10869. t.join();
  10870. });
  10871. svr.wait_until_ready();
  10872. Client cli(HOST, PORT);
  10873. vector<uint64_t> progress_values;
  10874. bool progress_called = false;
  10875. auto res =
  10876. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10877. progress_values.push_back(current);
  10878. progress_called = true;
  10879. return true;
  10880. });
  10881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10882. EXPECT_EQ(200, res->status);
  10883. EXPECT_TRUE(progress_called);
  10884. }
  10885. TEST(UploadProgressTest, PostStringBodyBasic) {
  10886. TestStringBodyUploadProgress(
  10887. [](Server &svr) {
  10888. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10889. res.set_content("received", "text/plain");
  10890. });
  10891. },
  10892. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10893. return cli.Post("/test", body, "text/plain", progress_callback);
  10894. },
  10895. "test data for upload progress");
  10896. }
  10897. TEST(UploadProgressTest, PutStringBodyBasic) {
  10898. TestStringBodyUploadProgress(
  10899. [](Server &svr) {
  10900. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10901. res.set_content("put received", "text/plain");
  10902. });
  10903. },
  10904. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10905. return cli.Put("/test", body, "text/plain", progress_callback);
  10906. },
  10907. "put test data for upload progress");
  10908. }
  10909. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10910. TestStringBodyUploadProgress(
  10911. [](Server &svr) {
  10912. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10913. res.set_content("patch received", "text/plain");
  10914. });
  10915. },
  10916. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10917. return cli.Patch("/test", body, "text/plain", progress_callback);
  10918. },
  10919. "patch test data for upload progress");
  10920. }
  10921. // Helper function for content provider upload progress tests
  10922. template <typename SetupHandler, typename ClientCall>
  10923. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10924. ClientCall &&client_call) {
  10925. Server svr;
  10926. setup_handler(svr);
  10927. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10928. auto se = detail::scope_exit([&] {
  10929. svr.stop();
  10930. t.join();
  10931. });
  10932. svr.wait_until_ready();
  10933. Client cli(HOST, PORT);
  10934. vector<uint64_t> progress_values;
  10935. auto res =
  10936. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10937. progress_values.push_back(current);
  10938. return true;
  10939. });
  10940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10941. EXPECT_EQ(200, res->status);
  10942. EXPECT_FALSE(progress_values.empty());
  10943. }
  10944. TEST(UploadProgressTest, PostContentProviderProgress) {
  10945. TestContentProviderUploadProgress(
  10946. [](Server &svr) {
  10947. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10948. res.set_content("provider received", "text/plain");
  10949. });
  10950. },
  10951. [](Client &cli, UploadProgress progress_callback) {
  10952. return cli.Post(
  10953. "/test", 9,
  10954. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10955. sink.os << "test data";
  10956. return true;
  10957. },
  10958. "text/plain", progress_callback);
  10959. });
  10960. }
  10961. // Helper function for multipart upload progress tests
  10962. template <typename SetupHandler, typename ClientCall>
  10963. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10964. ClientCall &&client_call,
  10965. const string &endpoint) {
  10966. Server svr;
  10967. setup_handler(svr);
  10968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10969. auto se = detail::scope_exit([&] {
  10970. svr.stop();
  10971. t.join();
  10972. });
  10973. svr.wait_until_ready();
  10974. Client cli(HOST, PORT);
  10975. vector<uint64_t> progress_values;
  10976. UploadFormDataItems items = {
  10977. {"field1", "value1", "", ""},
  10978. {"field2", "longer value for progress tracking test", "", ""},
  10979. {"file1", "file content data for upload progress", "test.txt",
  10980. "text/plain"}};
  10981. auto res = client_call(cli, endpoint, items,
  10982. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10983. progress_values.push_back(current);
  10984. return true;
  10985. });
  10986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10987. EXPECT_EQ(200, res->status);
  10988. EXPECT_FALSE(progress_values.empty());
  10989. }
  10990. TEST(UploadProgressTest, PostMultipartProgress) {
  10991. TestMultipartUploadProgress(
  10992. [](Server &svr) {
  10993. svr.Post("/multipart", [](const Request &req, Response &res) {
  10994. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10995. res.set_content("multipart received", "text/plain");
  10996. });
  10997. },
  10998. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10999. UploadProgress progress_callback) {
  11000. return cli.Post(endpoint, items, progress_callback);
  11001. },
  11002. "/multipart");
  11003. }
  11004. // Helper function for basic download progress tests
  11005. template <typename SetupHandler, typename ClientCall>
  11006. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11007. ClientCall &&client_call, const string &endpoint,
  11008. size_t expected_content_size) {
  11009. Server svr;
  11010. setup_handler(svr);
  11011. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11012. auto se = detail::scope_exit([&] {
  11013. svr.stop();
  11014. t.join();
  11015. });
  11016. svr.wait_until_ready();
  11017. Client cli(HOST, PORT);
  11018. vector<uint64_t> progress_values;
  11019. auto res = client_call(cli, endpoint,
  11020. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11021. progress_values.push_back(current);
  11022. return true;
  11023. });
  11024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11025. EXPECT_EQ(200, res->status);
  11026. EXPECT_FALSE(progress_values.empty());
  11027. EXPECT_EQ(expected_content_size, res->body.size());
  11028. }
  11029. TEST(DownloadProgressTest, GetBasic) {
  11030. TestBasicDownloadProgress(
  11031. [](Server &svr) {
  11032. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11033. string content(1000, 'D');
  11034. res.set_content(content, "text/plain");
  11035. });
  11036. },
  11037. [](Client &cli, const string &endpoint,
  11038. DownloadProgress progress_callback) {
  11039. return cli.Get(endpoint, progress_callback);
  11040. },
  11041. "/download", 1000u);
  11042. }
  11043. // Helper function for content receiver download progress tests
  11044. template <typename SetupHandler, typename ClientCall>
  11045. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11046. ClientCall &&client_call,
  11047. const string &endpoint,
  11048. size_t expected_content_size) {
  11049. Server svr;
  11050. setup_handler(svr);
  11051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11052. auto se = detail::scope_exit([&] {
  11053. svr.stop();
  11054. t.join();
  11055. });
  11056. svr.wait_until_ready();
  11057. Client cli(HOST, PORT);
  11058. vector<uint64_t> progress_values;
  11059. string received_body;
  11060. auto res = client_call(
  11061. cli, endpoint,
  11062. [&](const char *data, size_t data_length) -> bool {
  11063. received_body.append(data, data_length);
  11064. return true;
  11065. },
  11066. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11067. progress_values.push_back(current);
  11068. return true;
  11069. });
  11070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11071. EXPECT_EQ(200, res->status);
  11072. EXPECT_FALSE(progress_values.empty());
  11073. EXPECT_EQ(expected_content_size, received_body.size());
  11074. EXPECT_TRUE(res->body.empty());
  11075. }
  11076. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11077. TestContentReceiverDownloadProgress(
  11078. [](Server &svr) {
  11079. svr.Get("/download-receiver",
  11080. [](const Request & /*req*/, Response &res) {
  11081. string content(2000, 'R');
  11082. res.set_content(content, "text/plain");
  11083. });
  11084. },
  11085. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11086. DownloadProgress progress_callback) {
  11087. return cli.Get(endpoint, content_receiver, progress_callback);
  11088. },
  11089. "/download-receiver", 2000u);
  11090. }
  11091. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11092. // A provider reaching a pass with nothing to hand over - an empty buffer
  11093. // popped off a queue, say - must not be taken to mean the body is finished.
  11094. // It used to end the loop with the terminating chunk unwritten while the
  11095. // server still considered the response complete, so the peer waited for an
  11096. // end that never arrived.
  11097. Server svr;
  11098. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11099. auto step = std::make_shared<int>(0);
  11100. res.set_chunked_content_provider("text/plain",
  11101. [step](size_t /*offset*/, DataSink &sink) {
  11102. switch ((*step)++) {
  11103. case 0: sink.write("", 0); break;
  11104. case 1: sink.write("hello", 5); break;
  11105. default: sink.done(); break;
  11106. }
  11107. return true;
  11108. });
  11109. });
  11110. auto port = svr.bind_to_any_port(HOST);
  11111. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11112. auto listen_se = detail::scope_exit([&] {
  11113. svr.stop();
  11114. listen_thread.join();
  11115. ASSERT_FALSE(svr.is_running());
  11116. });
  11117. svr.wait_until_ready();
  11118. Client cli(HOST, port);
  11119. // Without the fix the body is never terminated, so bound the wait rather
  11120. // than letting the test hang on the default read timeout.
  11121. cli.set_read_timeout(5, 0);
  11122. auto res = cli.Get("/stream");
  11123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11124. EXPECT_EQ(StatusCode::OK_200, res->status);
  11125. EXPECT_EQ("hello", res->body);
  11126. }
  11127. TEST(StreamingTest, NoContentLengthStreaming) {
  11128. Server svr;
  11129. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11130. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11131. if (offset < 6) {
  11132. sink.os << (offset < 3 ? "a" : "b");
  11133. } else {
  11134. sink.done();
  11135. }
  11136. return true;
  11137. });
  11138. });
  11139. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11140. auto listen_se = detail::scope_exit([&] {
  11141. svr.stop();
  11142. listen_thread.join();
  11143. ASSERT_FALSE(svr.is_running());
  11144. });
  11145. svr.wait_until_ready();
  11146. Client client(HOST, PORT);
  11147. auto get_thread = std::thread([&client]() {
  11148. std::string s;
  11149. auto res =
  11150. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11151. s += std::string(data, len);
  11152. return true;
  11153. });
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::OK_200, res->status);
  11156. EXPECT_EQ("aaabbb", s);
  11157. });
  11158. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11159. // Give GET time to get a few messages.
  11160. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11161. }
  11162. TEST(MountTest, Unmount) {
  11163. Server svr;
  11164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. listen_thread.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. });
  11170. svr.wait_until_ready();
  11171. Client cli("localhost", PORT);
  11172. svr.set_mount_point("/mount2", "./www2");
  11173. auto res = cli.Get("/");
  11174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11175. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11176. res = cli.Get("/mount2/dir/test.html");
  11177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11178. EXPECT_EQ(StatusCode::OK_200, res->status);
  11179. svr.set_mount_point("/", "./www");
  11180. res = cli.Get("/dir/");
  11181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11182. EXPECT_EQ(StatusCode::OK_200, res->status);
  11183. svr.remove_mount_point("/");
  11184. res = cli.Get("/dir/");
  11185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11187. svr.remove_mount_point("/mount2");
  11188. res = cli.Get("/mount2/dir/test.html");
  11189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11190. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11191. }
  11192. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11193. Server svr;
  11194. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11195. svr.Get("/api/hello", [](const Request &, Response &res) {
  11196. res.set_content("api", "text/plain");
  11197. });
  11198. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11199. auto se = detail::scope_exit([&] {
  11200. svr.stop();
  11201. listen_thread.join();
  11202. ASSERT_FALSE(svr.is_running());
  11203. });
  11204. svr.wait_until_ready();
  11205. Client cli(HOST, PORT);
  11206. auto res = cli.Get("/dir/test.html");
  11207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11208. EXPECT_EQ(StatusCode::OK_200, res->status);
  11209. res = cli.Get("/api/hello");
  11210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11211. EXPECT_EQ(StatusCode::OK_200, res->status);
  11212. EXPECT_EQ("api", res->body);
  11213. }
  11214. TEST(MountTest, PathSegmentBoundary) {
  11215. Server svr;
  11216. svr.set_mount_point("/mount2", "./www2");
  11217. svr.set_mount_point("/", "./www");
  11218. auto port = svr.bind_to_any_port(HOST);
  11219. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11220. auto se = detail::scope_exit([&] {
  11221. svr.stop();
  11222. listen_thread.join();
  11223. ASSERT_FALSE(svr.is_running());
  11224. });
  11225. svr.wait_until_ready();
  11226. Client cli(HOST, port);
  11227. auto res = cli.Get("/mount2/dir/test.html");
  11228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11229. EXPECT_EQ(StatusCode::OK_200, res->status);
  11230. // "/mount2" must not match part-way through a path segment.
  11231. res = cli.Get("/mount2dir/test.html");
  11232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11234. // A mount point ending in '/' keeps matching every path below it.
  11235. res = cli.Get("/dir/test.html");
  11236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11237. EXPECT_EQ(StatusCode::OK_200, res->status);
  11238. }
  11239. TEST(MountTest, Redicect) {
  11240. Server svr;
  11241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.set_mount_point("/", "./www");
  11248. svr.wait_until_ready();
  11249. Client cli("localhost", PORT);
  11250. auto res = cli.Get("/dir/");
  11251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11252. EXPECT_EQ(StatusCode::OK_200, res->status);
  11253. res = cli.Get("/dir");
  11254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11255. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11256. res = cli.Get("/file");
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. EXPECT_EQ(StatusCode::OK_200, res->status);
  11259. res = cli.Get("/file/");
  11260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11262. cli.set_follow_location(true);
  11263. res = cli.Get("/dir");
  11264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11265. EXPECT_EQ(StatusCode::OK_200, res->status);
  11266. }
  11267. TEST(MountTest, MultibytesPathName) {
  11268. Server svr;
  11269. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11270. auto se = detail::scope_exit([&] {
  11271. svr.stop();
  11272. listen_thread.join();
  11273. ASSERT_FALSE(svr.is_running());
  11274. });
  11275. svr.set_mount_point("/", "./www");
  11276. svr.wait_until_ready();
  11277. Client cli("localhost", PORT);
  11278. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11280. EXPECT_EQ(StatusCode::OK_200, res->status);
  11281. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11282. }
  11283. // A mount point serves no path with an empty segment or one ending in '.' or
  11284. // a space, so a guard in the pre-routing handler sees the path of every file
  11285. // that is served
  11286. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11287. Server svr;
  11288. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11289. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11290. if (req.path == "/dir/test.html") {
  11291. res.status = StatusCode::Unauthorized_401;
  11292. return Server::HandlerResponse::Handled;
  11293. }
  11294. return Server::HandlerResponse::Unhandled;
  11295. });
  11296. auto port = svr.bind_to_any_port(HOST);
  11297. ASSERT_LT(0, port);
  11298. thread t = thread([&] { svr.listen_after_bind(); });
  11299. auto se = detail::scope_exit([&] {
  11300. svr.stop();
  11301. t.join();
  11302. ASSERT_FALSE(svr.is_running());
  11303. });
  11304. svr.wait_until_ready();
  11305. Client cli(HOST, port);
  11306. for (auto path :
  11307. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11308. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11309. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11310. "/dir/test.html%3A%3A$DATA"}) {
  11311. SCOPED_TRACE(path);
  11312. auto res = cli.Get(path);
  11313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11315. }
  11316. }
  11317. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11318. Server svr;
  11319. svr.set_mount_point("/", "./www");
  11320. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11321. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11322. auto port = svr.bind_to_any_port(HOST);
  11323. ASSERT_GT(port, 0);
  11324. thread t = thread([&] { svr.listen_after_bind(); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. t.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. });
  11330. svr.wait_until_ready();
  11331. Client cli(HOST, port);
  11332. auto res = cli.Get("/dir/test.abcde");
  11333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11334. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11335. res = cli.Get("/dir/test.html");
  11336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11337. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11338. }
  11339. #ifdef _WIN32
  11340. // Issue #2435: mmap::open() must succeed even when another handle holds
  11341. // the file open for writing (e.g. an active log file).
  11342. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11343. const char *path = "mmap_concurrent_writer_test.txt";
  11344. const char *content = "hello";
  11345. {
  11346. std::ofstream f(path, std::ios::binary);
  11347. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11348. }
  11349. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11350. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11351. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11352. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11353. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11354. detail::mmap m(path);
  11355. ASSERT_TRUE(m.is_open());
  11356. EXPECT_EQ(strlen(content), m.size());
  11357. char buf[8];
  11358. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11359. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11360. }
  11361. #endif
  11362. #ifndef _WIN32
  11363. // A directory or a device has no size to serve.
  11364. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11365. const char *path = "./mmap_not_regular_test_dir";
  11366. ASSERT_EQ(0, ::mkdir(path, 0755));
  11367. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11368. for (auto p : {path, "/dev/null"}) {
  11369. detail::mmap m(p);
  11370. EXPECT_FALSE(m.is_open()) << p;
  11371. EXPECT_EQ(0U, m.size()) << p;
  11372. }
  11373. Server svr;
  11374. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11375. res.set_file_content("/dev/null");
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. thread t = thread([&] { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. svr.stop();
  11381. t.join();
  11382. });
  11383. svr.wait_until_ready();
  11384. auto res = Client(HOST, port).Get("/null");
  11385. ASSERT_TRUE(res);
  11386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11387. }
  11388. #endif
  11389. #ifdef __linux__
  11390. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11391. TEST(MmapTest, FileIsNotMapped) {
  11392. const char *path = "mmap_not_mapped_test.txt";
  11393. {
  11394. std::ofstream f(path, std::ios::binary);
  11395. f << "hello";
  11396. }
  11397. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11398. detail::mmap m(path);
  11399. ASSERT_TRUE(m.is_open());
  11400. std::ifstream maps("/proc/self/maps");
  11401. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11402. std::istreambuf_iterator<char>());
  11403. EXPECT_EQ(std::string::npos, mappings.find(path));
  11404. }
  11405. #endif
  11406. TEST(KeepAliveTest, ReadTimeout) {
  11407. Server svr;
  11408. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11409. std::this_thread::sleep_for(std::chrono::seconds(2));
  11410. res.set_content("a", "text/plain");
  11411. });
  11412. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11413. res.set_content("b", "text/plain");
  11414. });
  11415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. listen_thread.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. });
  11421. svr.wait_until_ready();
  11422. Client cli("localhost", PORT);
  11423. cli.set_keep_alive(true);
  11424. cli.set_read_timeout(std::chrono::seconds(1));
  11425. auto resa = cli.Get("/a");
  11426. ASSERT_FALSE(resa);
  11427. EXPECT_EQ(Error::Read, resa.error());
  11428. auto resb = cli.Get("/b");
  11429. ASSERT_TRUE(resb);
  11430. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11431. EXPECT_EQ("b", resb->body);
  11432. }
  11433. TEST(KeepAliveTest, MaxCount) {
  11434. size_t keep_alive_max_count = 3;
  11435. Server svr;
  11436. svr.set_keep_alive_max_count(keep_alive_max_count);
  11437. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11438. res.set_content("Hello World!", "text/plain");
  11439. });
  11440. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11441. auto se = detail::scope_exit([&] {
  11442. svr.stop();
  11443. listen_thread.join();
  11444. ASSERT_FALSE(svr.is_running());
  11445. });
  11446. svr.wait_until_ready();
  11447. Client cli(HOST, PORT);
  11448. cli.set_keep_alive(true);
  11449. for (size_t i = 0; i < 5; i++) {
  11450. auto result = cli.Get("/hi");
  11451. ASSERT_TRUE(result);
  11452. EXPECT_EQ(StatusCode::OK_200, result->status);
  11453. if (i == keep_alive_max_count - 1) {
  11454. EXPECT_EQ("close", result->get_header_value("Connection"));
  11455. } else {
  11456. EXPECT_FALSE(result->has_header("Connection"));
  11457. }
  11458. }
  11459. }
  11460. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11461. // can pull the next one into the server's buffer. The server must serve it
  11462. // without waiting for the socket to become readable again. The keep-alive
  11463. // timeout outlasts the client's read timeout, so a request left waiting for it
  11464. // shows up as a missing response.
  11465. static void serve_pipelining_routes(Server &svr,
  11466. const std::function<void(int)> &client) {
  11467. svr.set_keep_alive_timeout(5);
  11468. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11469. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11470. });
  11471. svr.Post("/echo", [](const Request &req, Response &res) {
  11472. res.set_content("echo " + req.body, "text/plain");
  11473. });
  11474. auto port = svr.bind_to_any_port(HOST);
  11475. thread t = thread([&] { svr.listen_after_bind(); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. });
  11480. svr.wait_until_ready();
  11481. client(port);
  11482. }
  11483. static std::string
  11484. send_pipelined_requests(const std::vector<std::string> &parts) {
  11485. Server svr;
  11486. std::string res;
  11487. serve_pipelining_routes(svr, [&](int port) {
  11488. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11489. });
  11490. return res;
  11491. }
  11492. static void expect_in_order(const std::string &res,
  11493. const std::vector<std::string> &bodies) {
  11494. size_t pos = 0;
  11495. for (const auto &body : bodies) {
  11496. pos = res.find(body, pos);
  11497. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11498. pos += body.size();
  11499. }
  11500. }
  11501. TEST(KeepAliveTest, PipelinedRequests) {
  11502. auto res = send_pipelined_requests(
  11503. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11504. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11505. "Content-Length: 4\r\n\r\nbody"
  11506. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11507. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11508. }
  11509. // The second request starts in the server's buffer and ends on the socket.
  11510. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11511. auto res =
  11512. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11513. "GET /hi/2 HTTP/1.1\r\nHo",
  11514. "st: localhost\r\nConnection: close\r\n\r\n"});
  11515. expect_in_order(res, {"hi 1", "hi 2"});
  11516. }
  11517. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11518. // CRLF after a body does not turn into a 400 for the next request.
  11519. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11520. auto res = send_pipelined_requests(
  11521. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11522. "Content-Length: 4\r\n\r\nbody\r\n"
  11523. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11524. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11525. expect_in_order(res, {"echo body", "hi 2"});
  11526. }
  11527. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11528. // must not be served as the next request.
  11529. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11530. auto res = send_pipelined_requests(
  11531. {"INVALID REQUEST LINE\r\n\r\n"
  11532. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11533. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11534. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11535. }
  11536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11537. // Over TLS, the next request is held by the TLS library as already decrypted
  11538. // data rather than on the socket.
  11539. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11541. std::string res;
  11542. serve_pipelining_routes(svr, [&](int port) {
  11543. // One part, so all three requests arrive in one TLS record
  11544. EXPECT_TRUE(send_ssl_request_in_parts(
  11545. 2,
  11546. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11547. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11548. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11549. &res, port));
  11550. });
  11551. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11552. }
  11553. #endif
  11554. TEST(KeepAliveTest, Issue1041) {
  11555. Server svr;
  11556. svr.set_keep_alive_timeout(3);
  11557. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11558. res.set_content("Hello World!", "text/plain");
  11559. });
  11560. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11561. auto se = detail::scope_exit([&] {
  11562. svr.stop();
  11563. listen_thread.join();
  11564. ASSERT_FALSE(svr.is_running());
  11565. });
  11566. svr.wait_until_ready();
  11567. Client cli(HOST, PORT);
  11568. cli.set_keep_alive(true);
  11569. auto result = cli.Get("/hi");
  11570. ASSERT_TRUE(result);
  11571. EXPECT_EQ(StatusCode::OK_200, result->status);
  11572. std::this_thread::sleep_for(std::chrono::seconds(5));
  11573. result = cli.Get("/hi");
  11574. ASSERT_TRUE(result);
  11575. EXPECT_EQ(StatusCode::OK_200, result->status);
  11576. }
  11577. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11578. Server svr;
  11579. svr.set_keep_alive_max_count(0);
  11580. std::set<int> remote_ports;
  11581. svr.Get("/hi", [&](const Request &req, Response &res) {
  11582. remote_ports.insert(req.remote_port);
  11583. res.set_content("hi", "text/plain");
  11584. });
  11585. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11586. auto se = detail::scope_exit([&] {
  11587. svr.stop();
  11588. listen_thread.join();
  11589. ASSERT_FALSE(svr.is_running());
  11590. });
  11591. svr.wait_until_ready();
  11592. Client cli(HOST, PORT);
  11593. cli.set_keep_alive(true);
  11594. for (int i = 0; i < 3; i++) {
  11595. auto res = cli.Get("/hi");
  11596. ASSERT_TRUE(res);
  11597. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11598. }
  11599. // All three over one connection
  11600. EXPECT_EQ(1u, remote_ports.size());
  11601. }
  11602. // Forward declaration (see the base64_encode note).
  11603. namespace httplib {
  11604. namespace detail {
  11605. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11606. } // namespace detail
  11607. } // namespace httplib
  11608. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11609. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11610. #ifndef _WIN32
  11611. signal(SIGPIPE, SIG_IGN);
  11612. #endif
  11613. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11614. ASSERT_NE(INVALID_SOCKET, srv);
  11615. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11616. default_socket_options(srv);
  11617. sockaddr_in addr{};
  11618. addr.sin_family = AF_INET;
  11619. addr.sin_port = 0;
  11620. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11621. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11622. ASSERT_EQ(0, ::listen(srv, 2));
  11623. socklen_t addr_len = sizeof(addr);
  11624. ASSERT_EQ(0,
  11625. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11626. auto port = ntohs(addr.sin_port);
  11627. struct Peer {
  11628. socket_t sock = INVALID_SOCKET;
  11629. #ifdef CPPHTTPLIB_SSL_ENABLED
  11630. tls::session_t session = nullptr;
  11631. #endif
  11632. };
  11633. #ifdef CPPHTTPLIB_SSL_ENABLED
  11634. tls::ctx_t ctx = nullptr;
  11635. if (use_tls) {
  11636. ctx = tls::create_server_context();
  11637. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11638. nullptr);
  11639. }
  11640. auto ctx_se = detail::scope_exit([&] {
  11641. if (ctx) { tls::free_context(ctx); }
  11642. });
  11643. #endif
  11644. auto close_peer = [](Peer &peer) {
  11645. #ifdef CPPHTTPLIB_SSL_ENABLED
  11646. if (peer.session) { tls::free_session(peer.session); }
  11647. #endif
  11648. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11649. };
  11650. auto accept_peer = [&]() {
  11651. Peer peer;
  11652. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11653. peer.sock = ::accept(srv, nullptr, nullptr);
  11654. if (peer.sock == INVALID_SOCKET) { return peer; }
  11655. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11656. #ifdef CPPHTTPLIB_SSL_ENABLED
  11657. if (use_tls) {
  11658. peer.session = tls::create_session(ctx, peer.sock);
  11659. tls::TlsError err;
  11660. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11661. close_peer(peer);
  11662. return Peer();
  11663. }
  11664. }
  11665. #endif
  11666. return peer;
  11667. };
  11668. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11669. #ifdef CPPHTTPLIB_SSL_ENABLED
  11670. tls::TlsError err;
  11671. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11672. #endif
  11673. return detail::read_socket(peer.sock, buf, len, 0);
  11674. };
  11675. auto read_head = [&](const Peer &peer) {
  11676. std::string head;
  11677. char buf[1024];
  11678. while (head.find("\r\n\r\n") == std::string::npos) {
  11679. auto n = read_some(peer, buf, sizeof(buf));
  11680. if (n <= 0) { break; }
  11681. head.append(buf, static_cast<size_t>(n));
  11682. }
  11683. };
  11684. auto send_text = [](const Peer &peer, const std::string &text) {
  11685. #ifdef CPPHTTPLIB_SSL_ENABLED
  11686. tls::TlsError err;
  11687. if (peer.session) {
  11688. tls::write(peer.session, text.data(), text.size(), err);
  11689. return;
  11690. }
  11691. #endif
  11692. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11693. };
  11694. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11695. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11696. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11697. // Sent once the first response is read, so that it lands on an idle socket
  11698. std::promise<void> first_response_read;
  11699. auto first_response_read_future = first_response_read.get_future();
  11700. auto server_thread = std::thread([&] {
  11701. auto peer1 = accept_peer();
  11702. if (peer1.sock == INVALID_SOCKET) { return; }
  11703. read_head(peer1);
  11704. if (same_write) {
  11705. send_text(peer1, first + stray);
  11706. } else {
  11707. send_text(peer1, first);
  11708. first_response_read_future.wait_for(std::chrono::seconds(5));
  11709. send_text(peer1, stray);
  11710. }
  11711. // peer1 stays open, so only the unread data can tell the client
  11712. auto peer2 = accept_peer();
  11713. if (peer2.sock != INVALID_SOCKET) {
  11714. read_head(peer2);
  11715. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11716. "Connection: close\r\n\r\nsecond");
  11717. close_peer(peer2);
  11718. }
  11719. close_peer(peer1);
  11720. });
  11721. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11722. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11723. std::to_string(port));
  11724. #ifdef CPPHTTPLIB_SSL_ENABLED
  11725. cli.enable_server_certificate_verification(false);
  11726. #endif
  11727. cli.set_keep_alive(true);
  11728. cli.set_read_timeout(5, 0);
  11729. auto res = cli.Get("/1");
  11730. first_response_read.set_value();
  11731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11732. EXPECT_EQ("first", res->body);
  11733. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11734. res = cli.Get("/2");
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. EXPECT_EQ(StatusCode::OK_200, res->status);
  11737. EXPECT_EQ("second", res->body);
  11738. }
  11739. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11740. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11741. }
  11742. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11743. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11744. }
  11745. #ifdef CPPHTTPLIB_SSL_ENABLED
  11746. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11747. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11748. }
  11749. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11750. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11751. }
  11752. #endif
  11753. TEST(KeepAliveTest, Issue1959) {
  11754. Server svr;
  11755. svr.set_keep_alive_timeout(5);
  11756. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11757. res.set_content("a", "text/plain");
  11758. });
  11759. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11760. auto se = detail::scope_exit([&] {
  11761. if (!svr.is_running()) return;
  11762. svr.stop();
  11763. listen_thread.join();
  11764. ASSERT_FALSE(svr.is_running());
  11765. });
  11766. svr.wait_until_ready();
  11767. Client cli("localhost", PORT);
  11768. cli.set_keep_alive(true);
  11769. using namespace std::chrono;
  11770. auto start = steady_clock::now();
  11771. cli.Get("/a");
  11772. svr.stop();
  11773. listen_thread.join();
  11774. auto end = steady_clock::now();
  11775. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11776. EXPECT_LT(elapsed, 5000);
  11777. }
  11778. #ifdef CPPHTTPLIB_SSL_ENABLED
  11779. TEST(KeepAliveTest, SSLClientReconnection) {
  11780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11781. ASSERT_TRUE(svr.is_valid());
  11782. svr.set_keep_alive_timeout(1);
  11783. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11784. res.set_content("Hello World!", "text/plain");
  11785. });
  11786. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11787. auto se = detail::scope_exit([&] {
  11788. svr.stop();
  11789. listen_thread.join();
  11790. ASSERT_FALSE(svr.is_running());
  11791. });
  11792. svr.wait_until_ready();
  11793. SSLClient cli(HOST, PORT);
  11794. cli.enable_server_certificate_verification(false);
  11795. cli.set_keep_alive(true);
  11796. auto result = cli.Get("/hi");
  11797. ASSERT_TRUE(result);
  11798. EXPECT_EQ(StatusCode::OK_200, result->status);
  11799. result = cli.Get("/hi");
  11800. ASSERT_TRUE(result);
  11801. EXPECT_EQ(StatusCode::OK_200, result->status);
  11802. std::this_thread::sleep_for(std::chrono::seconds(2));
  11803. // Recoonect
  11804. result = cli.Get("/hi");
  11805. ASSERT_TRUE(result);
  11806. EXPECT_EQ(StatusCode::OK_200, result->status);
  11807. result = cli.Get("/hi");
  11808. ASSERT_TRUE(result);
  11809. EXPECT_EQ(StatusCode::OK_200, result->status);
  11810. }
  11811. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11813. ASSERT_TRUE(svr.is_valid());
  11814. svr.set_keep_alive_timeout(1);
  11815. std::string content = "reconnect";
  11816. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11817. res.set_content("Hello World!", "text/plain");
  11818. });
  11819. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11820. auto se = detail::scope_exit([&] {
  11821. svr.stop();
  11822. listen_thread.join();
  11823. ASSERT_FALSE(svr.is_running());
  11824. });
  11825. svr.wait_until_ready();
  11826. SSLClient cli(HOST, PORT);
  11827. cli.enable_server_certificate_verification(false);
  11828. cli.set_keep_alive(true);
  11829. auto result = cli.Post(
  11830. "/hi", content.size(),
  11831. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11832. sink.write(content.c_str(), content.size());
  11833. return true;
  11834. },
  11835. "text/plain");
  11836. ASSERT_TRUE(result);
  11837. EXPECT_EQ(200, result->status);
  11838. std::this_thread::sleep_for(std::chrono::seconds(2));
  11839. // Recoonect
  11840. result = cli.Post(
  11841. "/hi", content.size(),
  11842. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11843. sink.write(content.c_str(), content.size());
  11844. return true;
  11845. },
  11846. "text/plain");
  11847. ASSERT_TRUE(result);
  11848. EXPECT_EQ(200, result->status);
  11849. result = cli.Post(
  11850. "/hi", content.size(),
  11851. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11852. sink.write(content.c_str(), content.size());
  11853. return true;
  11854. },
  11855. "text/plain");
  11856. ASSERT_TRUE(result);
  11857. EXPECT_EQ(200, result->status);
  11858. }
  11859. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11860. using namespace httplib::tls;
  11861. {
  11862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11863. ASSERT_TRUE(svr.is_valid());
  11864. svr.Get("/sni", [&](const Request &req, Response &res) {
  11865. std::string expected = req.sni();
  11866. EXPECT_EQ(expected, req.get_param_value("expected"));
  11867. res.set_content("ok", "text/plain");
  11868. });
  11869. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11870. auto se = detail::scope_exit([&] {
  11871. svr.stop();
  11872. listen_thread.join();
  11873. ASSERT_FALSE(svr.is_running());
  11874. });
  11875. svr.wait_until_ready();
  11876. {
  11877. SSLClient cli("localhost", PORT);
  11878. cli.enable_server_certificate_verification(false);
  11879. auto res = cli.Get("/sni?expected=localhost");
  11880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11881. }
  11882. {
  11883. SSLClient cli("::1", PORT);
  11884. cli.enable_server_certificate_verification(false);
  11885. auto res = cli.Get("/sni?expected=");
  11886. // NOTE: This may fail if the server is listening on IPv4 only
  11887. // (e.g., when localhost resolves to 127.0.0.1 only)
  11888. if (res) {
  11889. EXPECT_EQ(StatusCode::OK_200, res->status);
  11890. } else {
  11891. EXPECT_EQ(Error::Connection, res.error());
  11892. }
  11893. }
  11894. }
  11895. }
  11896. // The SNI of a failed handshake does not reach the next connection that the
  11897. // same worker thread serves
  11898. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11900. ASSERT_TRUE(svr.is_valid());
  11901. svr.new_task_queue = [] { return new ThreadPool(1); };
  11902. svr.Get("/sni", [](const Request &req, Response &res) {
  11903. res.set_content(req.sni(), "text/plain");
  11904. });
  11905. auto port = svr.bind_to_any_port("127.0.0.1");
  11906. ASSERT_LT(0, port);
  11907. thread t = thread([&] { svr.listen_after_bind(); });
  11908. auto se = detail::scope_exit([&] {
  11909. svr.stop();
  11910. t.join();
  11911. ASSERT_FALSE(svr.is_running());
  11912. });
  11913. svr.wait_until_ready();
  11914. {
  11915. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11916. SSLClient cli("localhost", port);
  11917. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11918. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11919. auto res = cli.Get("/sni");
  11920. ASSERT_FALSE(res);
  11921. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11922. }
  11923. // An IP host sends no SNI (RFC 6066)
  11924. SSLClient cli("127.0.0.1", port);
  11925. cli.enable_server_certificate_verification(false);
  11926. auto res = cli.Get("/sni");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. EXPECT_EQ("", res->body);
  11929. }
  11930. #endif
  11931. TEST(ClientProblemDetectionTest, ContentProvider) {
  11932. Server svr;
  11933. size_t content_length = 1024 * 1024;
  11934. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11935. res.set_content_provider(
  11936. content_length, "text/plain",
  11937. [&](size_t offset, size_t length, DataSink &sink) {
  11938. auto out_len = std::min(length, static_cast<size_t>(1024));
  11939. std::string out(out_len, '@');
  11940. sink.write(out.data(), out_len);
  11941. return offset < 4096;
  11942. },
  11943. [](bool success) { ASSERT_FALSE(success); });
  11944. });
  11945. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11946. res.set_content_provider(
  11947. 0, "text/plain",
  11948. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11949. EXPECT_TRUE(false);
  11950. return true;
  11951. },
  11952. [](bool success) { ASSERT_FALSE(success); });
  11953. });
  11954. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11955. auto se = detail::scope_exit([&] {
  11956. svr.stop();
  11957. listen_thread.join();
  11958. ASSERT_FALSE(svr.is_running());
  11959. });
  11960. svr.wait_until_ready();
  11961. Client cli("localhost", PORT);
  11962. {
  11963. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11964. size_t /*data_length*/) { return false; });
  11965. ASSERT_FALSE(res);
  11966. }
  11967. {
  11968. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11969. size_t /*data_length*/) { return false; });
  11970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11971. }
  11972. }
  11973. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11974. // A provider that reports success without writing anything and without
  11975. // calling done() used to be handed the same offset and length again on every
  11976. // pass, so it spun for as long as the peer stayed connected.
  11977. Server svr;
  11978. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11979. res.set_content("ok", "text/plain");
  11980. });
  11981. auto port = svr.bind_to_any_port(HOST);
  11982. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11983. auto se = detail::scope_exit([&] {
  11984. svr.stop();
  11985. listen_thread.join();
  11986. ASSERT_FALSE(svr.is_running());
  11987. });
  11988. svr.wait_until_ready();
  11989. std::atomic<int> call_count{0};
  11990. Client cli(HOST, port);
  11991. auto res = cli.Post(
  11992. "/", 1024,
  11993. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11994. // Give up after enough passes to show the spin, so that losing the
  11995. // check below fails this test instead of hanging it.
  11996. return ++call_count < 100;
  11997. },
  11998. "text/plain");
  11999. ASSERT_FALSE(res);
  12000. EXPECT_EQ(Error::Write, res.error());
  12001. EXPECT_EQ(1, call_count.load());
  12002. }
  12003. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12004. // A writer only has to assign `write`. The other three used to be left as
  12005. // empty std::functions, so a provider calling one threw
  12006. // std::bad_function_call out of the thread running it and took the whole
  12007. // process down.
  12008. DataSink sink;
  12009. std::string written;
  12010. sink.write = [&](const char *data, size_t data_len) {
  12011. written.append(data, data_len);
  12012. return true;
  12013. };
  12014. EXPECT_TRUE(sink.is_writable());
  12015. sink.done();
  12016. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12017. EXPECT_TRUE(written.empty());
  12018. }
  12019. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12020. // A sink that cannot carry trailers still has to finish.
  12021. DataSink sink;
  12022. auto done_count = 0;
  12023. sink.done = [&]() { done_count++; };
  12024. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12025. EXPECT_EQ(1, done_count);
  12026. }
  12027. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12028. Server svr;
  12029. const std::string body(4096, 'x');
  12030. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12031. res.set_content_provider(body.size(), "text/plain",
  12032. [&](size_t offset, size_t length, DataSink &sink) {
  12033. sink.write(body.data() + offset, length);
  12034. sink.done();
  12035. return true;
  12036. });
  12037. });
  12038. auto port = svr.bind_to_any_port(HOST);
  12039. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12040. auto se = detail::scope_exit([&] {
  12041. svr.stop();
  12042. listen_thread.join();
  12043. ASSERT_FALSE(svr.is_running());
  12044. });
  12045. svr.wait_until_ready();
  12046. Client cli(HOST, port);
  12047. auto res = cli.Get("/");
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. EXPECT_EQ(StatusCode::OK_200, res->status);
  12050. EXPECT_EQ(body, res->body);
  12051. }
  12052. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12053. Server svr;
  12054. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12055. res.set_content_provider(
  12056. 1024, "text/plain",
  12057. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12058. sink.write("hello", 5);
  12059. sink.done(); // short of the 1024 bytes the response promised
  12060. return true;
  12061. });
  12062. });
  12063. auto port = svr.bind_to_any_port(HOST);
  12064. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12065. auto se = detail::scope_exit([&] {
  12066. svr.stop();
  12067. listen_thread.join();
  12068. ASSERT_FALSE(svr.is_running());
  12069. });
  12070. svr.wait_until_ready();
  12071. Client cli(HOST, port);
  12072. cli.set_read_timeout(5, 0);
  12073. // The response is short of its Content-Length, so the client cannot read a
  12074. // complete body. What matters is that this returns at all: a no-op done()
  12075. // would leave the writer looping over a provider that never makes progress.
  12076. auto res = cli.Get("/");
  12077. EXPECT_FALSE(res);
  12078. }
  12079. // Read as the next response by a peer that sees it after a framed body.
  12080. static const std::string smuggled_response =
  12081. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12082. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12083. Server svr;
  12084. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12085. res.set_content_provider(
  12086. 5, "text/plain",
  12087. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12088. auto data = "AAAAA" + smuggled_response;
  12089. sink.write(data.data(), data.size());
  12090. return true;
  12091. });
  12092. });
  12093. thread t = thread([&] { svr.listen(HOST, PORT); });
  12094. auto se = detail::scope_exit([&] {
  12095. svr.stop();
  12096. t.join();
  12097. ASSERT_FALSE(svr.is_running());
  12098. });
  12099. svr.wait_until_ready();
  12100. std::string resp;
  12101. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12102. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12103. resp.clear();
  12104. ASSERT_TRUE(send_request(
  12105. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12106. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12107. }
  12108. TEST(NoContentTest, BodyIsNotSent) {
  12109. Server svr;
  12110. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12111. res.status = StatusCode::NoContent_204;
  12112. res.set_content(smuggled_response, "text/plain");
  12113. });
  12114. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12115. res.status = StatusCode::NotModified_304;
  12116. res.set_chunked_content_provider(
  12117. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12118. sink.write(smuggled_response.data(), smuggled_response.size());
  12119. sink.done();
  12120. return true;
  12121. });
  12122. });
  12123. thread t = thread([&] { svr.listen(HOST, PORT); });
  12124. auto se = detail::scope_exit([&] {
  12125. svr.stop();
  12126. t.join();
  12127. ASSERT_FALSE(svr.is_running());
  12128. });
  12129. svr.wait_until_ready();
  12130. for (auto path : {"/204", "/304"}) {
  12131. std::string resp;
  12132. ASSERT_TRUE(send_request(
  12133. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12134. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12135. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12136. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12137. }
  12138. }
  12139. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12140. Server svr;
  12141. std::atomic<bool> smuggled(false);
  12142. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12143. res.set_content("ok", "text/plain");
  12144. });
  12145. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12146. smuggled = true;
  12147. });
  12148. auto port = svr.bind_to_any_port(HOST);
  12149. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12150. auto se = detail::scope_exit([&] {
  12151. svr.stop();
  12152. listen_thread.join();
  12153. ASSERT_FALSE(svr.is_running());
  12154. });
  12155. svr.wait_until_ready();
  12156. // What follows the body would be read as the next request.
  12157. Client cli(HOST, port);
  12158. auto res = cli.Post(
  12159. "/", 5,
  12160. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12161. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12162. sink.write(data.data(), data.size());
  12163. return true;
  12164. },
  12165. "text/plain");
  12166. ASSERT_FALSE(res);
  12167. EXPECT_EQ(Error::Write, res.error());
  12168. EXPECT_FALSE(smuggled);
  12169. }
  12170. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12171. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12172. // The compressed path builds the whole body before connecting, so this
  12173. // fails client-side and never reaches a server.
  12174. Client cli(HOST, PORT);
  12175. cli.set_compress(true);
  12176. auto res = cli.Post(
  12177. "/", 1024,
  12178. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12179. sink.write("hello", 5);
  12180. sink.done(); // short of the 1024 bytes the request announced
  12181. return true;
  12182. },
  12183. "text/plain");
  12184. ASSERT_FALSE(res);
  12185. EXPECT_EQ(Error::Write, res.error());
  12186. }
  12187. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12188. Server svr;
  12189. std::string received;
  12190. size_t content_length_count = 0;
  12191. bool has_transfer_encoding = true;
  12192. svr.Post("/echo", [&](const Request &req, Response &res) {
  12193. received = req.body;
  12194. content_length_count = req.get_header_value_count("Content-Length");
  12195. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12196. res.set_content("ok", "text/plain");
  12197. });
  12198. svr.Get("/next", [](const Request &, Response &res) {
  12199. res.set_content("next", "text/plain");
  12200. });
  12201. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12202. auto se = detail::scope_exit([&] {
  12203. svr.stop();
  12204. listen_thread.join();
  12205. ASSERT_FALSE(svr.is_running());
  12206. });
  12207. svr.wait_until_ready();
  12208. Client cli(HOST, PORT);
  12209. cli.set_keep_alive(true);
  12210. cli.set_compress(true);
  12211. const std::string body = "hello world";
  12212. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12213. auto res = cli.Post("/echo", headers, body, "text/plain");
  12214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12215. EXPECT_EQ(StatusCode::OK_200, res->status);
  12216. EXPECT_EQ(body, received);
  12217. EXPECT_EQ(1u, content_length_count);
  12218. EXPECT_FALSE(has_transfer_encoding);
  12219. // The rest of a truncated body would be read as this request
  12220. auto res2 = cli.Get("/next");
  12221. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12222. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12223. EXPECT_EQ("next", res2->body);
  12224. }
  12225. #endif
  12226. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12227. Server svr;
  12228. std::string received;
  12229. size_t content_length_count = 1;
  12230. bool has_transfer_encoding = false;
  12231. svr.Post("/echo", [&](const Request &req, Response &res) {
  12232. received = req.body;
  12233. content_length_count = req.get_header_value_count("Content-Length");
  12234. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12235. res.set_content("ok", "text/plain");
  12236. });
  12237. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. listen_thread.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. Client cli(HOST, PORT);
  12245. cli.set_keep_alive(true);
  12246. const std::string body = "hello world";
  12247. Headers headers = {{"Content-Length", "5"}};
  12248. auto res = cli.Post(
  12249. "/echo", headers,
  12250. [&](size_t /*offset*/, DataSink &sink) {
  12251. sink.write(body.data(), body.size());
  12252. sink.done();
  12253. return true;
  12254. },
  12255. "text/plain");
  12256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12257. EXPECT_EQ(StatusCode::OK_200, res->status);
  12258. EXPECT_EQ(body, received);
  12259. EXPECT_EQ(0u, content_length_count);
  12260. EXPECT_TRUE(has_transfer_encoding);
  12261. }
  12262. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12263. Server svr;
  12264. svr.set_error_handler([](Request const &, Response &res) -> void {
  12265. res.set_chunked_content_provider(
  12266. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12267. sink.os << "hello";
  12268. sink.os << "world";
  12269. sink.done();
  12270. return true;
  12271. });
  12272. });
  12273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. listen_thread.join();
  12277. ASSERT_FALSE(svr.is_running());
  12278. });
  12279. svr.wait_until_ready();
  12280. Client cli("localhost", PORT);
  12281. auto res = cli.Get("/");
  12282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12283. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12284. EXPECT_EQ("helloworld", res->body);
  12285. }
  12286. // A body set after a content provider must replace it, not be sent through it.
  12287. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12288. Server svr;
  12289. svr.set_mount_point("/", "./www");
  12290. svr.set_file_request_handler([](const Request &req, Response &res) {
  12291. if (req.path == "/dir/test.html") {
  12292. res.status = StatusCode::Forbidden_403;
  12293. res.set_content(std::string(5000, 'D'), "text/plain");
  12294. } else if (req.path == "/file") {
  12295. res.status = StatusCode::Forbidden_403;
  12296. res.body = "Denied";
  12297. }
  12298. });
  12299. auto port = svr.bind_to_any_port(HOST);
  12300. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12301. auto se = detail::scope_exit([&] {
  12302. svr.stop();
  12303. t.join();
  12304. ASSERT_FALSE(svr.is_running());
  12305. });
  12306. svr.wait_until_ready();
  12307. Client cli(HOST, port);
  12308. {
  12309. auto res = cli.Get("/dir/test.html");
  12310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12311. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12312. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12313. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12314. }
  12315. {
  12316. auto res = cli.Get("/file");
  12317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12318. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12319. EXPECT_EQ("Denied", res->body);
  12320. }
  12321. {
  12322. auto res = cli.Get("/dir/index.html");
  12323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12324. EXPECT_EQ(StatusCode::OK_200, res->status);
  12325. EXPECT_EQ(0U, res->body.find("<html>"));
  12326. }
  12327. }
  12328. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12329. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12330. Server svr;
  12331. std::vector<bool> released;
  12332. std::mutex released_mutex;
  12333. auto releaser = [&](bool success) {
  12334. std::lock_guard<std::mutex> guard(released_mutex);
  12335. released.push_back(success);
  12336. };
  12337. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12338. return sink.write(&"hello"[offset], length);
  12339. };
  12340. svr.Get("/sized", [&](const Request &, Response &res) {
  12341. res.status = StatusCode::NotFound_404;
  12342. res.set_content_provider(5, "text/plain", provider, releaser);
  12343. });
  12344. svr.Get("/chunked", [&](const Request &, Response &res) {
  12345. res.status = StatusCode::ServiceUnavailable_503;
  12346. res.set_chunked_content_provider(
  12347. "text/plain",
  12348. [](size_t, DataSink &sink) {
  12349. sink.os << "chunk";
  12350. sink.done();
  12351. return true;
  12352. },
  12353. releaser);
  12354. });
  12355. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12356. res.set_content_provider(5, "text/plain", provider, releaser);
  12357. throw std::runtime_error("after the provider");
  12358. });
  12359. svr.set_error_handler([](const Request &req, Response &res) {
  12360. // Leave the exception handler's content to it.
  12361. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12362. res.set_content(std::string(1000, 'E'), "text/html");
  12363. return Server::HandlerResponse::Handled;
  12364. });
  12365. svr.set_exception_handler(
  12366. [](const Request &, Response &res, std::exception_ptr) {
  12367. res.status = StatusCode::InternalServerError_500;
  12368. res.set_content(std::string(1000, 'X'), "text/html");
  12369. });
  12370. auto port = svr.bind_to_any_port(HOST);
  12371. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12372. auto se = detail::scope_exit([&] {
  12373. svr.stop();
  12374. t.join();
  12375. ASSERT_FALSE(svr.is_running());
  12376. });
  12377. svr.wait_until_ready();
  12378. Client cli(HOST, port);
  12379. {
  12380. auto res = cli.Get("/sized");
  12381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12383. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12384. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12385. }
  12386. {
  12387. auto res = cli.Get("/chunked");
  12388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12389. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12390. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12391. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12392. }
  12393. {
  12394. auto res = cli.Get("/throw");
  12395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12396. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12397. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12398. }
  12399. std::lock_guard<std::mutex> guard(released_mutex);
  12400. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12401. }
  12402. #endif
  12403. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12404. Server svr;
  12405. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12406. return sink.write(&"abc"[offset], length);
  12407. };
  12408. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12409. res.set_file_content("./www/dir/test.html");
  12410. res.set_content("body", "text/plain");
  12411. });
  12412. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12413. res.set_content(std::string(100, 'B'), "text/plain");
  12414. res.set_file_content("./www/dir/test.html");
  12415. });
  12416. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12417. res.set_content(std::string(100, 'B'), "text/plain");
  12418. res.set_content_provider(3, "text/x-provider", abc);
  12419. });
  12420. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12421. res.set_content_provider(3, "text/x-provider", abc);
  12422. res.set_content(std::string(100, 'B'), "text/plain");
  12423. });
  12424. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12425. res.set_content_provider(3, "text/x-provider", abc);
  12426. res.set_file_content("./www/dir/test.html", "text/x-file");
  12427. });
  12428. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12429. res.set_file_content("./www/dir/test.html");
  12430. res.set_header("Content-Type", "text/x-handler");
  12431. });
  12432. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12433. res.set_content_provider(3, "text/plain", abc);
  12434. res.body = "direct";
  12435. });
  12436. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12437. res.set_file_content("./www/dir/test.html");
  12438. res.body = "direct";
  12439. });
  12440. auto port = svr.bind_to_any_port(HOST);
  12441. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. });
  12447. svr.wait_until_ready();
  12448. Client cli(HOST, port);
  12449. auto expect_body = [&](const char *path, const std::string &body,
  12450. const std::string &type) {
  12451. // Uncompressed, so Content-Length can be compared with the body.
  12452. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12453. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12454. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12455. EXPECT_EQ(body, res->body) << path;
  12456. EXPECT_EQ(std::to_string(body.size()),
  12457. res->get_header_value("Content-Length"))
  12458. << path;
  12459. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12460. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12461. };
  12462. expect_body("/file-then-body", "body", "text/plain");
  12463. expect_body("/body-then-file", "test.html", "text/html");
  12464. expect_body("/body-then-provider", "abc", "text/x-provider");
  12465. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12466. expect_body("/provider-then-file", "test.html", "text/x-file");
  12467. expect_body("/file-then-header", "test.html", "text/x-handler");
  12468. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12469. expect_body("/file-then-direct-body", "direct", "text/plain");
  12470. // Ranges are checked against the body, not the dropped provider.
  12471. {
  12472. auto res = cli.Get("/provider-then-direct-body",
  12473. Headers{{make_range_header({{1, 2}})}});
  12474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12476. EXPECT_EQ("ir", res->body);
  12477. }
  12478. {
  12479. auto res = cli.Get("/file-then-direct-body",
  12480. Headers{{make_range_header({{7, 8}})}});
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12483. }
  12484. }
  12485. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12486. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12487. const char *path = "./truncated_while_served.txt";
  12488. const size_t size = 32 * 1024 * 1024;
  12489. {
  12490. std::ofstream f(path, std::ios::binary);
  12491. f << std::string(size, 'x');
  12492. }
  12493. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12494. // Over TLS, where the bytes are encrypted in this process rather than
  12495. // copied by send().
  12496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12497. svr.Get("/file", [&](const Request &, Response &res) {
  12498. res.set_file_content(path, "text/plain");
  12499. });
  12500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. thread.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. });
  12506. svr.wait_until_ready();
  12507. // The file shrinks once the first bytes are in, as a rewrite in place
  12508. // would, and reading the mapping past its new end used to raise SIGBUS.
  12509. SSLClient cli(HOST, PORT);
  12510. cli.enable_server_certificate_verification(false);
  12511. size_t received = 0;
  12512. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12513. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12514. received += len;
  12515. return true;
  12516. });
  12517. EXPECT_FALSE(res);
  12518. EXPECT_LT(received, size);
  12519. }
  12520. #endif
  12521. // Forward declaration (see the base64_encode note).
  12522. namespace httplib {
  12523. namespace detail {
  12524. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12525. const std::string &content_type,
  12526. EncodingType encoding);
  12527. } // namespace detail
  12528. } // namespace httplib
  12529. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12530. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12531. ASSERT_TRUE(mm->is_open());
  12532. Response res;
  12533. detail::set_file_content_provider(res, mm, "text/html",
  12534. detail::EncodingType::None);
  12535. std::string out;
  12536. DataSink sink;
  12537. sink.write = [&](const char *d, size_t l) {
  12538. out.append(d, l);
  12539. return true;
  12540. };
  12541. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12542. EXPECT_EQ("test.html", out);
  12543. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12544. EXPECT_EQ("test.html", out);
  12545. }
  12546. TEST(LongPollingTest, ClientCloseDetection) {
  12547. Server svr;
  12548. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12549. res.set_chunked_content_provider(
  12550. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12551. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12552. sink.os << "hello";
  12553. auto count = 10;
  12554. while (count > 0 && sink.is_writable()) {
  12555. this_thread::sleep_for(chrono::milliseconds(10));
  12556. count--;
  12557. }
  12558. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12559. return true;
  12560. });
  12561. });
  12562. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12563. auto se = detail::scope_exit([&] {
  12564. svr.stop();
  12565. listen_thread.join();
  12566. ASSERT_FALSE(svr.is_running());
  12567. });
  12568. svr.wait_until_ready();
  12569. Client cli("localhost", PORT);
  12570. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12571. EXPECT_EQ("hello", string(data, data_length));
  12572. return false; // close the socket immediately.
  12573. });
  12574. ASSERT_FALSE(res);
  12575. }
  12576. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12577. Server svr;
  12578. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12579. res.set_chunked_content_provider(
  12580. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12581. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12582. sink.os << "hello";
  12583. EXPECT_TRUE(sink.os.good());
  12584. // Wait for the client to close the connection
  12585. auto count = 10;
  12586. while (count > 0 && sink.is_writable()) {
  12587. this_thread::sleep_for(chrono::milliseconds(10));
  12588. count--;
  12589. }
  12590. // After client disconnect, write repeatedly until the socket
  12591. // write actually fails (small writes may be absorbed by the
  12592. // kernel buffer)
  12593. std::string chunk(1024, 'x');
  12594. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12595. sink.os << chunk;
  12596. }
  12597. EXPECT_TRUE(sink.os.fail());
  12598. return true;
  12599. });
  12600. });
  12601. auto port = svr.bind_to_any_port("localhost");
  12602. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. listen_thread.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. });
  12608. svr.wait_until_ready();
  12609. Client cli("localhost", port);
  12610. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12611. EXPECT_EQ("hello", string(data, data_length));
  12612. return false; // close the socket immediately.
  12613. });
  12614. ASSERT_FALSE(res);
  12615. }
  12616. TEST(GetWithParametersTest, GetWithParameters) {
  12617. Server svr;
  12618. svr.Get("/", [&](const Request &req, Response &) {
  12619. EXPECT_EQ("world", req.get_param_value("hello"));
  12620. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12621. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12622. });
  12623. svr.Get("/params", [&](const Request &req, Response &) {
  12624. EXPECT_EQ("world", req.get_param_value("hello"));
  12625. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12626. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12627. });
  12628. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12629. EXPECT_EQ("resource-id", req.matches[1]);
  12630. EXPECT_EQ("foo", req.get_param_value("param1"));
  12631. EXPECT_EQ("bar", req.get_param_value("param2"));
  12632. });
  12633. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12634. EXPECT_EQ("user-id", req.path_params.at("id"));
  12635. EXPECT_EQ("foo", req.get_param_value("param1"));
  12636. EXPECT_EQ("bar", req.get_param_value("param2"));
  12637. });
  12638. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12639. auto se = detail::scope_exit([&] {
  12640. svr.stop();
  12641. listen_thread.join();
  12642. ASSERT_FALSE(svr.is_running());
  12643. });
  12644. svr.wait_until_ready();
  12645. {
  12646. Client cli(HOST, PORT);
  12647. Params params;
  12648. params.emplace("hello", "world");
  12649. params.emplace("hello2", "world2");
  12650. params.emplace("hello3", "world3");
  12651. auto res = cli.Get("/", params, Headers{});
  12652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12653. EXPECT_EQ(StatusCode::OK_200, res->status);
  12654. }
  12655. {
  12656. Client cli(HOST, PORT);
  12657. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(StatusCode::OK_200, res->status);
  12660. }
  12661. {
  12662. Client cli(HOST, PORT);
  12663. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12665. EXPECT_EQ(StatusCode::OK_200, res->status);
  12666. }
  12667. {
  12668. Client cli(HOST, PORT);
  12669. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12671. EXPECT_EQ(StatusCode::OK_200, res->status);
  12672. }
  12673. }
  12674. TEST(GetWithParametersTest, GetWithParameters2) {
  12675. Server svr;
  12676. svr.Get("/", [&](const Request &req, Response &res) {
  12677. auto text = req.get_param_value("hello");
  12678. res.set_content(text, "text/plain");
  12679. });
  12680. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12681. auto se = detail::scope_exit([&] {
  12682. svr.stop();
  12683. listen_thread.join();
  12684. ASSERT_FALSE(svr.is_running());
  12685. });
  12686. svr.wait_until_ready();
  12687. Client cli("localhost", PORT);
  12688. Params params;
  12689. params.emplace("hello", "world");
  12690. std::string body;
  12691. auto res = cli.Get("/", params, Headers{},
  12692. [&](const char *data, size_t data_length) {
  12693. body.append(data, data_length);
  12694. return true;
  12695. });
  12696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12697. EXPECT_EQ(StatusCode::OK_200, res->status);
  12698. EXPECT_EQ("world", body);
  12699. }
  12700. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12701. Server svr;
  12702. svr.Get("/search", [&](const Request &req, Response &res) {
  12703. auto q = req.get_param_value("q");
  12704. res.set_content(q, "text/plain");
  12705. });
  12706. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12707. auto se = detail::scope_exit([&] {
  12708. svr.stop();
  12709. listen_thread.join();
  12710. ASSERT_FALSE(svr.is_running());
  12711. });
  12712. svr.wait_until_ready();
  12713. Client cli("localhost", PORT);
  12714. // Verify that Get(path, params) works without requiring Headers argument
  12715. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12717. EXPECT_EQ(StatusCode::OK_200, res->status);
  12718. EXPECT_EQ("cpp-httplib", res->body);
  12719. }
  12720. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12721. auto host = "httpbingo.org";
  12722. auto path = std::string{"/range/32"};
  12723. #ifdef CPPHTTPLIB_SSL_ENABLED
  12724. SSLClient cli(host);
  12725. #else
  12726. Client cli(host);
  12727. #endif
  12728. cli.set_default_headers({make_range_header({{1, 10}})});
  12729. cli.set_connection_timeout(5);
  12730. {
  12731. auto res = cli.Get(path);
  12732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12733. EXPECT_EQ("bcdefghijk", res->body);
  12734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12735. }
  12736. {
  12737. auto res = cli.Get(path);
  12738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12739. EXPECT_EQ("bcdefghijk", res->body);
  12740. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12741. }
  12742. }
  12743. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12744. Server svr;
  12745. svr.set_default_headers({{"Hello", "World"}});
  12746. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12747. res.set_content("ok", "text/plain");
  12748. });
  12749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12750. auto se = detail::scope_exit([&] {
  12751. svr.stop();
  12752. listen_thread.join();
  12753. ASSERT_FALSE(svr.is_running());
  12754. });
  12755. svr.wait_until_ready();
  12756. Client cli("localhost", PORT);
  12757. auto res = cli.Get("/");
  12758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12759. EXPECT_EQ(StatusCode::OK_200, res->status);
  12760. EXPECT_EQ("ok", res->body);
  12761. EXPECT_EQ("World", res->get_header_value("Hello"));
  12762. }
  12763. #ifdef CPPHTTPLIB_SSL_ENABLED
  12764. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. ASSERT_TRUE(svr.is_valid());
  12767. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12768. std::this_thread::sleep_for(std::chrono::seconds(2));
  12769. res.set_content("a", "text/plain");
  12770. });
  12771. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12772. res.set_content("b", "text/plain");
  12773. });
  12774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12775. auto se = detail::scope_exit([&] {
  12776. svr.stop();
  12777. listen_thread.join();
  12778. ASSERT_FALSE(svr.is_running());
  12779. });
  12780. svr.wait_until_ready();
  12781. SSLClient cli("localhost", PORT);
  12782. cli.enable_server_certificate_verification(false);
  12783. cli.set_keep_alive(true);
  12784. cli.set_read_timeout(std::chrono::seconds(1));
  12785. auto resa = cli.Get("/a");
  12786. ASSERT_TRUE(!resa);
  12787. EXPECT_EQ(Error::Read, resa.error());
  12788. auto resb = cli.Get("/b");
  12789. ASSERT_TRUE(resb);
  12790. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12791. EXPECT_EQ("b", resb->body);
  12792. }
  12793. // Closing an idle keep-alive connection sends close_notify and returns. The
  12794. // server must not wait for the client's close_notify: an idle client never
  12795. // sends one, so the worker would be held until the read timeout expires, and
  12796. // stop() would wait for it.
  12797. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12799. ASSERT_TRUE(svr.is_valid());
  12800. svr.set_keep_alive_timeout(1);
  12801. svr.set_read_timeout(10, 0);
  12802. svr.Get("/", [](const Request &, Response &res) {
  12803. res.set_content("ok", "text/plain");
  12804. });
  12805. auto port = svr.bind_to_any_port(HOST);
  12806. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12807. auto se = detail::scope_exit([&] {
  12808. if (listen_thread.joinable()) {
  12809. svr.stop();
  12810. listen_thread.join();
  12811. }
  12812. });
  12813. svr.wait_until_ready();
  12814. SSLClient cli(HOST, port);
  12815. cli.enable_server_certificate_verification(false);
  12816. cli.set_keep_alive(true);
  12817. auto res = cli.Get("/");
  12818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12819. EXPECT_EQ(StatusCode::OK_200, res->status);
  12820. // Stay idle past the keep-alive timeout so the server closes the connection.
  12821. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12822. auto start = std::chrono::steady_clock::now();
  12823. svr.stop();
  12824. listen_thread.join();
  12825. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12826. std::chrono::steady_clock::now() - start)
  12827. .count();
  12828. EXPECT_LT(elapsed, 3000);
  12829. }
  12830. #endif
  12831. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12832. protected:
  12833. ServerTestWithAI_PASSIVE()
  12834. : cli_(HOST, PORT)
  12835. #ifdef CPPHTTPLIB_SSL_ENABLED
  12836. ,
  12837. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12838. #endif
  12839. {
  12840. #ifdef CPPHTTPLIB_SSL_ENABLED
  12841. cli_.enable_server_certificate_verification(false);
  12842. #endif
  12843. }
  12844. virtual void SetUp() {
  12845. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12846. res.set_content("Hello World!", "text/plain");
  12847. });
  12848. t_ = thread(
  12849. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12850. svr_.wait_until_ready();
  12851. }
  12852. virtual void TearDown() {
  12853. svr_.stop();
  12854. t_.join();
  12855. }
  12856. #ifdef CPPHTTPLIB_SSL_ENABLED
  12857. SSLClient cli_;
  12858. SSLServer svr_;
  12859. #else
  12860. Client cli_;
  12861. Server svr_;
  12862. #endif
  12863. thread t_;
  12864. };
  12865. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12866. auto res = cli_.Get("/hi");
  12867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12868. EXPECT_EQ(StatusCode::OK_200, res->status);
  12869. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12870. EXPECT_EQ("Hello World!", res->body);
  12871. }
  12872. class ServerUpDownTest : public ::testing::Test {
  12873. protected:
  12874. ServerUpDownTest() : cli_(HOST, PORT) {}
  12875. virtual void SetUp() {
  12876. t_ = thread([&]() {
  12877. svr_.bind_to_any_port(HOST);
  12878. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12879. ASSERT_TRUE(svr_.listen_after_bind());
  12880. });
  12881. svr_.wait_until_ready();
  12882. }
  12883. virtual void TearDown() {
  12884. svr_.stop();
  12885. t_.join();
  12886. }
  12887. Client cli_;
  12888. Server svr_;
  12889. thread t_;
  12890. };
  12891. TEST_F(ServerUpDownTest, QuickStartStop) {
  12892. // Should not crash, especially when run with
  12893. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12894. }
  12895. class PayloadMaxLengthTest : public ::testing::Test {
  12896. protected:
  12897. PayloadMaxLengthTest()
  12898. : cli_(HOST, PORT)
  12899. #ifdef CPPHTTPLIB_SSL_ENABLED
  12900. ,
  12901. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12902. #endif
  12903. {
  12904. #ifdef CPPHTTPLIB_SSL_ENABLED
  12905. cli_.enable_server_certificate_verification(false);
  12906. #endif
  12907. }
  12908. virtual void SetUp() {
  12909. svr_.set_payload_max_length(8);
  12910. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12911. res.set_content("test", "text/plain");
  12912. });
  12913. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12914. svr_.wait_until_ready();
  12915. }
  12916. virtual void TearDown() {
  12917. svr_.stop();
  12918. t_.join();
  12919. }
  12920. #ifdef CPPHTTPLIB_SSL_ENABLED
  12921. SSLClient cli_;
  12922. SSLServer svr_;
  12923. #else
  12924. Client cli_;
  12925. Server svr_;
  12926. #endif
  12927. thread t_;
  12928. };
  12929. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12930. auto res = cli_.Post("/test", "123456789", "text/plain");
  12931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12932. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12933. res = cli_.Post("/test", "12345678", "text/plain");
  12934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12935. EXPECT_EQ(StatusCode::OK_200, res->status);
  12936. }
  12937. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12938. // Test chunked encoding with payload exceeding the 8-byte limit
  12939. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12940. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12942. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12943. }
  12944. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12945. // Test chunked encoding with payload within the 8-byte limit
  12946. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12947. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12949. EXPECT_EQ(StatusCode::OK_200, res->status);
  12950. }
  12951. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12952. // Test using send_request to send chunked data exceeding payload limit
  12953. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12954. "Host: " +
  12955. std::string(HOST) + ":" + std::to_string(PORT) +
  12956. "\r\n"
  12957. "Transfer-Encoding: chunked\r\n"
  12958. "Connection: close\r\n"
  12959. "\r\n"
  12960. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12961. "0123456789\r\n"
  12962. "0\r\n" // End chunk
  12963. "\r\n";
  12964. std::string response;
  12965. bool result = send_request(1, chunked_request, &response);
  12966. if (!result) {
  12967. // If send_request fails, it might be because the server closed the
  12968. // connection due to payload limit enforcement, which is acceptable
  12969. SUCCEED()
  12970. << "Server rejected oversized chunked request (connection closed)";
  12971. } else {
  12972. // If we got a response, check if it's an error response or connection was
  12973. // closed early Short response length indicates connection was closed due to
  12974. // payload limit
  12975. if (response.length() <= 10) {
  12976. SUCCEED() << "Server closed connection for oversized chunked request";
  12977. } else {
  12978. // Check for error status codes
  12979. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12980. response.find("Payload Too Large") != std::string::npos ||
  12981. response.find("400") != std::string::npos);
  12982. }
  12983. }
  12984. }
  12985. class LargePayloadMaxLengthTest : public ::testing::Test {
  12986. protected:
  12987. LargePayloadMaxLengthTest()
  12988. : cli_(HOST, PORT)
  12989. #ifdef CPPHTTPLIB_SSL_ENABLED
  12990. ,
  12991. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12992. #endif
  12993. {
  12994. #ifdef CPPHTTPLIB_SSL_ENABLED
  12995. cli_.enable_server_certificate_verification(false);
  12996. #endif
  12997. }
  12998. virtual void SetUp() {
  12999. // Set 10MB payload limit
  13000. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13001. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13002. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13003. res.set_content("Large payload test", "text/plain");
  13004. });
  13005. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13006. svr_.wait_until_ready();
  13007. }
  13008. virtual void TearDown() {
  13009. svr_.stop();
  13010. t_.join();
  13011. }
  13012. #ifdef CPPHTTPLIB_SSL_ENABLED
  13013. SSLClient cli_;
  13014. SSLServer svr_;
  13015. #else
  13016. Client cli_;
  13017. Server svr_;
  13018. #endif
  13019. thread t_;
  13020. };
  13021. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13022. // Test chunked encoding with payload within 10MB limit
  13023. std::string medium_payload(5 * 1024 * 1024,
  13024. 'A'); // 5MB payload, within 10MB limit
  13025. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13027. EXPECT_EQ(StatusCode::OK_200, res->status);
  13028. }
  13029. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13030. // Test chunked encoding with payload exceeding 10MB limit
  13031. std::string large_payload(12 * 1024 * 1024,
  13032. 'B'); // 12MB payload, exceeds 10MB limit
  13033. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13034. // Server may either return 413 or close the connection
  13035. if (res) {
  13036. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13037. } else {
  13038. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13039. }
  13040. }
  13041. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13042. Server svr;
  13043. svr.Get("/", [](const Request &, Response &res) {
  13044. // Claims the most the client accepts, far more than it sends, then drops
  13045. // the connection.
  13046. res.set_content_provider(std::string().max_size(), "text/plain",
  13047. [](size_t, size_t, DataSink &sink) {
  13048. sink.write("abc", 3);
  13049. return false;
  13050. });
  13051. });
  13052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13053. auto se = detail::scope_exit([&] {
  13054. svr.stop();
  13055. thread.join();
  13056. ASSERT_FALSE(svr.is_running());
  13057. });
  13058. svr.wait_until_ready();
  13059. Client cli(HOST, PORT);
  13060. cli.set_payload_max_length(0);
  13061. EXPECT_FALSE(cli.Get("/"));
  13062. }
  13063. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13064. // Stream API does, not as a plain read failure
  13065. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13066. Server svr;
  13067. svr.Get("/big", [](const Request &, Response &res) {
  13068. res.set_content(std::string(100000, 'b'), "text/plain");
  13069. });
  13070. auto port = svr.bind_to_any_port(HOST);
  13071. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13072. auto se = detail::scope_exit([&] {
  13073. svr.stop();
  13074. thread.join();
  13075. });
  13076. svr.wait_until_ready();
  13077. Client cli(HOST, port);
  13078. cli.set_payload_max_length(1000);
  13079. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13080. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13081. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13082. [](const char *, size_t) { return true; });
  13083. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13084. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13085. // Small on the wire, over the limit once decompressed
  13086. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13087. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13088. #endif
  13089. }
  13090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13091. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13092. // path.
  13093. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13094. Server svr;
  13095. const size_t LIMIT = 64 * 1024; // 64KB
  13096. svr.set_payload_max_length(LIMIT);
  13097. size_t total = 0;
  13098. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13099. const ContentReader &content_reader) {
  13100. content_reader([&](const char * /*data*/, size_t len) {
  13101. total += len;
  13102. return true;
  13103. });
  13104. res.status = 200;
  13105. res.set_content("stream_ok", "text/plain");
  13106. });
  13107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13108. auto se = detail::scope_exit([&] {
  13109. svr.stop();
  13110. thread.join();
  13111. ASSERT_FALSE(svr.is_running());
  13112. });
  13113. svr.wait_until_ready();
  13114. // Prepare 256KB raw data and gzip-compress it
  13115. std::string raw(256 * 1024, 'A');
  13116. std::string gz;
  13117. {
  13118. z_stream zs{};
  13119. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13120. Z_DEFAULT_STRATEGY);
  13121. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13122. zs.avail_in = static_cast<uInt>(raw.size());
  13123. char outbuf[4096];
  13124. int ret;
  13125. do {
  13126. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13127. zs.avail_out = sizeof(outbuf);
  13128. ret = deflate(&zs, Z_FINISH);
  13129. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13130. } while (ret != Z_STREAM_END);
  13131. deflateEnd(&zs);
  13132. }
  13133. Client cli(HOST, PORT);
  13134. cli.set_connection_timeout(std::chrono::seconds(5));
  13135. Headers headers = {{"Content-Encoding", "gzip"}};
  13136. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13137. "application/octet-stream");
  13138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13139. // Server must reject oversized decompressed payloads with 413.
  13140. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13141. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13142. EXPECT_LE(total, LIMIT);
  13143. }
  13144. #endif
  13145. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13146. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13147. // the payload must be passed through untouched instead of being rejected.
  13148. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13149. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13150. Server svr;
  13151. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13152. res.set_content(body, "image/jpeg");
  13153. res.set_header("Content-Encoding", "UTF-8");
  13154. });
  13155. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13156. res.set_content(body, "image/jpeg");
  13157. res.set_header("Content-Encoding", "identity");
  13158. });
  13159. svr.Post("/echo", [](const Request &req, Response &res) {
  13160. res.set_content(req.body, "image/jpeg");
  13161. });
  13162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13163. auto se = detail::scope_exit([&] {
  13164. svr.stop();
  13165. t.join();
  13166. ASSERT_FALSE(svr.is_running());
  13167. });
  13168. svr.wait_until_ready();
  13169. Client cli(HOST, PORT);
  13170. {
  13171. auto res = cli.Get("/image");
  13172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13173. EXPECT_EQ(StatusCode::OK_200, res->status);
  13174. EXPECT_EQ(body, res->body);
  13175. }
  13176. {
  13177. auto res = cli.Get("/identity");
  13178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13179. EXPECT_EQ(StatusCode::OK_200, res->status);
  13180. EXPECT_EQ(body, res->body);
  13181. }
  13182. {
  13183. // The same applies to a request body reaching the server.
  13184. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13185. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_EQ(StatusCode::OK_200, res->status);
  13188. EXPECT_EQ(body, res->body);
  13189. }
  13190. }
  13191. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13192. // gzip-encoded response even when the build has no zlib support.
  13193. static const char GZIPPED_HELLO_WORLD[] = {
  13194. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13195. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13196. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13197. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13198. // A content coding is a whole token, not something the field value merely
  13199. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13200. // as "fibre" look like Brotli, and turned a multi-coding value like
  13201. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13202. // it was never meant to see.
  13203. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13204. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13205. Server svr;
  13206. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13207. res.set_content(body, "image/jpeg");
  13208. res.set_header("Content-Encoding", "fibre");
  13209. });
  13210. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13211. res.set_content(body, "image/jpeg");
  13212. res.set_header("Content-Encoding", "gzip, br");
  13213. });
  13214. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13215. res.set_content(body, "image/jpeg");
  13216. res.set_header("Content-Encoding", "x-zstd-ish");
  13217. });
  13218. auto port = svr.bind_to_any_port(HOST);
  13219. thread t = thread([&]() { svr.listen_after_bind(); });
  13220. auto se = detail::scope_exit([&] {
  13221. svr.stop();
  13222. t.join();
  13223. ASSERT_FALSE(svr.is_running());
  13224. });
  13225. svr.wait_until_ready();
  13226. Client cli(HOST, port);
  13227. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13228. auto res = cli.Get(path);
  13229. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13230. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13231. // Not a coding we recognize, so the payload comes back untouched
  13232. EXPECT_EQ(body, res->body) << path;
  13233. }
  13234. }
  13235. // A content coding cpp-httplib recognizes but was not built with must be
  13236. // reported as such. Handing the still-compressed payload back to the caller
  13237. // would silently corrupt it.
  13238. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13239. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13240. Server svr;
  13241. // "image/jpeg" keeps the server from applying a content coding of its own,
  13242. // so the hand-crafted Content-Encoding below survives.
  13243. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13244. res.set_content(gzipped, "image/jpeg");
  13245. res.set_header("Content-Encoding", "gzip");
  13246. });
  13247. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13248. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13249. res.set_content(gzipped, "image/jpeg");
  13250. res.set_header("Content-Encoding", "GZIP");
  13251. });
  13252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13253. auto se = detail::scope_exit([&] {
  13254. svr.stop();
  13255. t.join();
  13256. ASSERT_FALSE(svr.is_running());
  13257. });
  13258. svr.wait_until_ready();
  13259. Client cli(HOST, PORT);
  13260. {
  13261. auto res = cli.Get("/gzipped");
  13262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13264. EXPECT_EQ("Hello World!", res->body);
  13265. #else
  13266. ASSERT_FALSE(res);
  13267. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13268. #endif
  13269. }
  13270. {
  13271. // open_stream() must behave the same way.
  13272. auto handle = cli.open_stream("GET", "/gzipped");
  13273. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13274. ASSERT_TRUE(handle.is_valid());
  13275. std::string received;
  13276. char buf[256];
  13277. ssize_t n;
  13278. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13279. received.append(buf, static_cast<size_t>(n));
  13280. }
  13281. EXPECT_EQ("Hello World!", received);
  13282. #else
  13283. EXPECT_FALSE(handle.is_valid());
  13284. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13285. #endif
  13286. }
  13287. {
  13288. // A differently-cased coding must not be mistaken for an unknown one, or
  13289. // the body would be handed back still compressed.
  13290. auto res = cli.Get("/gzipped-uppercase");
  13291. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13293. EXPECT_EQ("Hello World!", res->body);
  13294. #else
  13295. ASSERT_FALSE(res);
  13296. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13297. #endif
  13298. }
  13299. }
  13300. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13301. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13302. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13303. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13304. // body a second time and appending a second Content-Encoding field line, so
  13305. // clients that decode one coding per listed value handed back raw gzip bytes.
  13306. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13307. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13308. Server svr;
  13309. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13310. // keeps the server from applying a coding of its own.
  13311. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13312. res.set_content(gzipped, "text/plain");
  13313. res.set_header("Content-Encoding", "gzip");
  13314. });
  13315. auto port = svr.bind_to_any_port(HOST);
  13316. thread t = thread([&]() { svr.listen_after_bind(); });
  13317. auto se = detail::scope_exit([&] {
  13318. svr.stop();
  13319. t.join();
  13320. ASSERT_FALSE(svr.is_running());
  13321. });
  13322. svr.wait_until_ready();
  13323. Client cli(HOST, port);
  13324. Headers headers = {{"Accept-Encoding", "gzip"}};
  13325. auto res = cli.Get("/pre-gzipped", headers);
  13326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13327. EXPECT_EQ(StatusCode::OK_200, res->status);
  13328. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13329. EXPECT_EQ("Hello World!", res->body);
  13330. }
  13331. // set_compress(false) sends every handler response as it is, buffered or
  13332. // streamed
  13333. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13334. const std::string text(1000, 'a');
  13335. Server svr;
  13336. svr.set_compress(false);
  13337. svr.Get("/buffered", [&](const Request &, Response &res) {
  13338. res.set_content(text, "text/plain");
  13339. });
  13340. svr.Get("/streamed", [&](const Request &, Response &res) {
  13341. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13342. sink.write(text.data(), text.size());
  13343. sink.done();
  13344. return true;
  13345. });
  13346. });
  13347. auto port = svr.bind_to_any_port(HOST);
  13348. ASSERT_LT(0, port);
  13349. thread t = thread([&] { svr.listen_after_bind(); });
  13350. auto se = detail::scope_exit([&] {
  13351. svr.stop();
  13352. t.join();
  13353. ASSERT_FALSE(svr.is_running());
  13354. });
  13355. svr.wait_until_ready();
  13356. Client cli(HOST, port);
  13357. cli.set_decompress(false);
  13358. for (auto path : {"/buffered", "/streamed"}) {
  13359. SCOPED_TRACE(path);
  13360. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13362. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13363. EXPECT_EQ(text, res->body);
  13364. }
  13365. }
  13366. // A chunked provider settles its coding where the headers are written and
  13367. // reuses it at write time. Both ends of that have to hold: a handler's own
  13368. // Content-Encoding suppresses the coding, and a response without one is still
  13369. // compressed as it always was.
  13370. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13371. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13372. const std::string plain = "Hello World! Hello World! Hello World!";
  13373. Server svr;
  13374. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13375. res.set_header("Content-Encoding", "gzip");
  13376. res.set_chunked_content_provider(
  13377. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13378. sink.write(gzipped.data(), gzipped.size());
  13379. sink.done();
  13380. return true;
  13381. });
  13382. });
  13383. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13384. res.set_chunked_content_provider(
  13385. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13386. sink.write(plain.data(), plain.size());
  13387. sink.done();
  13388. return true;
  13389. });
  13390. });
  13391. auto port = svr.bind_to_any_port(HOST);
  13392. thread t = thread([&]() { svr.listen_after_bind(); });
  13393. auto se = detail::scope_exit([&] {
  13394. svr.stop();
  13395. t.join();
  13396. ASSERT_FALSE(svr.is_running());
  13397. });
  13398. svr.wait_until_ready();
  13399. Client cli(HOST, port);
  13400. Headers headers = {{"Accept-Encoding", "gzip"}};
  13401. {
  13402. auto res = cli.Get("/pre-gzipped", headers);
  13403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13404. EXPECT_EQ(StatusCode::OK_200, res->status);
  13405. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13406. EXPECT_EQ("Hello World!", res->body);
  13407. }
  13408. {
  13409. auto res = cli.Get("/negotiated", headers);
  13410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13411. EXPECT_EQ(StatusCode::OK_200, res->status);
  13412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13413. EXPECT_EQ(plain, res->body);
  13414. }
  13415. }
  13416. #endif
  13417. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13418. // the same message as the comma-joined one, so both have to be read the same
  13419. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13420. // single gzip coding, and a body the sender says was encoded twice was handed
  13421. // back after one pass, still compressed but presented as decoded.
  13422. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13423. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13424. Server svr;
  13425. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13426. res.set_content(body, "image/jpeg");
  13427. res.headers.emplace("Content-Encoding", "gzip");
  13428. res.headers.emplace("Content-Encoding", "gzip");
  13429. });
  13430. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13431. res.set_content(body, "image/jpeg");
  13432. res.set_header("Content-Encoding", "gzip, gzip");
  13433. });
  13434. auto port = svr.bind_to_any_port(HOST);
  13435. thread t = thread([&]() { svr.listen_after_bind(); });
  13436. auto se = detail::scope_exit([&] {
  13437. svr.stop();
  13438. t.join();
  13439. ASSERT_FALSE(svr.is_running());
  13440. });
  13441. svr.wait_until_ready();
  13442. Client cli(HOST, port);
  13443. // Two codings is not something cpp-httplib decodes, so both representations
  13444. // take the pass-through path rather than one of them being gunzipped once.
  13445. for (const char *path : {"/split", "/joined"}) {
  13446. auto res = cli.Get(path);
  13447. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13448. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13449. EXPECT_EQ(body, res->body) << path;
  13450. }
  13451. }
  13452. // Regression test for DoS vulnerability: a malicious server sending a response
  13453. // without Content-Length header must not cause unbounded memory consumption on
  13454. // the client side. The client should stop reading after a reasonable limit,
  13455. // similar to the server-side set_payload_max_length protection.
  13456. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13457. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13458. #ifndef _WIN32
  13459. signal(SIGPIPE, SIG_IGN);
  13460. #endif
  13461. auto server_thread = std::thread([] {
  13462. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13463. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13464. default_socket_options(srv);
  13465. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13466. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13467. sockaddr_in addr{};
  13468. addr.sin_family = AF_INET;
  13469. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13470. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13471. int opt = 1;
  13472. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13473. #ifdef _WIN32
  13474. reinterpret_cast<const char *>(&opt),
  13475. #else
  13476. &opt,
  13477. #endif
  13478. sizeof(opt));
  13479. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13480. ::listen(srv, 1);
  13481. sockaddr_in cli_addr{};
  13482. socklen_t cli_len = sizeof(cli_addr);
  13483. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13484. if (cli != INVALID_SOCKET) {
  13485. char buf[4096];
  13486. ::recv(cli, buf, sizeof(buf), 0);
  13487. // Malicious response: no Content-Length, no chunked encoding
  13488. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13489. "Connection: close\r\n"
  13490. "\r\n";
  13491. ::send(cli,
  13492. #ifdef _WIN32
  13493. static_cast<const char *>(response_header.c_str()),
  13494. static_cast<int>(response_header.size()),
  13495. #else
  13496. response_header.c_str(), response_header.size(),
  13497. #endif
  13498. 0);
  13499. // Send 10MB of data
  13500. std::string chunk(64 * 1024, 'A');
  13501. size_t total_sent = 0;
  13502. while (total_sent < MALICIOUS_DATA_SIZE) {
  13503. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13504. auto sent = ::send(cli,
  13505. #ifdef _WIN32
  13506. static_cast<const char *>(chunk.c_str()),
  13507. static_cast<int>(to_send),
  13508. #else
  13509. chunk.c_str(), to_send,
  13510. #endif
  13511. 0);
  13512. if (sent <= 0) break;
  13513. total_sent += static_cast<size_t>(sent);
  13514. }
  13515. detail::close_socket(cli);
  13516. }
  13517. detail::close_socket(srv);
  13518. });
  13519. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13520. size_t total_read = 0;
  13521. {
  13522. Client cli("127.0.0.1", PORT + 2);
  13523. cli.set_read_timeout(5, 0);
  13524. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13525. auto stream = cli.open_stream("GET", "/malicious");
  13526. ASSERT_TRUE(stream.is_valid());
  13527. char buffer[64 * 1024];
  13528. ssize_t n;
  13529. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13530. total_read += static_cast<size_t>(n);
  13531. }
  13532. } // StreamHandle and Client destroyed here, closing the socket
  13533. server_thread.join();
  13534. // With set_payload_max_length, the client must stop reading before consuming
  13535. // all 10MB. The read loop should be cut off at or near the configured limit.
  13536. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13537. << "Client read " << total_read << " bytes, exceeding the configured "
  13538. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13539. }
  13540. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13541. // the entire response body without truncation.
  13542. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13543. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13544. #ifndef _WIN32
  13545. signal(SIGPIPE, SIG_IGN);
  13546. #endif
  13547. auto server_thread = std::thread([] {
  13548. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13549. default_socket_options(srv);
  13550. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13551. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13552. sockaddr_in addr{};
  13553. addr.sin_family = AF_INET;
  13554. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13555. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13556. int opt = 1;
  13557. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13558. #ifdef _WIN32
  13559. reinterpret_cast<const char *>(&opt),
  13560. #else
  13561. &opt,
  13562. #endif
  13563. sizeof(opt));
  13564. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13565. ::listen(srv, 1);
  13566. sockaddr_in cli_addr{};
  13567. socklen_t cli_len = sizeof(cli_addr);
  13568. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13569. if (cli != INVALID_SOCKET) {
  13570. char buf[4096];
  13571. ::recv(cli, buf, sizeof(buf), 0);
  13572. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13573. "Connection: close\r\n"
  13574. "\r\n";
  13575. ::send(cli,
  13576. #ifdef _WIN32
  13577. static_cast<const char *>(response_header.c_str()),
  13578. static_cast<int>(response_header.size()),
  13579. #else
  13580. response_header.c_str(), response_header.size(),
  13581. #endif
  13582. 0);
  13583. std::string chunk(64 * 1024, 'A');
  13584. size_t total_sent = 0;
  13585. while (total_sent < DATA_SIZE) {
  13586. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13587. auto sent = ::send(cli,
  13588. #ifdef _WIN32
  13589. static_cast<const char *>(chunk.c_str()),
  13590. static_cast<int>(to_send),
  13591. #else
  13592. chunk.c_str(), to_send,
  13593. #endif
  13594. 0);
  13595. if (sent <= 0) break;
  13596. total_sent += static_cast<size_t>(sent);
  13597. }
  13598. #ifdef _WIN32
  13599. ::shutdown(cli, SD_SEND);
  13600. #else
  13601. ::shutdown(cli, SHUT_WR);
  13602. #endif
  13603. // Drain until the client closes its end, ensuring all data is delivered
  13604. char drain[1024];
  13605. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13606. detail::close_socket(cli);
  13607. }
  13608. detail::close_socket(srv);
  13609. });
  13610. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13611. size_t total_read = 0;
  13612. {
  13613. Client cli("127.0.0.1", PORT + 2);
  13614. cli.set_read_timeout(5, 0);
  13615. cli.set_payload_max_length(0); // 0 means no limit
  13616. auto stream = cli.open_stream("GET", "/data");
  13617. ASSERT_TRUE(stream.is_valid());
  13618. char buffer[64 * 1024];
  13619. ssize_t n;
  13620. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13621. total_read += static_cast<size_t>(n);
  13622. }
  13623. }
  13624. server_thread.join();
  13625. EXPECT_EQ(total_read, DATA_SIZE)
  13626. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13627. << " bytes without truncation, but only read " << total_read << " bytes.";
  13628. }
  13629. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13630. // enormous Content-Length must not cause the client to pre-allocate a huge
  13631. // response body buffer. The reservation is capped at payload_max_length_, and
  13632. // the read itself fails when the body exceeds the limit.
  13633. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13634. #ifndef _WIN32
  13635. signal(SIGPIPE, SIG_IGN);
  13636. #endif
  13637. auto server_thread = std::thread([] {
  13638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13639. default_socket_options(srv);
  13640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13642. sockaddr_in addr{};
  13643. addr.sin_family = AF_INET;
  13644. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13645. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13646. int opt = 1;
  13647. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13648. #ifdef _WIN32
  13649. reinterpret_cast<const char *>(&opt),
  13650. #else
  13651. &opt,
  13652. #endif
  13653. sizeof(opt));
  13654. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13655. ::listen(srv, 1);
  13656. sockaddr_in cli_addr{};
  13657. socklen_t cli_len = sizeof(cli_addr);
  13658. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13659. if (cli != INVALID_SOCKET) {
  13660. char buf[4096];
  13661. ::recv(cli, buf, sizeof(buf), 0);
  13662. // Malicious response: claim a 20GB body but send only a tiny payload.
  13663. std::string response = "HTTP/1.1 200 OK\r\n"
  13664. "Content-Length: 20000000000\r\n"
  13665. "\r\n"
  13666. "abc";
  13667. ::send(cli,
  13668. #ifdef _WIN32
  13669. static_cast<const char *>(response.c_str()),
  13670. static_cast<int>(response.size()),
  13671. #else
  13672. response.c_str(), response.size(),
  13673. #endif
  13674. 0);
  13675. detail::close_socket(cli);
  13676. }
  13677. detail::close_socket(srv);
  13678. });
  13679. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13680. {
  13681. Client cli("127.0.0.1", PORT + 2);
  13682. cli.set_read_timeout(5, 0);
  13683. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13684. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13685. // (server claims more bytes than payload_max_length permits), but it must
  13686. // not exhaust memory before getting there.
  13687. auto res = cli.Get("/malicious");
  13688. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13689. }
  13690. server_thread.join();
  13691. }
  13692. // Verify that content_receiver bypasses the default payload_max_length,
  13693. // allowing streaming downloads larger than 100MB without requiring an explicit
  13694. // set_payload_max_length call.
  13695. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13696. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13697. #ifndef _WIN32
  13698. signal(SIGPIPE, SIG_IGN);
  13699. #endif
  13700. auto server_thread = std::thread([] {
  13701. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13702. default_socket_options(srv);
  13703. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13704. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13705. sockaddr_in addr{};
  13706. addr.sin_family = AF_INET;
  13707. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13708. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13709. int opt = 1;
  13710. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13711. #ifdef _WIN32
  13712. reinterpret_cast<const char *>(&opt),
  13713. #else
  13714. &opt,
  13715. #endif
  13716. sizeof(opt));
  13717. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13718. ::listen(srv, 1);
  13719. sockaddr_in cli_addr{};
  13720. socklen_t cli_len = sizeof(cli_addr);
  13721. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13722. if (cli != INVALID_SOCKET) {
  13723. char buf[4096];
  13724. ::recv(cli, buf, sizeof(buf), 0);
  13725. // Response with Content-Length larger than default 100MB limit
  13726. auto content_length = std::to_string(DATA_SIZE);
  13727. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13728. "Content-Length: " +
  13729. content_length +
  13730. "\r\n"
  13731. "Connection: close\r\n"
  13732. "\r\n";
  13733. ::send(cli,
  13734. #ifdef _WIN32
  13735. static_cast<const char *>(response_header.c_str()),
  13736. static_cast<int>(response_header.size()),
  13737. #else
  13738. response_header.c_str(), response_header.size(),
  13739. #endif
  13740. 0);
  13741. std::string chunk(64 * 1024, 'A');
  13742. size_t total_sent = 0;
  13743. while (total_sent < DATA_SIZE) {
  13744. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13745. auto sent = ::send(cli,
  13746. #ifdef _WIN32
  13747. static_cast<const char *>(chunk.c_str()),
  13748. static_cast<int>(to_send),
  13749. #else
  13750. chunk.c_str(), to_send,
  13751. #endif
  13752. 0);
  13753. if (sent <= 0) break;
  13754. total_sent += static_cast<size_t>(sent);
  13755. }
  13756. detail::close_socket(cli);
  13757. }
  13758. detail::close_socket(srv);
  13759. });
  13760. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13761. size_t total_received = 0;
  13762. {
  13763. Client cli("127.0.0.1", PORT + 2);
  13764. cli.set_read_timeout(10, 0);
  13765. // Do NOT call set_payload_max_length — use the default 100MB limit
  13766. auto res =
  13767. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13768. total_received += data_length;
  13769. return true;
  13770. });
  13771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13772. EXPECT_EQ(StatusCode::OK_200, res->status);
  13773. }
  13774. server_thread.join();
  13775. EXPECT_EQ(total_received, DATA_SIZE)
  13776. << "With content_receiver, the client should read all " << DATA_SIZE
  13777. << " bytes despite the default 100MB payload_max_length, but only read "
  13778. << total_received << " bytes.";
  13779. }
  13780. // Verify that an explicit set_payload_max_length smaller than the response is
  13781. // enforced even when a content_receiver is used.
  13782. TEST(ClientVulnerabilityTest,
  13783. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13784. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13785. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13786. #ifndef _WIN32
  13787. signal(SIGPIPE, SIG_IGN);
  13788. #endif
  13789. auto server_thread = std::thread([] {
  13790. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13791. default_socket_options(srv);
  13792. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13793. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13794. sockaddr_in addr{};
  13795. addr.sin_family = AF_INET;
  13796. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13797. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13798. int opt = 1;
  13799. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13800. #ifdef _WIN32
  13801. reinterpret_cast<const char *>(&opt),
  13802. #else
  13803. &opt,
  13804. #endif
  13805. sizeof(opt));
  13806. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13807. ::listen(srv, 1);
  13808. sockaddr_in cli_addr{};
  13809. socklen_t cli_len = sizeof(cli_addr);
  13810. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13811. if (cli != INVALID_SOCKET) {
  13812. char buf[4096];
  13813. ::recv(cli, buf, sizeof(buf), 0);
  13814. auto content_length = std::to_string(DATA_SIZE);
  13815. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13816. "Content-Length: " +
  13817. content_length +
  13818. "\r\n"
  13819. "Connection: close\r\n"
  13820. "\r\n";
  13821. ::send(cli,
  13822. #ifdef _WIN32
  13823. static_cast<const char *>(response_header.c_str()),
  13824. static_cast<int>(response_header.size()),
  13825. #else
  13826. response_header.c_str(), response_header.size(),
  13827. #endif
  13828. 0);
  13829. std::string chunk(64 * 1024, 'A');
  13830. size_t total_sent = 0;
  13831. while (total_sent < DATA_SIZE) {
  13832. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13833. auto sent = ::send(cli,
  13834. #ifdef _WIN32
  13835. static_cast<const char *>(chunk.c_str()),
  13836. static_cast<int>(to_send),
  13837. #else
  13838. chunk.c_str(), to_send,
  13839. #endif
  13840. 0);
  13841. if (sent <= 0) break;
  13842. total_sent += static_cast<size_t>(sent);
  13843. }
  13844. detail::close_socket(cli);
  13845. }
  13846. detail::close_socket(srv);
  13847. });
  13848. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13849. size_t total_received = 0;
  13850. {
  13851. Client cli("127.0.0.1", PORT + 2);
  13852. cli.set_read_timeout(10, 0);
  13853. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13854. auto res =
  13855. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13856. total_received += data_length;
  13857. return true;
  13858. });
  13859. // Should fail because 200MB exceeds the explicit 150MB limit
  13860. EXPECT_FALSE(res);
  13861. }
  13862. server_thread.join();
  13863. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13864. << "Client with content_receiver should respect the explicit "
  13865. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13866. << total_received << " bytes.";
  13867. }
  13868. // Verify that an explicit set_payload_max_length larger than the response
  13869. // allows the content_receiver to read all data successfully.
  13870. TEST(ClientVulnerabilityTest,
  13871. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13872. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13873. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13874. #ifndef _WIN32
  13875. signal(SIGPIPE, SIG_IGN);
  13876. #endif
  13877. auto server_thread = std::thread([] {
  13878. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13879. default_socket_options(srv);
  13880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13882. sockaddr_in addr{};
  13883. addr.sin_family = AF_INET;
  13884. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13885. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13886. int opt = 1;
  13887. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13888. #ifdef _WIN32
  13889. reinterpret_cast<const char *>(&opt),
  13890. #else
  13891. &opt,
  13892. #endif
  13893. sizeof(opt));
  13894. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13895. ::listen(srv, 1);
  13896. sockaddr_in cli_addr{};
  13897. socklen_t cli_len = sizeof(cli_addr);
  13898. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13899. if (cli != INVALID_SOCKET) {
  13900. char buf[4096];
  13901. ::recv(cli, buf, sizeof(buf), 0);
  13902. auto content_length = std::to_string(DATA_SIZE);
  13903. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13904. "Content-Length: " +
  13905. content_length +
  13906. "\r\n"
  13907. "Connection: close\r\n"
  13908. "\r\n";
  13909. ::send(cli,
  13910. #ifdef _WIN32
  13911. static_cast<const char *>(response_header.c_str()),
  13912. static_cast<int>(response_header.size()),
  13913. #else
  13914. response_header.c_str(), response_header.size(),
  13915. #endif
  13916. 0);
  13917. std::string chunk(64 * 1024, 'A');
  13918. size_t total_sent = 0;
  13919. while (total_sent < DATA_SIZE) {
  13920. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13921. auto sent = ::send(cli,
  13922. #ifdef _WIN32
  13923. static_cast<const char *>(chunk.c_str()),
  13924. static_cast<int>(to_send),
  13925. #else
  13926. chunk.c_str(), to_send,
  13927. #endif
  13928. 0);
  13929. if (sent <= 0) break;
  13930. total_sent += static_cast<size_t>(sent);
  13931. }
  13932. #ifdef _WIN32
  13933. ::shutdown(cli, SD_SEND);
  13934. #else
  13935. ::shutdown(cli, SHUT_WR);
  13936. #endif
  13937. char drain[1024];
  13938. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13939. detail::close_socket(cli);
  13940. }
  13941. detail::close_socket(srv);
  13942. });
  13943. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13944. size_t total_received = 0;
  13945. {
  13946. Client cli("127.0.0.1", PORT + 2);
  13947. cli.set_read_timeout(10, 0);
  13948. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13949. auto res =
  13950. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13951. total_received += data_length;
  13952. return true;
  13953. });
  13954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13955. EXPECT_EQ(StatusCode::OK_200, res->status);
  13956. }
  13957. server_thread.join();
  13958. EXPECT_EQ(total_received, DATA_SIZE)
  13959. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13960. << " bytes (larger than " << DATA_SIZE
  13961. << " bytes response), content_receiver should read all data, but only "
  13962. "read "
  13963. << total_received << " bytes.";
  13964. }
  13965. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13966. // Regression test for "zip bomb" attack on the client side: a malicious server
  13967. // sends a small gzip-compressed response that decompresses to a huge payload.
  13968. // The client must enforce payload_max_length on the decompressed size.
  13969. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13970. constexpr size_t DECOMPRESSED_SIZE =
  13971. 10 * 1024 * 1024; // 10MB after decompression
  13972. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13973. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13974. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13975. std::string compressed;
  13976. {
  13977. httplib::detail::gzip_compressor compressor;
  13978. bool ok =
  13979. compressor.compress(uncompressed.data(), uncompressed.size(),
  13980. /*last=*/true, [&](const char *buf, size_t len) {
  13981. compressed.append(buf, len);
  13982. return true;
  13983. });
  13984. ASSERT_TRUE(ok);
  13985. }
  13986. // Sanity: compressed data should be much smaller than the decompressed size
  13987. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13988. #ifndef _WIN32
  13989. signal(SIGPIPE, SIG_IGN);
  13990. #endif
  13991. // Set up the listening socket in the main thread so the server is guaranteed
  13992. // to be ready before the client connects (eliminates race condition).
  13993. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13994. default_socket_options(srv);
  13995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13997. sockaddr_in addr{};
  13998. addr.sin_family = AF_INET;
  13999. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14000. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14001. int opt = 1;
  14002. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14003. #ifdef _WIN32
  14004. reinterpret_cast<const char *>(&opt),
  14005. #else
  14006. &opt,
  14007. #endif
  14008. sizeof(opt));
  14009. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14010. ASSERT_EQ(0, ::listen(srv, 1));
  14011. auto server_thread = std::thread([&compressed, srv] {
  14012. sockaddr_in cli_addr{};
  14013. socklen_t cli_len = sizeof(cli_addr);
  14014. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14015. if (cli != INVALID_SOCKET) {
  14016. // Read the full HTTP request (until \r\n\r\n)
  14017. char buf[4096];
  14018. size_t total = 0;
  14019. while (total < sizeof(buf)) {
  14020. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14021. if (n <= 0) break;
  14022. total += static_cast<size_t>(n);
  14023. // Check for end of headers
  14024. if (total >= 4) {
  14025. std::string req(buf, total);
  14026. if (req.find("\r\n\r\n") != std::string::npos) break;
  14027. }
  14028. }
  14029. // Malicious response: gzip-compressed body, no Content-Length
  14030. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14031. "Content-Encoding: gzip\r\n"
  14032. "Connection: close\r\n"
  14033. "\r\n";
  14034. ::send(cli,
  14035. #ifdef _WIN32
  14036. static_cast<const char *>(response_header.c_str()),
  14037. static_cast<int>(response_header.size()),
  14038. #else
  14039. response_header.c_str(), response_header.size(),
  14040. #endif
  14041. 0);
  14042. // Send the compressed payload (small on the wire, huge when decompressed)
  14043. size_t total_sent = 0;
  14044. while (total_sent < compressed.size()) {
  14045. auto to_send = std::min(compressed.size() - total_sent,
  14046. static_cast<size_t>(64 * 1024));
  14047. auto sent =
  14048. ::send(cli,
  14049. #ifdef _WIN32
  14050. static_cast<const char *>(compressed.c_str() + total_sent),
  14051. static_cast<int>(to_send),
  14052. #else
  14053. compressed.c_str() + total_sent, to_send,
  14054. #endif
  14055. 0);
  14056. if (sent <= 0) break;
  14057. total_sent += static_cast<size_t>(sent);
  14058. }
  14059. detail::close_socket(cli);
  14060. }
  14061. });
  14062. auto se = detail::scope_exit([&] {
  14063. detail::close_socket(srv);
  14064. server_thread.join();
  14065. });
  14066. size_t total_decompressed = 0;
  14067. {
  14068. Client cli("127.0.0.1", PORT + 3);
  14069. cli.set_read_timeout(5, 0);
  14070. cli.set_decompress(true);
  14071. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14072. auto stream = cli.open_stream("GET", "/zipbomb");
  14073. ASSERT_TRUE(stream.is_valid());
  14074. char buffer[64 * 1024];
  14075. ssize_t n;
  14076. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14077. total_decompressed += static_cast<size_t>(n);
  14078. }
  14079. }
  14080. // The decompressed size must be capped by payload_max_length. Without
  14081. // protection, the client would decompress the full 10MB from a tiny
  14082. // compressed payload, enabling a zip bomb DoS attack.
  14083. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14084. << "Client decompressed " << total_decompressed
  14085. << " bytes from a gzip response. The decompressed size should be "
  14086. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14087. }
  14088. #endif
  14089. TEST(HostAndPortPropertiesTest, NoSSL) {
  14090. httplib::Client cli("www.google.com", 1234);
  14091. ASSERT_EQ("www.google.com", cli.host());
  14092. ASSERT_EQ(1234, cli.port());
  14093. }
  14094. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14095. httplib::Client cli("www.google.com:1234");
  14096. ASSERT_EQ("www.google.com", cli.host());
  14097. ASSERT_EQ(1234, cli.port());
  14098. }
  14099. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14100. // Port number that overflows int — should not crash, client becomes invalid
  14101. httplib::Client cli("http://www.google.com:99999999999999999999");
  14102. ASSERT_FALSE(cli.is_valid());
  14103. }
  14104. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14105. // Port 99999 exceeds valid range (1-65535) — should not crash
  14106. httplib::Client cli("http://www.google.com:99999");
  14107. ASSERT_FALSE(cli.is_valid());
  14108. auto res = cli.Get("/");
  14109. EXPECT_FALSE(res);
  14110. EXPECT_EQ(Error::Connection, res.error());
  14111. }
  14112. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14113. httplib::Client cli("http://user:pass@localhost:1234");
  14114. ASSERT_FALSE(cli.is_valid());
  14115. EXPECT_FALSE(cli.Get("/"));
  14116. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14117. }
  14118. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14119. httplib::Client cli("http://www.google.com:80abc");
  14120. ASSERT_FALSE(cli.is_valid());
  14121. }
  14122. #ifdef CPPHTTPLIB_SSL_ENABLED
  14123. TEST(HostAndPortPropertiesTest, SSL) {
  14124. httplib::SSLClient cli("www.google.com");
  14125. ASSERT_EQ("www.google.com", cli.host());
  14126. ASSERT_EQ(443, cli.port());
  14127. }
  14128. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14129. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14130. std::string cert;
  14131. read_file(CA_CERT_FILE, cert);
  14132. httplib::SSLClient httplib_client("www.google.com");
  14133. // Load CA store first time
  14134. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14135. // Load CA store second time (update)
  14136. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14137. // Verify client is still valid and can make connections
  14138. httplib_client.enable_server_certificate_verification(true);
  14139. auto res = httplib_client.Get("/");
  14140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14141. // Google may return 200 or 301 depending on various factors
  14142. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14143. res->status == StatusCode::MovedPermanently_301);
  14144. }
  14145. TEST(SSLClientTest, ServerNameIndication_Online) {
  14146. auto host = "httpbingo.org";
  14147. auto path = std::string{"/get"};
  14148. SSLClient cli(host, 443);
  14149. auto res = cli.Get(path);
  14150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14151. ASSERT_EQ(StatusCode::OK_200, res->status);
  14152. }
  14153. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14154. // Use a site that will cause SSL verification failure due to self-signed cert
  14155. SSLClient cli("self-signed.badssl.com", 443);
  14156. cli.enable_server_certificate_verification(true);
  14157. auto res = cli.Get("/");
  14158. ASSERT_TRUE(!res);
  14159. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14160. // Verify backend error is captured for SSLServerVerification
  14161. // This occurs when certificate verification fails
  14162. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14163. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14164. EXPECT_NE(0UL, res.ssl_backend_error());
  14165. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14166. res.ssl_error());
  14167. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14168. #if !defined(_WIN32) || \
  14169. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14170. // On non-Windows or when Windows Schannel is disabled, the error comes
  14171. // from OpenSSL's verification
  14172. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14173. res.ssl_backend_error());
  14174. #endif
  14175. #endif
  14176. }
  14177. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14178. // Use a site where hostname doesn't match the certificate
  14179. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14180. SSLClient cli("wrong.host.badssl.com", 443);
  14181. cli.enable_server_certificate_verification(true);
  14182. cli.enable_server_hostname_verification(true);
  14183. auto res = cli.Get("/");
  14184. ASSERT_TRUE(!res);
  14185. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14186. // Verify backend error is captured for hostname verification failure
  14187. EXPECT_NE(0UL, res.ssl_backend_error());
  14188. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14189. res.ssl_error());
  14190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14191. #if !defined(_WIN32) || \
  14192. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14193. // On non-Windows or when Windows Schannel is disabled, the error comes
  14194. // from OpenSSL's hostname verification
  14195. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14196. res.ssl_backend_error());
  14197. #endif
  14198. #endif
  14199. }
  14200. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14201. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14202. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14203. SSLClient cli("www.google.com", 443);
  14204. cli.enable_server_certificate_verification(true);
  14205. auto res = cli.Get("/");
  14206. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14207. }
  14208. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14209. SSLClient cli("www.google.com", 443);
  14210. cli.enable_server_certificate_verification(true);
  14211. cli.enable_windows_certificate_verification(false);
  14212. auto res = cli.Get("/");
  14213. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14214. }
  14215. // The server sends an intermediate cross-signed by a root Windows trusts,
  14216. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14217. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14218. SSLClient cli("accounts.spotify.com", 443);
  14219. auto res = cli.Get("/");
  14220. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14221. << " ssl_backend_error=" << res.ssl_backend_error();
  14222. }
  14223. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14224. // policy status, which no backend reports for a self-signed certificate.
  14225. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14226. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14227. ASSERT_TRUE(svr.is_valid());
  14228. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14229. auto se = detail::scope_exit([&] {
  14230. svr.stop();
  14231. t.join();
  14232. ASSERT_FALSE(svr.is_running());
  14233. });
  14234. svr.wait_until_ready();
  14235. SSLClient cli("127.0.0.1", PORT);
  14236. cli.set_connection_timeout(30);
  14237. auto res = cli.Get("/");
  14238. ASSERT_FALSE(res);
  14239. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14240. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14241. }
  14242. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14243. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14244. ASSERT_TRUE(svr.is_valid());
  14245. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14246. auto se = detail::scope_exit([&] {
  14247. svr.stop();
  14248. t.join();
  14249. ASSERT_FALSE(svr.is_running());
  14250. });
  14251. svr.wait_until_ready();
  14252. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14253. {
  14254. ws::WebSocketClient client(url);
  14255. auto res = client.connect();
  14256. ASSERT_FALSE(res);
  14257. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14258. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14259. res.ssl_backend_error());
  14260. }
  14261. {
  14262. ws::WebSocketClient client(url);
  14263. client.enable_windows_certificate_verification(false);
  14264. auto res = client.connect();
  14265. ASSERT_FALSE(res);
  14266. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14267. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14268. res.ssl_backend_error());
  14269. }
  14270. }
  14271. #endif
  14272. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14273. Client cli("https://google.com");
  14274. auto res = cli.Get("/");
  14275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14276. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14277. }
  14278. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14279. SSLClient cli("google.com");
  14280. cli.set_ca_cert_path(CA_CERT_FILE);
  14281. auto res = cli.Get("/");
  14282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14283. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14284. }
  14285. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14286. SSLClient cli("google.com");
  14287. cli.enable_server_certificate_verification(true);
  14288. cli.set_ca_cert_path("hello");
  14289. auto res = cli.Get("/");
  14290. ASSERT_TRUE(!res);
  14291. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14292. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14293. // should be set
  14294. EXPECT_EQ(0, res.ssl_error());
  14295. // Verify backend error is captured for SSLLoadingCerts
  14296. // This error occurs when loading CA certificates fails
  14297. EXPECT_NE(0UL, res.ssl_backend_error());
  14298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14299. // OpenSSL specific error codes:
  14300. // > openssl errstr 0x80000002
  14301. // error:80000002:system library::No such file or directory
  14302. // > openssl errstr 0xA000126
  14303. // error:0A000126:SSL routines::unexpected eof while reading
  14304. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14305. res.ssl_backend_error() == 0xA000126);
  14306. #endif
  14307. }
  14308. TEST(SSLClientTest, ServerCertificateVerification4) {
  14309. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14310. ASSERT_TRUE(svr.is_valid());
  14311. svr.Get("/test", [&](const Request &, Response &res) {
  14312. res.set_content("test", "text/plain");
  14313. svr.stop();
  14314. ASSERT_TRUE(true);
  14315. });
  14316. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14317. auto se = detail::scope_exit([&] {
  14318. t.join();
  14319. ASSERT_FALSE(svr.is_running());
  14320. });
  14321. svr.wait_until_ready();
  14322. SSLClient cli("127.0.0.1", PORT);
  14323. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14324. cli.enable_server_certificate_verification(true);
  14325. cli.set_connection_timeout(30);
  14326. auto res = cli.Get("/test");
  14327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14328. ASSERT_EQ(StatusCode::OK_200, res->status);
  14329. }
  14330. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14331. std::string cert;
  14332. read_file(CA_CERT_FILE, cert);
  14333. SSLClient cli("google.com");
  14334. cli.load_ca_cert_store(cert.data(), cert.size());
  14335. const auto res = cli.Get("/");
  14336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14337. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14338. }
  14339. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14340. // clang-format off
  14341. static constexpr char cert[] =
  14342. "GlobalSign Root CA\n"
  14343. "==================\n"
  14344. "-----BEGIN CERTIFICATE-----\n"
  14345. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14346. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14347. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14348. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14349. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14350. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14351. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14352. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14353. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14354. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14355. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14356. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14357. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14358. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14359. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14360. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14361. "-----END CERTIFICATE-----\n";
  14362. // clang-format on
  14363. SSLClient cli("google.com");
  14364. cli.load_ca_cert_store(cert, sizeof(cert));
  14365. const auto res = cli.Get("/");
  14366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14367. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14368. }
  14369. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14370. SSLClient cli("www.youtube.com");
  14371. cli.set_ca_cert_path(CA_CERT_FILE);
  14372. cli.enable_server_certificate_verification(true);
  14373. cli.set_follow_location(true);
  14374. auto res = cli.Get("/");
  14375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14376. ASSERT_EQ(StatusCode::OK_200, res->status);
  14377. }
  14378. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14379. SSLClient cli("wWw.YouTube.Com");
  14380. cli.set_ca_cert_path(CA_CERT_FILE);
  14381. cli.enable_server_certificate_verification(true);
  14382. cli.enable_server_hostname_verification(true);
  14383. cli.set_follow_location(true);
  14384. auto res = cli.Get("/");
  14385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14386. ASSERT_EQ(StatusCode::OK_200, res->status);
  14387. }
  14388. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14389. SSLClient cli("gOoGlE.COm");
  14390. cli.enable_server_certificate_verification(true);
  14391. cli.enable_server_hostname_verification(true);
  14392. cli.set_follow_location(true);
  14393. auto res = cli.Get("/");
  14394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14395. ASSERT_EQ(StatusCode::OK_200, res->status);
  14396. }
  14397. TEST(SSLClientTest, Issue2004_Online) {
  14398. Client client("https://google.com");
  14399. client.set_follow_location(true);
  14400. auto res = client.Get("/");
  14401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14402. ASSERT_EQ(StatusCode::OK_200, res->status);
  14403. auto body = res->body;
  14404. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14405. }
  14406. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14407. // Create SSLClient with invalid cert/key to make is_valid() return false
  14408. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14409. "nonexistent_key.pem");
  14410. // is_valid() should be false due to cert loading failure
  14411. ASSERT_FALSE(cli.is_valid());
  14412. auto res = cli.Get("/");
  14413. ASSERT_FALSE(res);
  14414. EXPECT_EQ(Error::SSLConnection, res.error());
  14415. }
  14416. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14417. // Test for Issue #2251: SSL error not properly reported when client cert
  14418. // and key paths are swapped or mismatched
  14419. // This simulates the scenario where user accidentally swaps the cert and key
  14420. // files
  14421. // Using client cert file as private key and vice versa (completely wrong)
  14422. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14423. // Should fail validation due to cert/key mismatch
  14424. ASSERT_FALSE(cli.is_valid());
  14425. // Attempt to make a request should fail with proper error
  14426. auto res = cli.Get("/");
  14427. ASSERT_FALSE(res);
  14428. EXPECT_EQ(Error::SSLConnection, res.error());
  14429. // SSL error should be recorded in the Result object (this is the key fix for
  14430. // Issue #2251)
  14431. auto backend_error = res.ssl_backend_error();
  14432. EXPECT_NE(0u, backend_error);
  14433. }
  14434. // Tests cert/key mismatch detection at the TLS context level
  14435. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14436. // Test that using mismatched cert/key causes connection failure.
  14437. // We verify this at the SSLClient level rather than through internal
  14438. // TLS API functions.
  14439. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14440. cli.enable_server_certificate_verification(false);
  14441. cli.set_connection_timeout(2);
  14442. // The mismatch should cause a connection or handshake error
  14443. auto res = cli.Get("/test");
  14444. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14445. // Either way, the request should fail
  14446. EXPECT_FALSE(res);
  14447. }
  14448. #endif
  14449. #if 0
  14450. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14451. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14452. ASSERT_TRUE(cli != nullptr);
  14453. cli->set_address_family(AF_INET6);
  14454. cli->set_interface("en0");
  14455. auto res = cli->Get("/get");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::OK_200, res->status);
  14458. }
  14459. #endif
  14460. // Client certificate tests - work with all TLS backends
  14461. #ifdef CPPHTTPLIB_SSL_ENABLED
  14462. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14463. void ClientCertPresent(
  14464. const std::string &client_cert_file,
  14465. const std::string &client_private_key_file,
  14466. const std::string &client_encrypted_private_key_pass = std::string(),
  14467. const ClientCertServerSetup &setup = nullptr) {
  14468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14469. ASSERT_TRUE(svr.is_valid());
  14470. if (setup) { setup(svr); }
  14471. svr.Get("/test", [&](const Request &req, Response &res) {
  14472. res.set_content("test", "text/plain");
  14473. auto cert = req.peer_cert();
  14474. ASSERT_TRUE(static_cast<bool>(cert));
  14475. std::string common_name = cert.subject_cn();
  14476. EXPECT_EQ("Common Name", common_name);
  14477. });
  14478. auto port = svr.bind_to_any_port(HOST);
  14479. ASSERT_LT(0, port);
  14480. thread t = thread([&]() { svr.listen_after_bind(); });
  14481. auto se = detail::scope_exit([&] {
  14482. svr.stop();
  14483. t.join();
  14484. ASSERT_FALSE(svr.is_running());
  14485. });
  14486. svr.wait_until_ready();
  14487. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14488. client_encrypted_private_key_pass);
  14489. cli.enable_server_certificate_verification(false);
  14490. cli.set_connection_timeout(30);
  14491. auto res = cli.Get("/test");
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. ASSERT_EQ(StatusCode::OK_200, res->status);
  14494. }
  14495. TEST(SSLClientServerTest, ClientCertPresent) {
  14496. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14497. }
  14498. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14499. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14500. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14501. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14502. }
  14503. // Expects svr, which must require client certificates, to reject a client
  14504. // that has none
  14505. void RejectsClientWithoutCert(SSLServer &svr) {
  14506. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14507. auto port = svr.bind_to_any_port(HOST);
  14508. ASSERT_LT(0, port);
  14509. thread t = thread([&]() { svr.listen_after_bind(); });
  14510. auto se = detail::scope_exit([&] {
  14511. svr.stop();
  14512. t.join();
  14513. ASSERT_FALSE(svr.is_running());
  14514. });
  14515. svr.wait_until_ready();
  14516. SSLClient cli(HOST, port);
  14517. cli.set_connection_timeout(30);
  14518. // Skip the server certificate check, so that the request fails because the
  14519. // client certificate is missing rather than because cert.pem is not trusted
  14520. cli.enable_server_certificate_verification(false);
  14521. auto res = cli.Get("/test");
  14522. ASSERT_FALSE(res);
  14523. // The server rejects the client during the handshake, or on TLS 1.3 right
  14524. // after it, which the client notices on its first write or read
  14525. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14526. res.error() == Error::Write || res.error() == Error::Read)
  14527. << to_string(res.error());
  14528. if (res.error() == Error::SSLConnection) {
  14529. EXPECT_NE(0UL, res.ssl_backend_error());
  14530. }
  14531. // A rejection noticed on the write keeps the TLS error the write hit
  14532. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14533. }
  14534. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14536. ASSERT_TRUE(svr.is_valid());
  14537. if (setup) { setup(svr); }
  14538. RejectsClientWithoutCert(svr);
  14539. }
  14540. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14541. // A server that requires client certificates must keep requiring them after
  14542. // setup changes it, and keep accepting a client that has one
  14543. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14544. ClientCertMissing(setup);
  14545. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14546. setup);
  14547. }
  14548. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14549. ClientCertStillRequired([](SSLServer &svr) {
  14550. ASSERT_TRUE(tls::set_verify_callback(
  14551. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14552. });
  14553. }
  14554. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14555. ClientCertStillRequired([](SSLServer &svr) {
  14556. ASSERT_TRUE(tls::set_verify_callback(
  14557. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14558. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14559. });
  14560. }
  14561. // The client verifies the server certificate during the handshake, so a
  14562. // server that fails the check never gets the client certificate, even when a
  14563. // verifier of the client's own accepts it
  14564. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14565. struct Case {
  14566. const char *trusted_ca;
  14567. const char *host;
  14568. Error error;
  14569. };
  14570. // cert2.pem names localhost: the first client does not trust it, and the
  14571. // second trusts it but asks for another name
  14572. for (const auto &c :
  14573. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14574. Case{SERVER_CERT2_FILE, "example.com",
  14575. Error::SSLServerHostnameVerification}}) {
  14576. for (auto with_verifier : {false, true}) {
  14577. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14578. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14579. CLIENT_CA_CERT_FILE);
  14580. ASSERT_TRUE(svr.is_valid());
  14581. std::atomic<bool> got_client_cert{false};
  14582. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14583. [&](const tls::VerifyContext &) {
  14584. got_client_cert = true;
  14585. return true;
  14586. }));
  14587. auto port = svr.bind_to_any_port("127.0.0.1");
  14588. ASSERT_LT(0, port);
  14589. thread t = thread([&] { svr.listen_after_bind(); });
  14590. svr.wait_until_ready();
  14591. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14592. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14593. cli.set_ca_cert_path(c.trusted_ca);
  14594. if (with_verifier) {
  14595. cli.set_server_certificate_verifier(
  14596. [](const tls::VerifyContext &) { return true; });
  14597. }
  14598. auto res = cli.Get("/");
  14599. EXPECT_FALSE(res);
  14600. EXPECT_EQ(c.error, res.error());
  14601. svr.stop();
  14602. t.join();
  14603. EXPECT_FALSE(got_client_cert);
  14604. }
  14605. }
  14606. }
  14607. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14608. std::string cert_pem, key_pem, ca_pem;
  14609. read_file(SERVER_CERT_FILE, cert_pem);
  14610. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14611. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14612. ASSERT_TRUE(
  14613. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14614. }
  14615. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14617. ASSERT_TRUE(svr.is_valid());
  14618. UpdateCertsPemWithClientCA(svr);
  14619. RejectsClientWithoutCert(svr);
  14620. }
  14621. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14622. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14623. }
  14624. // A TLS error from one request must not show up in a later request's Result
  14625. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14627. ASSERT_TRUE(svr.is_valid());
  14628. svr.Get("/test", [](const Request &, Response &res) {
  14629. res.set_content("test", "text/plain");
  14630. });
  14631. auto port = svr.bind_to_any_port(HOST);
  14632. ASSERT_LT(0, port);
  14633. thread t = thread([&]() { svr.listen_after_bind(); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. ASSERT_FALSE(svr.is_running());
  14638. });
  14639. svr.wait_until_ready();
  14640. SSLClient cli(HOST, port);
  14641. cli.set_connection_timeout(30);
  14642. cli.enable_server_hostname_verification(false);
  14643. // cert.pem is not trusted, so the handshake fails
  14644. ASSERT_FALSE(cli.Get("/test"));
  14645. cli.enable_server_certificate_verification(false);
  14646. auto res = cli.Get("/test");
  14647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14648. EXPECT_EQ(0, res.ssl_error());
  14649. EXPECT_EQ(0UL, res.ssl_backend_error());
  14650. }
  14651. // PEM memory-based constructor tests (works with all TLS backends).
  14652. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14653. // terminator after it.
  14654. void PemMemoryClientCertPresent(
  14655. const std::string &client_cert_file,
  14656. const std::string &client_private_key_file,
  14657. const std::string &client_encrypted_private_key_pass = std::string(),
  14658. bool exact_size = false) {
  14659. // Read PEM files into memory
  14660. std::string server_cert_pem, server_key_pem;
  14661. std::string client_ca_pem;
  14662. std::string client_cert_pem, client_key_pem;
  14663. read_file(SERVER_CERT_FILE, server_cert_pem);
  14664. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14665. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14666. read_file(client_cert_file, client_cert_pem);
  14667. read_file(client_private_key_file, client_key_pem);
  14668. std::list<std::vector<char>> exact_copies;
  14669. auto data = [&](const std::string &pem) -> const char * {
  14670. if (!exact_size) { return pem.c_str(); }
  14671. exact_copies.emplace_back(pem.begin(), pem.end());
  14672. return exact_copies.back().data();
  14673. };
  14674. // Create server with PEM memory
  14675. SSLServer::PemMemory server_pem = {
  14676. data(server_cert_pem),
  14677. server_cert_pem.size(),
  14678. data(server_key_pem),
  14679. server_key_pem.size(),
  14680. data(client_ca_pem),
  14681. client_ca_pem.size(),
  14682. nullptr // no password for server key
  14683. };
  14684. SSLServer svr(server_pem);
  14685. ASSERT_TRUE(svr.is_valid());
  14686. svr.Get("/test", [&](const Request &req, Response &res) {
  14687. res.set_content("test", "text/plain");
  14688. auto cert = req.peer_cert();
  14689. ASSERT_TRUE(static_cast<bool>(cert));
  14690. EXPECT_EQ("Common Name", cert.subject_cn());
  14691. });
  14692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14693. auto se = detail::scope_exit([&] {
  14694. svr.stop();
  14695. t.join();
  14696. ASSERT_FALSE(svr.is_running());
  14697. });
  14698. svr.wait_until_ready();
  14699. // Create client with PEM memory
  14700. const char *password = client_encrypted_private_key_pass.empty()
  14701. ? nullptr
  14702. : client_encrypted_private_key_pass.c_str();
  14703. SSLClient::PemMemory client_pem = {
  14704. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14705. client_key_pem.size(), password};
  14706. SSLClient cli(HOST, PORT, client_pem);
  14707. cli.enable_server_certificate_verification(false);
  14708. cli.set_connection_timeout(30);
  14709. auto res = cli.Get("/test");
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. ASSERT_EQ(StatusCode::OK_200, res->status);
  14712. }
  14713. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14714. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14715. }
  14716. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14717. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14718. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14719. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14720. }
  14721. // A server built from PEM memory with a client CA requires client certificates,
  14722. // also when the CA is a NUL-terminated string passed with a length of 0
  14723. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14724. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14725. read_file(SERVER_CERT_FILE, server_cert_pem);
  14726. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14727. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14728. SSLServer::PemMemory server_pem = {
  14729. server_cert_pem.c_str(),
  14730. server_cert_pem.size(),
  14731. server_key_pem.c_str(),
  14732. server_key_pem.size(),
  14733. client_ca_pem.c_str(),
  14734. client_ca_pem.size(),
  14735. nullptr // no password for server key
  14736. };
  14737. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14738. SCOPED_TRACE(client_ca_pem_len);
  14739. server_pem.client_ca_pem_len = client_ca_pem_len;
  14740. SSLServer svr(server_pem);
  14741. ASSERT_TRUE(svr.is_valid());
  14742. RejectsClientWithoutCert(svr);
  14743. }
  14744. // An empty CA fails to load instead of turning the check off
  14745. server_pem.client_ca_pem = "";
  14746. server_pem.client_ca_pem_len = 0;
  14747. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14748. }
  14749. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14750. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14751. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14752. true);
  14753. }
  14754. // A length shorter than the PEM cuts it short, so it no longer loads
  14755. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14756. std::string cert, key;
  14757. read_file(SERVER_CERT_FILE, cert);
  14758. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14759. for (auto cut_cert : {true, false}) {
  14760. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14761. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14762. SSLServer::PemMemory server_pem = {
  14763. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14764. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14765. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14766. key_len, nullptr};
  14767. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14768. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14769. key.c_str(), key_len, nullptr};
  14770. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14771. }
  14772. }
  14773. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14774. class NoListenSSLServer : public SSLServer {
  14775. public:
  14776. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14777. const char *client_ca_cert_file_path,
  14778. const char *client_ca_cert_dir_path = nullptr)
  14779. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14780. client_ca_cert_dir_path),
  14781. stop_(false) {}
  14782. std::atomic_bool stop_;
  14783. private:
  14784. bool process_and_close_socket(socket_t /*sock*/) override {
  14785. // Don't create SSL context
  14786. while (!stop_.load()) {
  14787. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14788. }
  14789. return true;
  14790. }
  14791. };
  14792. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14793. CLIENT_CA_CERT_FILE);
  14794. ASSERT_TRUE(svr.is_valid());
  14795. // Keep-alive parking would bypass the override.
  14796. svr.set_keep_alive_parking(false);
  14797. svr.Get("/test", [&](const Request &, Response &res) {
  14798. res.set_content("test", "text/plain");
  14799. });
  14800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14801. auto se = detail::scope_exit([&] {
  14802. svr.stop_ = true;
  14803. svr.stop();
  14804. t.join();
  14805. ASSERT_FALSE(svr.is_running());
  14806. });
  14807. svr.wait_until_ready();
  14808. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14809. cli.enable_server_certificate_verification(false);
  14810. cli.set_connection_timeout(1);
  14811. auto res = cli.Get("/test");
  14812. ASSERT_TRUE(!res);
  14813. EXPECT_EQ(Error::SSLConnection, res.error());
  14814. // Timeout results in WantRead error code (maps to backend-specific value)
  14815. EXPECT_NE(0, res.ssl_error());
  14816. }
  14817. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14818. // Test SSLServer with client certificate verification using the standard
  14819. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14821. CLIENT_CA_CERT_DIR);
  14822. ASSERT_TRUE(svr.is_valid());
  14823. svr.Get("/test", [&](const Request &req, Response &res) {
  14824. res.set_content("test", "text/plain");
  14825. auto cert = req.peer_cert();
  14826. ASSERT_TRUE(static_cast<bool>(cert));
  14827. auto common_name = cert.subject_cn();
  14828. EXPECT_EQ("Common Name", common_name);
  14829. });
  14830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14831. auto se = detail::scope_exit([&] {
  14832. svr.stop();
  14833. t.join();
  14834. ASSERT_FALSE(svr.is_running());
  14835. });
  14836. svr.wait_until_ready();
  14837. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14838. cli.enable_server_certificate_verification(false);
  14839. cli.set_connection_timeout(30);
  14840. auto res = cli.Get("/test");
  14841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14842. ASSERT_EQ(StatusCode::OK_200, res->status);
  14843. }
  14844. // Test verify_hostname on every backend: a host is named by a SAN only
  14845. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14846. using namespace httplib::tls;
  14847. // We need a running server to test against
  14848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14849. ASSERT_TRUE(svr.is_valid());
  14850. svr.Get("/test", [](const Request &, Response &res) {
  14851. res.set_content("ok", "text/plain");
  14852. });
  14853. thread t([&]() { svr.listen(HOST, PORT); });
  14854. auto se = detail::scope_exit([&] {
  14855. svr.stop();
  14856. t.join();
  14857. });
  14858. svr.wait_until_ready();
  14859. bool verify_callback_called = false;
  14860. bool verify_result_wrong = false;
  14861. SSLClient cli(HOST, PORT);
  14862. cli.enable_server_certificate_verification(true);
  14863. cli.set_ca_cert_path(CA_CERT_FILE);
  14864. cli.set_connection_timeout(5);
  14865. // Note: Test certificate has CN="Common Name", not "localhost"
  14866. bool verify_result_cn = false;
  14867. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14868. verify_callback_called = true;
  14869. if (!ctx.cert) return false;
  14870. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14871. verify_result_cn = ctx.check_hostname("Common Name");
  14872. // Test 2: wrong hostname should not match
  14873. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14874. return true; // Accept for the purpose of this test
  14875. });
  14876. auto res = cli.Get("/test");
  14877. // The request may succeed or fail depending on cert configuration
  14878. // but the callback should have been called
  14879. ASSERT_TRUE(verify_callback_called)
  14880. << "Verify callback should have been called";
  14881. EXPECT_FALSE(verify_result_cn)
  14882. << "verify_hostname must not match the certificate CN (no SAN)";
  14883. // Wrong hostname should not match
  14884. EXPECT_FALSE(verify_result_wrong)
  14885. << "verify_hostname should not match 'wronghost.example.com'";
  14886. }
  14887. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14888. // backend verifies it.
  14889. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14890. // Certificate CN is "localhost" and it carries no SAN.
  14891. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14892. ASSERT_TRUE(svr.is_valid());
  14893. svr.Get("/test", [](const Request &, Response &res) {
  14894. res.set_content("ok", "text/plain");
  14895. });
  14896. auto port = svr.bind_to_any_port(HOST);
  14897. thread t([&]() { svr.listen_after_bind(); });
  14898. auto se = detail::scope_exit([&] {
  14899. svr.stop();
  14900. t.join();
  14901. });
  14902. svr.wait_until_ready();
  14903. SSLClient cli("localhost", port);
  14904. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14905. cli.enable_server_certificate_verification(true);
  14906. cli.set_connection_timeout(5);
  14907. auto res = cli.Get("/test");
  14908. ASSERT_FALSE(res);
  14909. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14910. // The same certificate is accepted once host name verification is off, so the
  14911. // failure above is the host name and not the chain.
  14912. cli.enable_server_hostname_verification(false);
  14913. res = cli.Get("/test");
  14914. ASSERT_TRUE(res) << to_string(res.error());
  14915. EXPECT_EQ(StatusCode::OK_200, res->status);
  14916. }
  14917. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14918. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14919. // X509_check_ip behavior and must hold for every backend.
  14920. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14921. using namespace httplib::tls;
  14922. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14923. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14924. ASSERT_TRUE(svr.is_valid());
  14925. svr.Get("/test", [](const Request &, Response &res) {
  14926. res.set_content("ok", "text/plain");
  14927. });
  14928. thread t([&]() { svr.listen(HOST, PORT); });
  14929. auto se = detail::scope_exit([&] {
  14930. svr.stop();
  14931. t.join();
  14932. });
  14933. svr.wait_until_ready();
  14934. bool verify_callback_called = false;
  14935. bool ip_matched_via_cn = true;
  14936. SSLClient cli(HOST, PORT);
  14937. cli.enable_server_certificate_verification(true);
  14938. cli.set_ca_cert_path(CA_CERT_FILE);
  14939. cli.set_connection_timeout(5);
  14940. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14941. verify_callback_called = true;
  14942. if (!ctx.cert) return false;
  14943. // The IP appears only in the CN, so it must NOT be accepted.
  14944. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14945. return true; // Accept for the purpose of this test
  14946. });
  14947. cli.Get("/test");
  14948. ASSERT_TRUE(verify_callback_called)
  14949. << "Verify callback should have been called";
  14950. EXPECT_FALSE(ip_matched_via_cn)
  14951. << "An IP host must not be authenticated via the certificate CN";
  14952. }
  14953. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14954. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14955. using namespace httplib::tls;
  14956. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14957. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14958. ASSERT_TRUE(svr.is_valid());
  14959. svr.Get("/test", [](const Request &, Response &res) {
  14960. res.set_content("ok", "text/plain");
  14961. });
  14962. thread t([&]() { svr.listen(HOST, PORT); });
  14963. auto se = detail::scope_exit([&] {
  14964. svr.stop();
  14965. t.join();
  14966. });
  14967. svr.wait_until_ready();
  14968. bool verify_callback_called = false;
  14969. bool san_matched = false;
  14970. bool wrong_ipv6_matched = true;
  14971. bool cn_ipv6_matched = true;
  14972. SSLClient cli(HOST, PORT);
  14973. cli.enable_server_certificate_verification(true);
  14974. cli.set_ca_cert_path(CA_CERT_FILE);
  14975. cli.set_connection_timeout(5);
  14976. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14977. verify_callback_called = true;
  14978. if (!ctx.cert) return false;
  14979. // Matches the IPv6 iPAddress SAN.
  14980. san_matched = ctx.check_hostname("2001:db8::1");
  14981. // A different IPv6 address must not match.
  14982. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14983. // "::1" lives only in the CN, so it must not be accepted.
  14984. cn_ipv6_matched = ctx.check_hostname("::1");
  14985. return true; // Accept for the purpose of this test
  14986. });
  14987. cli.Get("/test");
  14988. ASSERT_TRUE(verify_callback_called)
  14989. << "Verify callback should have been called";
  14990. EXPECT_TRUE(san_matched)
  14991. << "verify_hostname should match an IPv6 iPAddress SAN";
  14992. EXPECT_FALSE(wrong_ipv6_matched)
  14993. << "verify_hostname should not match a non-matching IPv6 address";
  14994. EXPECT_FALSE(cn_ipv6_matched)
  14995. << "An IPv6 host must not be authenticated via the certificate CN";
  14996. }
  14997. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14998. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14999. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15000. using namespace httplib::tls;
  15001. // SANs: DNS:a.zz, IP:42.46.122.122
  15002. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15003. ASSERT_TRUE(svr.is_valid());
  15004. svr.Get("/test", [](const Request &, Response &res) {
  15005. res.set_content("ok", "text/plain");
  15006. });
  15007. auto port = svr.bind_to_any_port(HOST);
  15008. thread t([&]() { svr.listen_after_bind(); });
  15009. auto se = detail::scope_exit([&] {
  15010. svr.stop();
  15011. t.join();
  15012. });
  15013. svr.wait_until_ready();
  15014. bool verify_callback_called = false;
  15015. bool dns_san_matched = false;
  15016. bool ip_san_matched = false;
  15017. bool ip_matched_via_dns_san = true;
  15018. bool dns_matched_via_ip_san = true;
  15019. bool cn_matched_next_to_dns_san = true;
  15020. SSLClient cli(HOST, port);
  15021. cli.enable_server_certificate_verification(true);
  15022. cli.set_ca_cert_path(CA_CERT_FILE);
  15023. cli.set_connection_timeout(5);
  15024. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15025. verify_callback_called = true;
  15026. if (!ctx.cert) return false;
  15027. dns_san_matched = ctx.check_hostname("a.zz");
  15028. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15029. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15030. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15031. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15032. return true; // Accept for the purpose of this test
  15033. });
  15034. cli.Get("/test");
  15035. ASSERT_TRUE(verify_callback_called)
  15036. << "Verify callback should have been called";
  15037. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15038. EXPECT_TRUE(ip_san_matched)
  15039. << "verify_hostname should match an iPAddress SAN";
  15040. EXPECT_FALSE(ip_matched_via_dns_san)
  15041. << "An IP host must not be authenticated via a dNSName SAN";
  15042. EXPECT_FALSE(dns_matched_via_ip_san)
  15043. << "A DNS host must not be authenticated via an iPAddress SAN";
  15044. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15045. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15046. }
  15047. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15048. // "www.*.example.test" names one host and not every host under example.test.
  15049. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15050. using namespace httplib::tls;
  15051. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15052. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15053. ASSERT_TRUE(svr.is_valid());
  15054. svr.Get("/test", [](const Request &, Response &res) {
  15055. res.set_content("ok", "text/plain");
  15056. });
  15057. auto port = svr.bind_to_any_port(HOST);
  15058. thread t([&]() { svr.listen_after_bind(); });
  15059. auto se = detail::scope_exit([&] {
  15060. svr.stop();
  15061. t.join();
  15062. });
  15063. svr.wait_until_ready();
  15064. bool verify_callback_called = false;
  15065. bool leftmost_wildcard_matched = false;
  15066. bool wildcard_spanned_labels = true;
  15067. bool inner_wildcard_matched = true;
  15068. SSLClient cli(HOST, port);
  15069. cli.enable_server_certificate_verification(true);
  15070. cli.set_ca_cert_path(CA_CERT_FILE);
  15071. cli.set_connection_timeout(5);
  15072. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15073. verify_callback_called = true;
  15074. if (!ctx.cert) return false;
  15075. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15076. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15077. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15078. return true; // Accept for the purpose of this test
  15079. });
  15080. cli.Get("/test");
  15081. ASSERT_TRUE(verify_callback_called)
  15082. << "Verify callback should have been called";
  15083. EXPECT_TRUE(leftmost_wildcard_matched)
  15084. << "A leftmost wildcard should match a single label";
  15085. EXPECT_FALSE(wildcard_spanned_labels)
  15086. << "A wildcard label must not match more than one label";
  15087. EXPECT_FALSE(inner_wildcard_matched)
  15088. << "A wildcard outside the leftmost label must not be honoured";
  15089. }
  15090. // sans() must report each SAN entry under its own type.
  15091. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15092. using namespace httplib::tls;
  15093. // SANs: DNS:a.zz, IP:42.46.122.122
  15094. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15095. ASSERT_TRUE(svr.is_valid());
  15096. svr.Get("/test", [](const Request &, Response &res) {
  15097. res.set_content("ok", "text/plain");
  15098. });
  15099. auto port = svr.bind_to_any_port(HOST);
  15100. thread t([&]() { svr.listen_after_bind(); });
  15101. auto se = detail::scope_exit([&] {
  15102. svr.stop();
  15103. t.join();
  15104. });
  15105. svr.wait_until_ready();
  15106. bool verify_callback_called = false;
  15107. std::vector<SanEntry> sans;
  15108. SSLClient cli(HOST, port);
  15109. cli.enable_server_certificate_verification(true);
  15110. cli.set_ca_cert_path(CA_CERT_FILE);
  15111. cli.set_connection_timeout(5);
  15112. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15113. verify_callback_called = true;
  15114. if (!ctx.cert) return false;
  15115. sans = ctx.sans();
  15116. return true; // Accept for the purpose of this test
  15117. });
  15118. cli.Get("/test");
  15119. ASSERT_TRUE(verify_callback_called)
  15120. << "Verify callback should have been called";
  15121. auto has_san = [&](SanType type, const std::string &value) {
  15122. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15123. return san.type == type && san.value == value;
  15124. });
  15125. };
  15126. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15127. << "sans() should report the dNSName SAN";
  15128. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15129. << "sans() should report the iPAddress SAN";
  15130. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15131. << "sans() must not report the dNSName SAN as an address";
  15132. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15133. << "sans() must not report the iPAddress SAN as a DNS name";
  15134. }
  15135. #endif
  15136. // mbedTLS-specific callback constructor test
  15137. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15138. #ifdef CPPHTTPLIB_SSL_ENABLED
  15139. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15141. ASSERT_TRUE(svr.is_valid());
  15142. // Set up a handler to verify client certificate is present
  15143. bool client_cert_verified = false;
  15144. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15145. // Verify that client certificate was provided
  15146. client_cert_verified = true;
  15147. res.set_content("success", "text/plain");
  15148. });
  15149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15150. auto se = detail::scope_exit([&] {
  15151. svr.stop();
  15152. t.join();
  15153. ASSERT_FALSE(svr.is_running());
  15154. });
  15155. svr.wait_until_ready();
  15156. // Client with certificate
  15157. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15158. cli.enable_server_certificate_verification(false);
  15159. cli.set_connection_timeout(30);
  15160. auto res = cli.Get("/test");
  15161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15162. ASSERT_EQ(StatusCode::OK_200, res->status);
  15163. ASSERT_TRUE(client_cert_verified);
  15164. EXPECT_EQ("success", res->body);
  15165. }
  15166. #endif
  15167. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15168. // backends
  15169. #ifdef CPPHTTPLIB_SSL_ENABLED
  15170. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15171. using namespace httplib::tls;
  15172. // Test that when client CA cert file is provided,
  15173. // the server properly requests and validates client certificates
  15174. // Create a server with client authentication
  15175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15176. ASSERT_TRUE(svr.is_valid());
  15177. bool handler_called = false;
  15178. svr.Get("/test", [&](const Request &req, Response &res) {
  15179. handler_called = true;
  15180. // Verify that a client certificate was provided
  15181. auto cert = req.peer_cert();
  15182. ASSERT_TRUE(static_cast<bool>(cert));
  15183. // Get the issuer name
  15184. std::string issuer_str = cert.issuer_name();
  15185. ASSERT_FALSE(issuer_str.empty());
  15186. // The client certificate should be issued by our test CA
  15187. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15188. res.set_content("authenticated", "text/plain");
  15189. });
  15190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. ASSERT_FALSE(svr.is_running());
  15195. });
  15196. svr.wait_until_ready();
  15197. // Connect with a client certificate issued by the CA
  15198. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15199. cli.enable_server_certificate_verification(false);
  15200. cli.set_connection_timeout(30);
  15201. auto res = cli.Get("/test");
  15202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15203. ASSERT_EQ(StatusCode::OK_200, res->status);
  15204. ASSERT_TRUE(handler_called);
  15205. EXPECT_EQ("authenticated", res->body);
  15206. }
  15207. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15208. using namespace httplib::tls;
  15209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15210. ASSERT_TRUE(svr.is_valid());
  15211. svr.Get("/test", [](const Request &, Response &res) {
  15212. res.set_content("ok", "text/plain");
  15213. });
  15214. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15215. auto se = detail::scope_exit([&] {
  15216. svr.stop();
  15217. t.join();
  15218. });
  15219. svr.wait_until_ready();
  15220. SSLClient cli(HOST, PORT);
  15221. cli.enable_server_certificate_verification(false);
  15222. cli.set_connection_timeout(30);
  15223. bool cert_checked = false;
  15224. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15225. if (ctx.cert) {
  15226. auto sans = ctx.sans();
  15227. // Test certificate may or may not have SANs - just verify the API
  15228. // works If SANs exist, verify the types are valid
  15229. for (const auto &san : sans) {
  15230. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15231. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15232. san.type == SanType::OTHER);
  15233. EXPECT_FALSE(san.value.empty());
  15234. }
  15235. cert_checked = true;
  15236. }
  15237. return true;
  15238. });
  15239. auto res = cli.Get("/test");
  15240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15241. EXPECT_TRUE(cert_checked);
  15242. }
  15243. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15244. using namespace httplib::tls;
  15245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15246. ASSERT_TRUE(svr.is_valid());
  15247. svr.Get("/test", [](const Request &, Response &res) {
  15248. res.set_content("ok", "text/plain");
  15249. });
  15250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15251. auto se = detail::scope_exit([&] {
  15252. svr.stop();
  15253. t.join();
  15254. });
  15255. svr.wait_until_ready();
  15256. SSLClient cli(HOST, PORT);
  15257. cli.enable_server_certificate_verification(false);
  15258. cli.set_connection_timeout(30);
  15259. bool validity_checked = false;
  15260. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15261. if (ctx.cert) {
  15262. time_t not_before = 0, not_after = 0;
  15263. bool result = ctx.validity(not_before, not_after);
  15264. EXPECT_TRUE(result);
  15265. // Verify that not_before < now < not_after for a valid cert
  15266. time_t now = time(nullptr);
  15267. EXPECT_LT(not_before, now);
  15268. EXPECT_GT(not_after, now);
  15269. validity_checked = true;
  15270. }
  15271. return true;
  15272. });
  15273. auto res = cli.Get("/test");
  15274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15275. EXPECT_TRUE(validity_checked);
  15276. }
  15277. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15278. using namespace httplib::tls;
  15279. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15280. ASSERT_TRUE(svr.is_valid());
  15281. svr.Get("/test", [](const Request &, Response &res) {
  15282. res.set_content("ok", "text/plain");
  15283. });
  15284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15285. auto se = detail::scope_exit([&] {
  15286. svr.stop();
  15287. t.join();
  15288. });
  15289. svr.wait_until_ready();
  15290. SSLClient cli(HOST, PORT);
  15291. cli.enable_server_certificate_verification(false);
  15292. cli.set_connection_timeout(30);
  15293. bool serial_checked = false;
  15294. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15295. if (ctx.cert) {
  15296. std::string serial = ctx.serial();
  15297. EXPECT_FALSE(serial.empty());
  15298. // Serial should be a hex string
  15299. for (char c : serial) {
  15300. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15301. (c >= 'a' && c <= 'f'));
  15302. }
  15303. serial_checked = true;
  15304. }
  15305. return true;
  15306. });
  15307. auto res = cli.Get("/test");
  15308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15309. EXPECT_TRUE(serial_checked);
  15310. }
  15311. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15312. // Test 1: Valid CA file - no error should be recorded
  15313. {
  15314. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15315. CLIENT_CA_CERT_FILE);
  15316. ASSERT_TRUE(svr.is_valid());
  15317. // With valid setup, last_ssl_error should be 0
  15318. EXPECT_EQ(0, svr.ssl_last_error());
  15319. }
  15320. // Test 2: Invalid CA file content
  15321. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15322. {
  15323. // Create a temporary file with completely invalid content
  15324. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15325. {
  15326. std::ofstream ofs(temp_invalid_ca);
  15327. ofs << "This is not a certificate file at all\n";
  15328. ofs << "Just plain text content\n";
  15329. }
  15330. // Create server with invalid CA file
  15331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15332. // Clean up temporary file
  15333. std::remove(temp_invalid_ca);
  15334. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15335. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15336. // Note: SSL_CTX_load_verify_locations typically fails first,
  15337. // but our error handling code path is still exercised
  15338. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15339. }
  15340. }
  15341. TEST(VerifyCallbackTest, VerifyContextFields) {
  15342. using namespace httplib::tls;
  15343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15344. ASSERT_TRUE(svr.is_valid());
  15345. svr.Get("/test", [](const Request &, Response &res) {
  15346. res.set_content("ok", "text/plain");
  15347. });
  15348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. });
  15353. svr.wait_until_ready();
  15354. SSLClient cli(HOST, PORT);
  15355. cli.enable_server_certificate_verification(false);
  15356. cli.set_connection_timeout(30);
  15357. int callback_count = 0;
  15358. bool saw_leaf_cert = false;
  15359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15360. if (ctx.cert) {
  15361. callback_count++;
  15362. // We should see at least one certificate (the leaf)
  15363. std::string cn = ctx.subject_cn();
  15364. if (!cn.empty()) { saw_leaf_cert = true; }
  15365. // Verify context fields are populated
  15366. EXPECT_NE(ctx.session, nullptr);
  15367. EXPECT_GE(ctx.depth, 0);
  15368. }
  15369. return true;
  15370. });
  15371. auto res = cli.Get("/test");
  15372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15373. EXPECT_GT(callback_count, 0);
  15374. EXPECT_TRUE(saw_leaf_cert);
  15375. }
  15376. // A verifier that accepts runs alongside the built-in verification, and is the
  15377. // only check once that is turned off.
  15378. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15379. using namespace httplib::tls;
  15380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15381. ASSERT_TRUE(svr.is_valid());
  15382. svr.Get("/test", [](const Request &, Response &res) {
  15383. res.set_content("ok", "text/plain");
  15384. });
  15385. auto port = svr.bind_to_any_port(HOST);
  15386. thread t([&]() { svr.listen_after_bind(); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. });
  15391. svr.wait_until_ready();
  15392. SSLClient cli(HOST, port);
  15393. cli.enable_server_hostname_verification(false);
  15394. auto calls = 0;
  15395. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15396. calls++;
  15397. return true;
  15398. });
  15399. // cert.pem is not trusted
  15400. auto res = cli.Get("/test");
  15401. ASSERT_FALSE(res);
  15402. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15403. EXPECT_GT(calls, 0);
  15404. cli.enable_server_certificate_verification(false);
  15405. res = cli.Get("/test");
  15406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15407. EXPECT_EQ("ok", res->body);
  15408. }
  15409. // A verifier belongs to the client that set it, not to the thread that set it.
  15410. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15411. using namespace httplib::tls;
  15412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15413. ASSERT_TRUE(svr.is_valid());
  15414. svr.Get("/test", [](const Request &, Response &res) {
  15415. res.set_content("ok", "text/plain");
  15416. });
  15417. auto port = svr.bind_to_any_port(HOST);
  15418. thread t([&]() { svr.listen_after_bind(); });
  15419. auto se = detail::scope_exit([&] {
  15420. svr.stop();
  15421. t.join();
  15422. });
  15423. svr.wait_until_ready();
  15424. auto rejecting_calls = 0;
  15425. SSLClient rejecting(HOST, port);
  15426. rejecting.enable_server_certificate_verification(false);
  15427. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15428. rejecting_calls++;
  15429. return false;
  15430. });
  15431. auto accepting_calls = 0;
  15432. SSLClient accepting(HOST, port);
  15433. accepting.enable_server_certificate_verification(false);
  15434. // Set on another thread than the requests below.
  15435. thread([&]() {
  15436. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15437. accepting_calls++;
  15438. return true;
  15439. });
  15440. }).join();
  15441. // Requested on another thread than the verifier was set on.
  15442. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15443. EXPECT_GT(rejecting_calls, 0);
  15444. auto res = accepting.Get("/test");
  15445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15446. EXPECT_GT(accepting_calls, 0);
  15447. }
  15448. // A verifier replaced while a handshake runs it lives until it returns.
  15449. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15450. using namespace httplib::tls;
  15451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15452. ASSERT_TRUE(svr.is_valid());
  15453. svr.Get("/test", [](const Request &, Response &res) {
  15454. res.set_content("ok", "text/plain");
  15455. });
  15456. auto port = svr.bind_to_any_port(HOST);
  15457. thread t([&]() { svr.listen_after_bind(); });
  15458. auto se = detail::scope_exit([&] {
  15459. svr.stop();
  15460. t.join();
  15461. });
  15462. svr.wait_until_ready();
  15463. SSLClient cli(HOST, port);
  15464. cli.enable_server_certificate_verification(false);
  15465. std::promise<void> entered;
  15466. std::promise<void> replaced;
  15467. auto replaced_future = replaced.get_future();
  15468. auto first_call = true;
  15469. // Long enough to live on the heap
  15470. std::string expected(64, 'v');
  15471. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15472. if (first_call) {
  15473. first_call = false;
  15474. entered.set_value();
  15475. replaced_future.wait();
  15476. }
  15477. return expected == std::string(64, 'v');
  15478. });
  15479. thread request([&]() {
  15480. auto res = cli.Get("/test");
  15481. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15482. });
  15483. entered.get_future().wait();
  15484. cli.set_server_certificate_verifier(
  15485. [](const VerifyContext &) { return true; });
  15486. replaced.set_value();
  15487. request.join();
  15488. }
  15489. // VerifyContext::session is the same handle the other tls:: functions take.
  15490. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15491. using namespace httplib::tls;
  15492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15493. ASSERT_TRUE(svr.is_valid());
  15494. svr.Get("/test", [](const Request &, Response &res) {
  15495. res.set_content("ok", "text/plain");
  15496. });
  15497. auto port = svr.bind_to_any_port(HOST);
  15498. thread t([&]() { svr.listen_after_bind(); });
  15499. auto se = detail::scope_exit([&] {
  15500. svr.stop();
  15501. t.join();
  15502. });
  15503. svr.wait_until_ready();
  15504. SSLClient cli(HOST, port);
  15505. cli.enable_server_certificate_verification(false);
  15506. session_t verifier_session = nullptr;
  15507. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15508. verifier_session = ctx.session;
  15509. return true;
  15510. });
  15511. session_t session_verifier_session = nullptr;
  15512. cli.set_session_verifier([&](session_t session) {
  15513. session_verifier_session = session;
  15514. return SSLVerifierResponse::NoDecisionMade;
  15515. });
  15516. auto res = cli.Get("/test");
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. EXPECT_NE(nullptr, verifier_session);
  15519. EXPECT_EQ(session_verifier_session, verifier_session);
  15520. }
  15521. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15522. using httplib::tls::TlsError;
  15523. // Test that verify_error_to_string returns empty for success
  15524. std::string success_str = TlsError::verify_error_to_string(0);
  15525. EXPECT_TRUE(success_str.empty());
  15526. // Test that verify_error_to_string returns non-empty for error codes
  15527. // Using a common error code (certificate expired)
  15528. std::string error_str =
  15529. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15530. EXPECT_FALSE(error_str.empty());
  15531. }
  15532. TEST(SessionVerifierTest, CertificateAccepted) {
  15533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15534. ASSERT_TRUE(svr.is_valid());
  15535. svr.Get("/test", [](const Request &, Response &res) {
  15536. res.set_content("ok", "text/plain");
  15537. });
  15538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15539. auto se = detail::scope_exit([&] {
  15540. svr.stop();
  15541. t.join();
  15542. });
  15543. svr.wait_until_ready();
  15544. SSLClient cli(HOST, PORT);
  15545. cli.enable_server_certificate_verification(false);
  15546. cli.set_connection_timeout(30);
  15547. bool callback_called = false;
  15548. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15549. EXPECT_NE(session, nullptr);
  15550. callback_called = true;
  15551. return SSLVerifierResponse::CertificateAccepted;
  15552. });
  15553. auto res = cli.Get("/test");
  15554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15555. EXPECT_EQ(200, res->status);
  15556. EXPECT_TRUE(callback_called);
  15557. }
  15558. TEST(SessionVerifierTest, CertificateRejected) {
  15559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15560. ASSERT_TRUE(svr.is_valid());
  15561. svr.Get("/test", [](const Request &, Response &res) {
  15562. res.set_content("ok", "text/plain");
  15563. });
  15564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15565. auto se = detail::scope_exit([&] {
  15566. svr.stop();
  15567. t.join();
  15568. });
  15569. svr.wait_until_ready();
  15570. SSLClient cli(HOST, PORT);
  15571. cli.enable_server_certificate_verification(false);
  15572. cli.set_connection_timeout(30);
  15573. bool callback_called = false;
  15574. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15575. EXPECT_NE(session, nullptr);
  15576. callback_called = true;
  15577. return SSLVerifierResponse::CertificateRejected;
  15578. });
  15579. auto res = cli.Get("/test");
  15580. EXPECT_FALSE(res);
  15581. EXPECT_TRUE(callback_called);
  15582. }
  15583. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15585. ASSERT_TRUE(svr.is_valid());
  15586. svr.Get("/test", [](const Request &, Response &res) {
  15587. res.set_content("ok", "text/plain");
  15588. });
  15589. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15590. auto se = detail::scope_exit([&] {
  15591. svr.stop();
  15592. t.join();
  15593. });
  15594. svr.wait_until_ready();
  15595. // NoDecisionMade with verification disabled should succeed (no default check)
  15596. SSLClient cli(HOST, PORT);
  15597. cli.enable_server_certificate_verification(false);
  15598. cli.set_connection_timeout(30);
  15599. bool callback_called = false;
  15600. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15601. EXPECT_NE(session, nullptr);
  15602. callback_called = true;
  15603. return SSLVerifierResponse::NoDecisionMade;
  15604. });
  15605. auto res = cli.Get("/test");
  15606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15607. EXPECT_EQ(200, res->status);
  15608. EXPECT_TRUE(callback_called);
  15609. }
  15610. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15612. ASSERT_TRUE(svr.is_valid());
  15613. svr.Get("/test", [](const Request &, Response &res) {
  15614. res.set_content("ok", "text/plain");
  15615. });
  15616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15617. auto se = detail::scope_exit([&] {
  15618. svr.stop();
  15619. t.join();
  15620. });
  15621. svr.wait_until_ready();
  15622. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15623. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15624. // so we only check that the request fails, not whether the callback was
  15625. // called.
  15626. SSLClient cli(HOST, PORT);
  15627. cli.enable_server_certificate_verification(true);
  15628. cli.set_connection_timeout(30);
  15629. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15630. EXPECT_NE(session, nullptr);
  15631. return SSLVerifierResponse::NoDecisionMade;
  15632. });
  15633. auto res = cli.Get("/test");
  15634. EXPECT_FALSE(res);
  15635. }
  15636. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15637. // Test SSL server using PemMemory constructor with client CA certificates
  15638. // Read PEM files
  15639. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15640. read_file(SERVER_CERT_FILE, server_cert_pem);
  15641. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15642. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15643. // Create SSLServer with PemMemory constructor including client CA
  15644. SSLServer::PemMemory server_pem = {
  15645. server_cert_pem.c_str(),
  15646. server_cert_pem.size(),
  15647. server_key_pem.c_str(),
  15648. server_key_pem.size(),
  15649. client_ca_pem.c_str(),
  15650. client_ca_pem.size(),
  15651. nullptr // no password for server key
  15652. };
  15653. SSLServer svr(server_pem);
  15654. ASSERT_TRUE(svr.is_valid());
  15655. // No SSL error should be recorded for valid setup
  15656. EXPECT_EQ(0, svr.ssl_last_error());
  15657. // Set up server endpoints
  15658. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15659. res.set_content("ok", "text/plain");
  15660. });
  15661. // Start server in a thread
  15662. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15663. svr.wait_until_ready();
  15664. // Connect with client certificate (using constructor with paths)
  15665. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15666. cli.enable_server_certificate_verification(false);
  15667. auto res = cli.Get("/test-pem-ca");
  15668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15669. EXPECT_EQ(200, res->status);
  15670. EXPECT_EQ("ok", res->body);
  15671. svr.stop();
  15672. server_thread.join();
  15673. }
  15674. #endif
  15675. #ifdef _WIN32
  15676. TEST(CleanupTest, WSACleanup) {
  15677. int ret = WSACleanup();
  15678. ASSERT_EQ(0, ret);
  15679. }
  15680. #endif
  15681. #ifndef CPPHTTPLIB_SSL_ENABLED
  15682. TEST(NoSSLSupport, SimpleInterface) {
  15683. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15684. }
  15685. #endif
  15686. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15687. TEST(InvalidScheme, SimpleInterface) {
  15688. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15689. }
  15690. #endif
  15691. TEST(NoScheme, SimpleInterface) {
  15692. Client cli("yahoo.com:80");
  15693. ASSERT_TRUE(cli.is_valid());
  15694. }
  15695. TEST(SendAPI, SimpleInterface_Online) {
  15696. Client cli("http://yahoo.com");
  15697. Request req;
  15698. req.method = "GET";
  15699. req.path = "/";
  15700. auto res = cli.send(req);
  15701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15703. }
  15704. TEST(SendAPI, WithParamsInRequest) {
  15705. Server svr;
  15706. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15707. EXPECT_TRUE(req.has_param("test"));
  15708. EXPECT_EQ("test_value", req.get_param_value("test"));
  15709. });
  15710. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15711. auto se = detail::scope_exit([&] {
  15712. svr.stop();
  15713. t.join();
  15714. ASSERT_FALSE(svr.is_running());
  15715. });
  15716. svr.wait_until_ready();
  15717. Client cli(HOST, PORT);
  15718. {
  15719. Request req;
  15720. req.method = "GET";
  15721. req.path = "/";
  15722. req.params.emplace("test", "test_value");
  15723. auto res = cli.send(req);
  15724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15725. }
  15726. {
  15727. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15729. }
  15730. }
  15731. TEST(ClientImplMethods, GetSocketTest) {
  15732. httplib::Server svr;
  15733. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15734. res.status = StatusCode::OK_200;
  15735. });
  15736. auto port = svr.bind_to_any_port("127.0.0.1");
  15737. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15738. auto se = detail::scope_exit([&] {
  15739. svr.stop();
  15740. thread.join();
  15741. ASSERT_FALSE(svr.is_running());
  15742. });
  15743. svr.wait_until_ready();
  15744. {
  15745. httplib::Client cli("127.0.0.1", port);
  15746. cli.set_keep_alive(true);
  15747. // Use the behavior of cpp-httplib of opening the connection
  15748. // only when the first request happens. If that changes,
  15749. // this test would be obsolete.
  15750. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15751. // This also implicitly tests the server. But other tests would fail much
  15752. // earlier than this one to be considered.
  15753. auto res = cli.Get("/");
  15754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15755. EXPECT_EQ(StatusCode::OK_200, res->status);
  15756. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15757. }
  15758. }
  15759. #ifdef CPPHTTPLIB_SSL_ENABLED
  15760. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15761. Client cli("http://yahoo.com");
  15762. auto res = cli.Get("/");
  15763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15764. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15765. cli.set_follow_location(true);
  15766. res = cli.Get("/");
  15767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15768. EXPECT_EQ(StatusCode::OK_200, res->status);
  15769. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15770. }
  15771. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15772. Client cli("https://yahoo.com");
  15773. auto res = cli.Get("/");
  15774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15775. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15776. cli.set_follow_location(true);
  15777. res = cli.Get("/");
  15778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15779. EXPECT_EQ(StatusCode::OK_200, res->status);
  15780. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15781. }
  15782. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15783. Client cli("https://yahoo.com");
  15784. auto res = cli.Get("/");
  15785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15786. ASSERT_FALSE(!res);
  15787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15788. ASSERT_FALSE(res == nullptr);
  15789. ASSERT_TRUE(res != nullptr);
  15790. EXPECT_EQ(Error::Success, res.error());
  15791. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15792. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15793. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15794. cli.set_follow_location(true);
  15795. res = cli.Get("/");
  15796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15797. EXPECT_EQ(Error::Success, res.error());
  15798. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15799. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15800. EXPECT_EQ(StatusCode::OK_200, res->status);
  15801. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15802. }
  15803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15804. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15805. Client cli("https://cdnjs.cloudflare.com");
  15806. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15807. Headers{{"Accept-Encoding", "br"}});
  15808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15809. EXPECT_EQ(StatusCode::OK_200, res->status);
  15810. EXPECT_EQ(287630U, res->body.size());
  15811. EXPECT_EQ("application/javascript; charset=utf-8",
  15812. res->get_header_value("Content-Type"));
  15813. }
  15814. #endif
  15815. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15816. #undef REDIR_HOST // Silence compiler warning
  15817. #define REDIR_HOST "https://httpbingo.org"
  15818. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15819. Client cli(REDIR_HOST);
  15820. cli.set_follow_location(true);
  15821. auto res =
  15822. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15824. EXPECT_EQ(StatusCode::OK_200, res->status);
  15825. }
  15826. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15827. Client cli(REDIR_HOST);
  15828. cli.set_follow_location(true);
  15829. Params params;
  15830. params.emplace("url", "http://example.com");
  15831. params.emplace("status_code", "302");
  15832. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. EXPECT_EQ(StatusCode::OK_200, res->status);
  15835. }
  15836. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15837. Client cli(REDIR_HOST);
  15838. cli.set_follow_location(true);
  15839. Params params;
  15840. params.emplace("url", "http://example.com");
  15841. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15843. EXPECT_EQ(StatusCode::OK_200, res->status);
  15844. }
  15845. TEST(HttpToHttpsRedirectTest, CertFile) {
  15846. auto ssl_port = PORT + 1;
  15847. Server svr;
  15848. ASSERT_TRUE(svr.is_valid());
  15849. svr.Get("/index", [&](const Request &, Response &res) {
  15850. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15851. "/index");
  15852. svr.stop();
  15853. });
  15854. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15855. ASSERT_TRUE(ssl_svr.is_valid());
  15856. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15857. res.set_content("test", "text/plain");
  15858. ssl_svr.stop();
  15859. });
  15860. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15861. thread t2 =
  15862. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15863. auto se = detail::scope_exit([&] {
  15864. t2.join();
  15865. t.join();
  15866. ASSERT_FALSE(svr.is_running());
  15867. });
  15868. svr.wait_until_ready();
  15869. ssl_svr.wait_until_ready();
  15870. Client cli("127.0.0.1", PORT);
  15871. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15872. cli.enable_server_certificate_verification(true);
  15873. cli.set_follow_location(true);
  15874. cli.set_connection_timeout(30);
  15875. auto res = cli.Get("/index");
  15876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15877. ASSERT_EQ(StatusCode::OK_200, res->status);
  15878. }
  15879. TEST(UppercaseSchemeTest, UsesTLS) {
  15880. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15881. ASSERT_TRUE(ssl_svr.is_valid());
  15882. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15883. res.set_content("test", "text/plain");
  15884. });
  15885. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15886. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15887. Server svr;
  15888. svr.Get("/index", [&](const Request &, Response &res) {
  15889. res.set_redirect(https_url + "/index");
  15890. });
  15891. auto port = svr.bind_to_any_port("127.0.0.1");
  15892. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15893. auto t2 = thread([&] { svr.listen_after_bind(); });
  15894. auto se = detail::scope_exit([&] {
  15895. svr.stop();
  15896. ssl_svr.stop();
  15897. t2.join();
  15898. t.join();
  15899. });
  15900. ssl_svr.wait_until_ready();
  15901. svr.wait_until_ready();
  15902. {
  15903. Client cli(https_url);
  15904. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15905. auto res = cli.Get("/index");
  15906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15907. EXPECT_EQ("test", res->body);
  15908. }
  15909. {
  15910. Client cli("127.0.0.1", port);
  15911. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15912. cli.set_follow_location(true);
  15913. auto res = cli.Get("/index");
  15914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15915. EXPECT_EQ("test", res->body);
  15916. }
  15917. }
  15918. TEST(SSLClientRedirectTest, CertFile) {
  15919. auto ssl_port = PORT + 1;
  15920. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15921. ASSERT_TRUE(ssl_svr1.is_valid());
  15922. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15923. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15924. "/index");
  15925. ssl_svr1.stop();
  15926. });
  15927. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15928. ASSERT_TRUE(ssl_svr2.is_valid());
  15929. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15930. res.set_content("test", "text/plain");
  15931. ssl_svr2.stop();
  15932. });
  15933. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15934. thread t2 =
  15935. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15936. auto se = detail::scope_exit([&] {
  15937. t2.join();
  15938. t.join();
  15939. ASSERT_FALSE(ssl_svr1.is_running());
  15940. });
  15941. ssl_svr1.wait_until_ready();
  15942. ssl_svr2.wait_until_ready();
  15943. SSLClient cli("127.0.0.1", PORT);
  15944. std::string cert;
  15945. read_file(SERVER_CERT2_FILE, cert);
  15946. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15947. cli.enable_server_certificate_verification(true);
  15948. cli.set_follow_location(true);
  15949. cli.set_connection_timeout(30);
  15950. auto res = cli.Get("/index");
  15951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15952. ASSERT_EQ(StatusCode::OK_200, res->status);
  15953. }
  15954. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15955. // another port, so the client follows it with a new client.
  15956. static Result GetThroughTlsRedirectToDifferentPort(
  15957. const std::function<void(SSLClient &)> &setup,
  15958. const char *target_cert = SERVER_CERT2_FILE,
  15959. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15960. auto ssl_port = PORT + 1;
  15961. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15962. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15963. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15964. "/index");
  15965. });
  15966. SSLServer ssl_svr2(target_cert, target_key);
  15967. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15968. res.set_content("test", "text/plain");
  15969. });
  15970. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15971. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15972. auto se = detail::scope_exit([&] {
  15973. ssl_svr2.stop();
  15974. ssl_svr1.stop();
  15975. t2.join();
  15976. t.join();
  15977. });
  15978. ssl_svr1.wait_until_ready();
  15979. ssl_svr2.wait_until_ready();
  15980. SSLClient cli("127.0.0.1", PORT);
  15981. cli.set_follow_location(true);
  15982. cli.set_connection_timeout(30);
  15983. setup(cli);
  15984. return cli.Get("/index");
  15985. }
  15986. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15987. auto calls = 0;
  15988. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15989. cli.enable_server_certificate_verification(false);
  15990. // Accept the first server only.
  15991. cli.set_session_verifier([&](tls::session_t) {
  15992. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15993. : SSLVerifierResponse::CertificateRejected;
  15994. });
  15995. });
  15996. ASSERT_FALSE(res);
  15997. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15998. EXPECT_EQ(2, calls);
  15999. }
  16000. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16001. std::string pinned;
  16002. auto res = GetThroughTlsRedirectToDifferentPort(
  16003. [&](SSLClient &cli) {
  16004. cli.enable_server_certificate_verification(false);
  16005. // Pin the first certificate seen.
  16006. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16007. if (pinned.empty()) { pinned = ctx.serial(); }
  16008. return ctx.serial() == pinned;
  16009. });
  16010. },
  16011. // A certificate other than the first server's.
  16012. SERVER_CERT_FILE);
  16013. EXPECT_FALSE(res);
  16014. EXPECT_FALSE(pinned.empty());
  16015. }
  16016. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16017. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16018. std::string cert;
  16019. read_file(SERVER_CERT2_FILE, cert);
  16020. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16021. });
  16022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16023. EXPECT_EQ(StatusCode::OK_200, res->status);
  16024. }
  16025. // The target's certificate is signed by the root CA, which the first server's
  16026. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16027. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16028. auto res = GetThroughTlsRedirectToDifferentPort(
  16029. [](SSLClient &cli) {
  16030. std::string root_ca, cert;
  16031. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16032. read_file(SERVER_CERT2_FILE, cert);
  16033. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16034. cli.load_ca_cert_store(cert.data(), cert.size());
  16035. cli.enable_server_hostname_verification(false);
  16036. },
  16037. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16039. EXPECT_EQ(StatusCode::OK_200, res->status);
  16040. }
  16041. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16042. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16043. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16044. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16045. auto res = GetThroughTlsRedirectToDifferentPort(
  16046. [](SSLClient &cli) {
  16047. std::string root_ca, cert;
  16048. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16049. read_file(SERVER_CERT2_FILE, cert);
  16050. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16051. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16052. cli.enable_server_hostname_verification(false);
  16053. },
  16054. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16055. ASSERT_FALSE(res);
  16056. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16057. }
  16058. #endif
  16059. #endif
  16060. #ifdef CPPHTTPLIB_SSL_ENABLED
  16061. // Test that set_ca_cert_store() skips system certs (consistent with
  16062. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16063. // should be trusted - system certs should NOT be loaded.
  16064. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16065. // Load a specific cert that is NOT a system CA cert
  16066. std::string cert;
  16067. read_file(SERVER_CERT2_FILE, cert);
  16068. SSLClient cli("google.com");
  16069. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16070. cli.enable_server_certificate_verification(true);
  16071. // This should FAIL because:
  16072. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16073. // 2. System certs should NOT be loaded when custom store is set
  16074. // If system certs WERE loaded, this would succeed
  16075. auto res = cli.Get("/");
  16076. ASSERT_FALSE(res);
  16077. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16078. }
  16079. // Same as above, but through the native store handle path. Regression test:
  16080. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16081. // merged system certs into the user-provided store.
  16082. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16083. std::string cert;
  16084. read_file(SERVER_CERT2_FILE, cert);
  16085. SSLClient cli("google.com");
  16086. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16087. cli.enable_server_certificate_verification(true);
  16088. auto res = cli.Get("/");
  16089. ASSERT_FALSE(res);
  16090. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16091. }
  16092. // A custom store set via the native handle must still verify a server whose
  16093. // cert it does contain.
  16094. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16095. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16096. ASSERT_TRUE(svr.is_valid());
  16097. svr.Get("/test", [&](const Request &, Response &res) {
  16098. res.set_content("test", "text/plain");
  16099. });
  16100. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16101. auto se = detail::scope_exit([&] {
  16102. svr.stop();
  16103. t.join();
  16104. ASSERT_FALSE(svr.is_running());
  16105. });
  16106. svr.wait_until_ready();
  16107. SSLClient cli("127.0.0.1", PORT);
  16108. std::string cert;
  16109. read_file(SERVER_CERT2_FILE, cert);
  16110. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16111. cli.enable_server_certificate_verification(true);
  16112. cli.set_connection_timeout(30);
  16113. auto res = cli.Get("/test");
  16114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16115. ASSERT_EQ(StatusCode::OK_200, res->status);
  16116. }
  16117. // CA certs loaded through the universal Client must be transferred to the
  16118. // client created internally for following an HTTPS redirect. Regression test:
  16119. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16120. // the CA data for redirect transfer.
  16121. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16122. auto ssl_port = PORT + 1;
  16123. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16124. ASSERT_TRUE(ssl_svr1.is_valid());
  16125. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16126. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16127. "/index");
  16128. });
  16129. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16130. ASSERT_TRUE(ssl_svr2.is_valid());
  16131. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16132. res.set_content("test", "text/plain");
  16133. });
  16134. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16135. thread t2 =
  16136. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16137. auto se = detail::scope_exit([&] {
  16138. ssl_svr2.stop();
  16139. ssl_svr1.stop();
  16140. t2.join();
  16141. t.join();
  16142. ASSERT_FALSE(ssl_svr1.is_running());
  16143. });
  16144. ssl_svr1.wait_until_ready();
  16145. ssl_svr2.wait_until_ready();
  16146. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16147. std::string cert;
  16148. read_file(SERVER_CERT2_FILE, cert);
  16149. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16150. cli.enable_server_certificate_verification(true);
  16151. cli.set_follow_location(true);
  16152. cli.set_connection_timeout(30);
  16153. auto res = cli.Get("/index");
  16154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16155. ASSERT_EQ(StatusCode::OK_200, res->status);
  16156. }
  16157. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16158. // so a host signed by a system CA verifies even though a custom CA is set
  16159. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16160. std::string cert;
  16161. read_file(SERVER_CERT2_FILE, cert);
  16162. SSLClient cli("google.com");
  16163. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16164. cli.enable_system_ca(true);
  16165. cli.enable_server_certificate_verification(true);
  16166. auto res = cli.Get("/");
  16167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16168. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16169. }
  16170. // The custom CA remains effective when combined with the system CA
  16171. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16172. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16173. ASSERT_TRUE(svr.is_valid());
  16174. svr.Get("/test", [&](const Request &, Response &res) {
  16175. res.set_content("test", "text/plain");
  16176. });
  16177. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16178. auto se = detail::scope_exit([&] {
  16179. svr.stop();
  16180. t.join();
  16181. ASSERT_FALSE(svr.is_running());
  16182. });
  16183. svr.wait_until_ready();
  16184. SSLClient cli("127.0.0.1", PORT);
  16185. std::string cert;
  16186. read_file(SERVER_CERT2_FILE, cert);
  16187. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16188. cli.enable_system_ca(true);
  16189. cli.enable_server_certificate_verification(true);
  16190. cli.set_connection_timeout(30);
  16191. auto res = cli.Get("/test");
  16192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16193. ASSERT_EQ(StatusCode::OK_200, res->status);
  16194. }
  16195. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16196. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16197. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16198. static CFDictionaryRef
  16199. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16200. const SecTrustSettingsResult *result) {
  16201. auto constraint =
  16202. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16203. &kCFTypeDictionaryValueCallBacks);
  16204. if (policy) {
  16205. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16206. }
  16207. if (policy_string) {
  16208. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16209. kCFStringEncodingUTF8);
  16210. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16211. CFRelease(str);
  16212. }
  16213. if (result) {
  16214. auto number_value = static_cast<SInt32>(*result);
  16215. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16216. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16217. CFRelease(number);
  16218. }
  16219. return constraint;
  16220. }
  16221. static SecTrustSettingsResult
  16222. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16223. auto trust_settings =
  16224. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16225. for (auto constraint : constraints) {
  16226. CFArrayAppendValue(trust_settings, constraint);
  16227. CFRelease(constraint);
  16228. }
  16229. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16230. CFRelease(trust_settings);
  16231. return result;
  16232. }
  16233. // The system CA loader takes a Keychain certificate as a trusted root only
  16234. // when its Trust Settings say so for SSL, not merely because it has some.
  16235. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16236. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16237. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16238. const auto deny = kSecTrustSettingsResultDeny;
  16239. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16240. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16241. auto x509_policy = SecPolicyCreateBasicX509();
  16242. // "Always Trust", which stores no constraint at all
  16243. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16244. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16245. ssl_trust_settings_result(
  16246. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16247. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16248. ssl_trust_settings_result(
  16249. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16250. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16251. ssl_trust_settings_result(
  16252. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16253. // "Never Trust", for everything or for SSL
  16254. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16255. ssl_trust_settings_result(
  16256. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16257. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16258. ssl_trust_settings_result(
  16259. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16260. // Trusted for another policy, for one host, or not at all
  16261. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16262. ssl_trust_settings_result(
  16263. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16264. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16265. ssl_trust_settings_result({make_usage_constraint(
  16266. ssl_policy, "www.example.com", &trust_root)}));
  16267. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16268. ssl_trust_settings_result(
  16269. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16270. // The first constraint that applies to SSL decides
  16271. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16272. ssl_trust_settings_result(
  16273. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16274. make_usage_constraint(nullptr, nullptr, &deny)}));
  16275. CFRelease(x509_policy);
  16276. CFRelease(ssl_policy);
  16277. }
  16278. #endif
  16279. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16280. // skip chain verification entirely (only the certificate identity was
  16281. // checked), so a server presenting an untrusted certificate with a matching
  16282. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16283. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16284. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16285. ASSERT_TRUE(svr.is_valid());
  16286. svr.Get("/test", [&](const Request &, Response &res) {
  16287. res.set_content("test", "text/plain");
  16288. });
  16289. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16290. auto se = detail::scope_exit([&] {
  16291. svr.stop();
  16292. t.join();
  16293. ASSERT_FALSE(svr.is_running());
  16294. });
  16295. svr.wait_until_ready();
  16296. SSLClient cli("127.0.0.1", PORT);
  16297. std::string cert;
  16298. // A trusted CA that did not sign the server certificate. The server cert
  16299. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16300. // this connection.
  16301. read_file(CLIENT_CA_CERT_FILE, cert);
  16302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16303. cli.enable_server_certificate_verification(true);
  16304. cli.set_connection_timeout(30);
  16305. auto res = cli.Get("/test");
  16306. ASSERT_FALSE(res);
  16307. }
  16308. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16309. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16310. // CA that failed to come through fails verification instead of trusting them.
  16311. // (wolfSSL does not list the system CAs it loaded.)
  16312. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16313. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16314. ASSERT_TRUE(svr.is_valid());
  16315. auto port = svr.bind_to_any_port("127.0.0.1");
  16316. ASSERT_LT(0, port);
  16317. thread t = thread([&] { svr.listen_after_bind(); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. });
  16323. svr.wait_until_ready();
  16324. // The CAs a client trusts once its first request has loaded them
  16325. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16326. Client cli("https://127.0.0.1:" + std::to_string(port));
  16327. setup(cli);
  16328. cli.Get("/");
  16329. return tls::get_ca_names(cli.tls_context()).size();
  16330. };
  16331. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16332. EXPECT_EQ(0u,
  16333. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16334. }
  16335. #endif
  16336. // A TLS setting changed between requests applies to the next one, not just to
  16337. // the next connection
  16338. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16339. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16340. ASSERT_TRUE(svr.is_valid());
  16341. svr.Get("/", [](const Request &req, Response &res) {
  16342. res.set_content(std::to_string(req.remote_port), "text/plain");
  16343. });
  16344. auto port = svr.bind_to_any_port("127.0.0.1");
  16345. ASSERT_LT(0, port);
  16346. thread t = thread([&] { svr.listen_after_bind(); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. t.join();
  16350. ASSERT_FALSE(svr.is_running());
  16351. });
  16352. svr.wait_until_ready();
  16353. SSLClient cli("127.0.0.1", port);
  16354. cli.set_keep_alive(true);
  16355. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16356. cli.enable_server_certificate_verification(false);
  16357. // The port the request went out from, so a new one means a new connection
  16358. auto client_port = [&] {
  16359. auto res = cli.Get("/");
  16360. return res ? res->body : std::string();
  16361. };
  16362. auto last = client_port();
  16363. ASSERT_FALSE(last.empty());
  16364. // Setting a value it already has keeps the connection
  16365. cli.enable_server_certificate_verification(false);
  16366. cli.enable_server_hostname_verification(true);
  16367. EXPECT_EQ(last, client_port());
  16368. cli.enable_server_certificate_verification(true);
  16369. auto res = cli.Get("/");
  16370. EXPECT_FALSE(res);
  16371. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16372. std::string ca;
  16373. read_file(SERVER_CERT2_FILE, ca);
  16374. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16375. last = client_port();
  16376. ASSERT_FALSE(last.empty());
  16377. std::vector<std::function<void()>> setters = {
  16378. [&] { cli.enable_server_hostname_verification(false); },
  16379. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16380. [&] {
  16381. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16382. },
  16383. [&] {
  16384. cli.set_server_certificate_verifier(
  16385. [](const tls::VerifyContext &) { return true; });
  16386. },
  16387. [&] {
  16388. cli.set_session_verifier(
  16389. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16390. },
  16391. };
  16392. for (const auto &setter : setters) {
  16393. setter();
  16394. auto next = client_port();
  16395. ASSERT_FALSE(next.empty());
  16396. EXPECT_NE(last, next);
  16397. last = next;
  16398. }
  16399. cli.set_session_verifier(
  16400. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16401. auto handle = cli.open_stream("GET", "/");
  16402. EXPECT_FALSE(handle.is_valid());
  16403. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16404. }
  16405. // A PEM given to create_ca_store() needs no NUL after it
  16406. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16407. std::string pem;
  16408. read_file(SERVER_CERT2_FILE, pem);
  16409. auto buf = pem + "X";
  16410. auto store = tls::create_ca_store(buf.data(), pem.size());
  16411. EXPECT_TRUE(store != nullptr);
  16412. SSLClient cli("localhost");
  16413. cli.set_ca_cert_store(store);
  16414. }
  16415. // enable_system_ca(false) prevents system CA loading entirely
  16416. TEST(SSLClientTest, DisableSystemCa_Online) {
  16417. SSLClient cli("google.com");
  16418. cli.enable_system_ca(false);
  16419. cli.enable_server_certificate_verification(true);
  16420. auto res = cli.Get("/");
  16421. ASSERT_FALSE(res);
  16422. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16423. // itself when the CA chain is empty
  16424. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16425. res.error() == Error::SSLConnection);
  16426. }
  16427. // The universal Client forwards enable_system_ca()
  16428. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16429. std::string cert;
  16430. read_file(SERVER_CERT2_FILE, cert);
  16431. Client cli("https://google.com");
  16432. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16433. cli.enable_system_ca(true);
  16434. cli.enable_server_certificate_verification(true);
  16435. auto res = cli.Get("/");
  16436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16437. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16438. }
  16439. // The system CA policy must carry over to the client created internally for
  16440. // following a cross-host HTTPS redirect
  16441. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16442. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16443. ASSERT_TRUE(svr.is_valid());
  16444. svr.Get("/index", [&](const Request &, Response &res) {
  16445. res.set_redirect("https://www.google.com/");
  16446. });
  16447. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16448. auto se = detail::scope_exit([&] {
  16449. svr.stop();
  16450. t.join();
  16451. ASSERT_FALSE(svr.is_running());
  16452. });
  16453. svr.wait_until_ready();
  16454. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16455. std::string cert;
  16456. read_file(SERVER_CERT2_FILE, cert);
  16457. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16458. cli.enable_system_ca(true);
  16459. cli.enable_server_certificate_verification(true);
  16460. cli.set_follow_location(true);
  16461. cli.set_connection_timeout(30);
  16462. // Receiving any response proves the redirect client completed the TLS
  16463. // handshake with a system-CA-signed host
  16464. auto res = cli.Get("/index");
  16465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16466. }
  16467. TEST(MultipartFormDataTest, LargeData) {
  16468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16469. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16470. const ContentReader &content_reader) {
  16471. if (req.is_multipart_form_data()) {
  16472. std::vector<FormData> items;
  16473. content_reader(
  16474. [&](const FormData &file) {
  16475. items.push_back(file);
  16476. return true;
  16477. },
  16478. [&](const char *data, size_t data_length) {
  16479. items.back().content.append(data, data_length);
  16480. return true;
  16481. });
  16482. EXPECT_TRUE(std::string(items[0].name) == "document");
  16483. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16484. EXPECT_TRUE(items[0].filename == "2MB_data");
  16485. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16486. EXPECT_TRUE(items[1].name == "hello");
  16487. EXPECT_TRUE(items[1].content == "world");
  16488. EXPECT_TRUE(items[1].filename == "");
  16489. EXPECT_TRUE(items[1].content_type == "");
  16490. } else {
  16491. std::string body;
  16492. content_reader([&](const char *data, size_t data_length) {
  16493. body.append(data, data_length);
  16494. return true;
  16495. });
  16496. }
  16497. });
  16498. auto port = svr.bind_to_any_port(HOST);
  16499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16500. auto se = detail::scope_exit([&] {
  16501. svr.stop();
  16502. t.join();
  16503. ASSERT_FALSE(svr.is_running());
  16504. });
  16505. svr.wait_until_ready();
  16506. {
  16507. std::string data(1024 * 1024 * 2, '.');
  16508. std::stringstream buffer;
  16509. buffer << data;
  16510. SSLClient cli(HOST, port);
  16511. cli.enable_server_certificate_verification(false);
  16512. UploadFormDataItems items{
  16513. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16514. {"hello", "world", "", ""},
  16515. };
  16516. auto res = cli.Post("/post", items);
  16517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16518. ASSERT_EQ(StatusCode::OK_200, res->status);
  16519. }
  16520. }
  16521. TEST(MultipartFormDataTest, DataProviderItems) {
  16522. std::random_device seed_gen;
  16523. std::mt19937 random(seed_gen());
  16524. std::string rand1;
  16525. rand1.resize(1000);
  16526. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16527. std::string rand2;
  16528. rand2.resize(3000);
  16529. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16531. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16532. const ContentReader &content_reader) {
  16533. ASSERT_FALSE(req.is_multipart_form_data());
  16534. std::string body;
  16535. content_reader([&](const char *data, size_t data_length) {
  16536. body.append(data, data_length);
  16537. return true;
  16538. });
  16539. EXPECT_EQ(body, "");
  16540. });
  16541. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16542. const ContentReader &content_reader) {
  16543. ASSERT_TRUE(req.is_multipart_form_data());
  16544. std::vector<FormData> items;
  16545. content_reader(
  16546. [&](const FormData &file) {
  16547. items.push_back(file);
  16548. return true;
  16549. },
  16550. [&](const char *data, size_t data_length) {
  16551. items.back().content.append(data, data_length);
  16552. return true;
  16553. });
  16554. ASSERT_TRUE(items.size() == 2);
  16555. EXPECT_EQ(std::string(items[0].name), "name1");
  16556. EXPECT_EQ(items[0].content, "Testing123");
  16557. EXPECT_EQ(items[0].filename, "filename1");
  16558. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16559. EXPECT_EQ(items[1].name, "name2");
  16560. EXPECT_EQ(items[1].content, "Testing456");
  16561. EXPECT_EQ(items[1].filename, "");
  16562. EXPECT_EQ(items[1].content_type, "");
  16563. });
  16564. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16565. const ContentReader &content_reader) {
  16566. ASSERT_TRUE(req.is_multipart_form_data());
  16567. std::vector<FormData> items;
  16568. content_reader(
  16569. [&](const FormData &file) {
  16570. items.push_back(file);
  16571. return true;
  16572. },
  16573. [&](const char *data, size_t data_length) {
  16574. items.back().content.append(data, data_length);
  16575. return true;
  16576. });
  16577. ASSERT_TRUE(items.size() == 2);
  16578. EXPECT_EQ(items[0].name, "name3");
  16579. EXPECT_EQ(items[0].content, rand1);
  16580. EXPECT_EQ(items[0].filename, "filename3");
  16581. EXPECT_EQ(items[0].content_type, "");
  16582. EXPECT_EQ(items[1].name, "name4");
  16583. EXPECT_EQ(items[1].content, rand2);
  16584. EXPECT_EQ(items[1].filename, "filename4");
  16585. EXPECT_EQ(items[1].content_type, "");
  16586. });
  16587. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16588. const ContentReader &content_reader) {
  16589. ASSERT_TRUE(req.is_multipart_form_data());
  16590. std::vector<FormData> items;
  16591. content_reader(
  16592. [&](const FormData &file) {
  16593. items.push_back(file);
  16594. return true;
  16595. },
  16596. [&](const char *data, size_t data_length) {
  16597. items.back().content.append(data, data_length);
  16598. return true;
  16599. });
  16600. ASSERT_TRUE(items.size() == 4);
  16601. EXPECT_EQ(std::string(items[0].name), "name1");
  16602. EXPECT_EQ(items[0].content, "Testing123");
  16603. EXPECT_EQ(items[0].filename, "filename1");
  16604. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16605. EXPECT_EQ(items[1].name, "name2");
  16606. EXPECT_EQ(items[1].content, "Testing456");
  16607. EXPECT_EQ(items[1].filename, "");
  16608. EXPECT_EQ(items[1].content_type, "");
  16609. EXPECT_EQ(items[2].name, "name3");
  16610. EXPECT_EQ(items[2].content, rand1);
  16611. EXPECT_EQ(items[2].filename, "filename3");
  16612. EXPECT_EQ(items[2].content_type, "");
  16613. EXPECT_EQ(items[3].name, "name4");
  16614. EXPECT_EQ(items[3].content, rand2);
  16615. EXPECT_EQ(items[3].filename, "filename4");
  16616. EXPECT_EQ(items[3].content_type, "");
  16617. });
  16618. auto port = svr.bind_to_any_port("localhost");
  16619. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16620. auto se = detail::scope_exit([&] {
  16621. svr.stop();
  16622. t.join();
  16623. ASSERT_FALSE(svr.is_running());
  16624. });
  16625. svr.wait_until_ready();
  16626. {
  16627. SSLClient cli("localhost", port);
  16628. cli.enable_server_certificate_verification(false);
  16629. UploadFormDataItems items{
  16630. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16631. {"name2", "Testing456", "", ""}, // not a file
  16632. };
  16633. {
  16634. auto res = cli.Post("/post-none", {}, {}, {});
  16635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16636. ASSERT_EQ(StatusCode::OK_200, res->status);
  16637. }
  16638. FormDataProviderItems providers;
  16639. {
  16640. auto res =
  16641. cli.Post("/post-items", {}, items, providers); // empty providers
  16642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16643. ASSERT_EQ(StatusCode::OK_200, res->status);
  16644. }
  16645. providers.push_back({"name3",
  16646. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16647. // test the offset is given correctly at each step
  16648. if (!offset)
  16649. sink.os.write(rand1.data(), 30);
  16650. else if (offset == 30)
  16651. sink.os.write(rand1.data() + 30, 300);
  16652. else if (offset == 330)
  16653. sink.os.write(rand1.data() + 330, 670);
  16654. else if (offset == rand1.size())
  16655. sink.done();
  16656. return true;
  16657. },
  16658. "filename3",
  16659. {}});
  16660. providers.push_back({"name4",
  16661. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16662. // test the offset is given correctly at each step
  16663. if (!offset)
  16664. sink.os.write(rand2.data(), 2000);
  16665. else if (offset == 2000)
  16666. sink.os.write(rand2.data() + 2000, 1);
  16667. else if (offset == 2001)
  16668. sink.os.write(rand2.data() + 2001, 999);
  16669. else if (offset == rand2.size())
  16670. sink.done();
  16671. return true;
  16672. },
  16673. "filename4",
  16674. {}});
  16675. {
  16676. auto res = cli.Post("/post-providers", {}, {}, providers);
  16677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16678. ASSERT_EQ(StatusCode::OK_200, res->status);
  16679. }
  16680. {
  16681. auto res = cli.Post("/post-both", {}, items, providers);
  16682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16683. ASSERT_EQ(StatusCode::OK_200, res->status);
  16684. }
  16685. }
  16686. }
  16687. TEST(MultipartFormDataTest, BadHeader) {
  16688. Server svr;
  16689. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16690. res.set_content("ok", "text/plain");
  16691. });
  16692. thread t = thread([&] { svr.listen(HOST, PORT); });
  16693. auto se = detail::scope_exit([&] {
  16694. svr.stop();
  16695. t.join();
  16696. ASSERT_FALSE(svr.is_running());
  16697. });
  16698. svr.wait_until_ready();
  16699. const std::string body =
  16700. "This is the preamble. It is to be ignored, though it\r\n"
  16701. "is a handy place for composition agents to include an\r\n"
  16702. "explanatory note to non-MIME conformant readers.\r\n"
  16703. "\r\n"
  16704. "\r\n"
  16705. "--simple boundary\r\n"
  16706. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16707. ": BAD...\r\n"
  16708. "\r\n"
  16709. "value1\r\n"
  16710. "--simple boundary\r\n"
  16711. "Content-Disposition: form-data; name=\"field2\"; "
  16712. "filename=\"example.txt\"\r\n"
  16713. "\r\n"
  16714. "value2\r\n"
  16715. "--simple boundary--\r\n"
  16716. "This is the epilogue. It is also to be ignored.\r\n";
  16717. std::string content_type =
  16718. R"(multipart/form-data; boundary="simple boundary")";
  16719. Client cli(HOST, PORT);
  16720. auto res = cli.Post("/post", body, content_type.c_str());
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16723. }
  16724. TEST(MultipartFormDataTest, WithPreamble) {
  16725. Server svr;
  16726. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16727. res.set_content("ok", "text/plain");
  16728. });
  16729. thread t = thread([&] { svr.listen(HOST, PORT); });
  16730. auto se = detail::scope_exit([&] {
  16731. svr.stop();
  16732. t.join();
  16733. ASSERT_FALSE(svr.is_running());
  16734. });
  16735. svr.wait_until_ready();
  16736. const std::string body =
  16737. "This is the preamble. It is to be ignored, though it\r\n"
  16738. "is a handy place for composition agents to include an\r\n"
  16739. "explanatory note to non-MIME conformant readers.\r\n"
  16740. "\r\n"
  16741. "\r\n"
  16742. "--simple boundary\r\n"
  16743. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16744. "\r\n"
  16745. "value1\r\n"
  16746. "--simple boundary\r\n"
  16747. "Content-Disposition: form-data; name=\"field2\"; "
  16748. "filename=\"example.txt\"\r\n"
  16749. "\r\n"
  16750. "value2\r\n"
  16751. "--simple boundary--\r\n"
  16752. "This is the epilogue. It is also to be ignored.\r\n";
  16753. std::string content_type =
  16754. R"(multipart/form-data; boundary="simple boundary")";
  16755. Client cli(HOST, PORT);
  16756. auto res = cli.Post("/post", body, content_type.c_str());
  16757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16758. EXPECT_EQ(StatusCode::OK_200, res->status);
  16759. }
  16760. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16762. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16763. const ContentReader &content_reader) {
  16764. if (req.is_multipart_form_data()) {
  16765. std::vector<FormData> items;
  16766. content_reader(
  16767. [&](const FormData &file) {
  16768. items.push_back(file);
  16769. return true;
  16770. },
  16771. [&](const char *data, size_t data_length) {
  16772. items.back().content.append(data, data_length);
  16773. return true;
  16774. });
  16775. EXPECT_TRUE(std::string(items[0].name) == "document");
  16776. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16777. EXPECT_TRUE(items[0].filename == "2MB_data");
  16778. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16779. EXPECT_TRUE(items[1].name == "hello");
  16780. EXPECT_TRUE(items[1].content == "world");
  16781. EXPECT_TRUE(items[1].filename == "");
  16782. EXPECT_TRUE(items[1].content_type == "");
  16783. } else {
  16784. std::string body;
  16785. content_reader([&](const char *data, size_t data_length) {
  16786. body.append(data, data_length);
  16787. return true;
  16788. });
  16789. }
  16790. });
  16791. auto port = svr.bind_to_any_port("localhost");
  16792. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16793. auto se = detail::scope_exit([&] {
  16794. svr.stop();
  16795. t.join();
  16796. ASSERT_FALSE(svr.is_running());
  16797. });
  16798. svr.wait_until_ready();
  16799. {
  16800. std::string data(1024 * 1024 * 2, '.');
  16801. std::stringstream buffer;
  16802. buffer << data;
  16803. SSLClient cli("localhost", port);
  16804. cli.enable_server_certificate_verification(false);
  16805. UploadFormDataItems items{
  16806. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16807. {"hello", "world", "", ""},
  16808. };
  16809. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16811. ASSERT_EQ(StatusCode::OK_200, res->status);
  16812. }
  16813. }
  16814. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16815. std::string data(1024 * 1024 * 2, '&');
  16816. std::stringstream buffer;
  16817. buffer << data;
  16818. Client cli("https://localhost:8080");
  16819. UploadFormDataItems items{
  16820. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16821. {"hello", "world", "", ""},
  16822. };
  16823. for (const char &c : " \t\r\n") {
  16824. auto res =
  16825. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16826. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16827. ASSERT_FALSE(res);
  16828. }
  16829. }
  16830. TEST(MultipartFormDataTest, PutFormData) {
  16831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16832. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16833. const ContentReader &content_reader) {
  16834. if (req.is_multipart_form_data()) {
  16835. std::vector<FormData> items;
  16836. content_reader(
  16837. [&](const FormData &file) {
  16838. items.push_back(file);
  16839. return true;
  16840. },
  16841. [&](const char *data, size_t data_length) {
  16842. items.back().content.append(data, data_length);
  16843. return true;
  16844. });
  16845. EXPECT_TRUE(std::string(items[0].name) == "document");
  16846. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16847. EXPECT_TRUE(items[0].filename == "2MB_data");
  16848. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16849. EXPECT_TRUE(items[1].name == "hello");
  16850. EXPECT_TRUE(items[1].content == "world");
  16851. EXPECT_TRUE(items[1].filename == "");
  16852. EXPECT_TRUE(items[1].content_type == "");
  16853. } else {
  16854. std::string body;
  16855. content_reader([&](const char *data, size_t data_length) {
  16856. body.append(data, data_length);
  16857. return true;
  16858. });
  16859. }
  16860. });
  16861. auto port = svr.bind_to_any_port("localhost");
  16862. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16863. auto se = detail::scope_exit([&] {
  16864. svr.stop();
  16865. t.join();
  16866. ASSERT_FALSE(svr.is_running());
  16867. });
  16868. svr.wait_until_ready();
  16869. {
  16870. std::string data(1024 * 1024 * 2, '&');
  16871. std::stringstream buffer;
  16872. buffer << data;
  16873. SSLClient cli("localhost", port);
  16874. cli.enable_server_certificate_verification(false);
  16875. UploadFormDataItems items{
  16876. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16877. {"hello", "world", "", ""},
  16878. };
  16879. auto res = cli.Put("/put", items);
  16880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16881. ASSERT_EQ(StatusCode::OK_200, res->status);
  16882. }
  16883. }
  16884. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16886. svr.Put("/put_customboundary",
  16887. [&](const Request &req, const Response & /*res*/,
  16888. const ContentReader &content_reader) {
  16889. if (req.is_multipart_form_data()) {
  16890. std::vector<FormData> items;
  16891. content_reader(
  16892. [&](const FormData &file) {
  16893. items.push_back(file);
  16894. return true;
  16895. },
  16896. [&](const char *data, size_t data_length) {
  16897. items.back().content.append(data, data_length);
  16898. return true;
  16899. });
  16900. EXPECT_TRUE(std::string(items[0].name) == "document");
  16901. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16902. EXPECT_TRUE(items[0].filename == "2MB_data");
  16903. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16904. EXPECT_TRUE(items[1].name == "hello");
  16905. EXPECT_TRUE(items[1].content == "world");
  16906. EXPECT_TRUE(items[1].filename == "");
  16907. EXPECT_TRUE(items[1].content_type == "");
  16908. } else {
  16909. std::string body;
  16910. content_reader([&](const char *data, size_t data_length) {
  16911. body.append(data, data_length);
  16912. return true;
  16913. });
  16914. }
  16915. });
  16916. auto port = svr.bind_to_any_port("localhost");
  16917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16918. auto se = detail::scope_exit([&] {
  16919. svr.stop();
  16920. t.join();
  16921. ASSERT_FALSE(svr.is_running());
  16922. });
  16923. svr.wait_until_ready();
  16924. {
  16925. std::string data(1024 * 1024 * 2, '&');
  16926. std::stringstream buffer;
  16927. buffer << data;
  16928. SSLClient cli("localhost", port);
  16929. cli.enable_server_certificate_verification(false);
  16930. UploadFormDataItems items{
  16931. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16932. {"hello", "world", "", ""},
  16933. };
  16934. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16936. ASSERT_EQ(StatusCode::OK_200, res->status);
  16937. }
  16938. }
  16939. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16940. std::string data(1024 * 1024 * 2, '&');
  16941. std::stringstream buffer;
  16942. buffer << data;
  16943. Client cli("https://localhost:8080");
  16944. cli.enable_server_certificate_verification(false);
  16945. UploadFormDataItems items{
  16946. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16947. {"hello", "world", "", ""},
  16948. };
  16949. for (const char &c : " \t\r\n") {
  16950. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16951. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16952. ASSERT_FALSE(res);
  16953. }
  16954. }
  16955. TEST(MultipartFormDataTest, AlternateFilename) {
  16956. auto handled = false;
  16957. Server svr;
  16958. svr.Post("/test", [&](const Request &req, Response &res) {
  16959. ASSERT_EQ(2u, req.form.files.size());
  16960. ASSERT_EQ(1u, req.form.fields.size());
  16961. // Test files
  16962. const auto &file1 = req.form.get_file("file1");
  16963. ASSERT_EQ("file1", file1.name);
  16964. ASSERT_EQ("A.txt", file1.filename);
  16965. ASSERT_EQ("text/plain", file1.content_type);
  16966. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16967. const auto &file2 = req.form.get_file("file2");
  16968. ASSERT_EQ("file2", file2.name);
  16969. ASSERT_EQ("a.html", file2.filename);
  16970. ASSERT_EQ("text/html", file2.content_type);
  16971. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16972. file2.content);
  16973. // Test text field
  16974. const auto &text = req.form.get_field("text");
  16975. ASSERT_EQ("text default", text);
  16976. res.set_content("ok", "text/plain");
  16977. handled = true;
  16978. });
  16979. thread t = thread([&] { svr.listen(HOST, PORT); });
  16980. auto se = detail::scope_exit([&] {
  16981. svr.stop();
  16982. t.join();
  16983. ASSERT_FALSE(svr.is_running());
  16984. ASSERT_TRUE(handled);
  16985. });
  16986. svr.wait_until_ready();
  16987. auto req = "POST /test HTTP/1.1\r\n"
  16988. "Host: localhost\r\n"
  16989. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16990. "Content-Length: 399\r\n"
  16991. "\r\n"
  16992. "----------\r\n"
  16993. "Content-Disposition: form-data; name=\"text\"\r\n"
  16994. "\r\n"
  16995. "text default\r\n"
  16996. "----------\r\n"
  16997. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16998. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16999. "Content-Type: text/plain\r\n"
  17000. "\r\n"
  17001. "Content of a.txt.\r\n"
  17002. "\r\n"
  17003. "----------\r\n"
  17004. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17005. "\"a.html\"\r\n"
  17006. "Content-Type: text/html\r\n"
  17007. "\r\n"
  17008. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17009. "\r\n"
  17010. "------------\r\n";
  17011. ASSERT_TRUE(send_request(1, req));
  17012. }
  17013. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17014. auto handled = false;
  17015. Server svr;
  17016. svr.Post("/test", [&](const Request &req, Response &res) {
  17017. // Case-insensitive "utf-8''" prefix with a long value
  17018. const auto &file = req.form.get_file("file1");
  17019. ASSERT_EQ("file1", file.name);
  17020. // 8000 chars exercises both the Content-Disposition parser and the
  17021. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17022. // Prior to the fix, std::regex_match on this header would cause O(N)
  17023. // stack recursion in libstdc++, leading to SIGSEGV.
  17024. std::string expected_filename(8000, 'A');
  17025. ASSERT_EQ(expected_filename, file.filename);
  17026. res.set_content("ok", "text/plain");
  17027. handled = true;
  17028. });
  17029. thread t = thread([&] { svr.listen(HOST, PORT); });
  17030. auto se = detail::scope_exit([&] {
  17031. svr.stop();
  17032. t.join();
  17033. ASSERT_FALSE(svr.is_running());
  17034. ASSERT_TRUE(handled);
  17035. });
  17036. svr.wait_until_ready();
  17037. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17038. // Regression test for GHSA-qq6v-r583-3h69
  17039. std::string long_filename(8000, 'A');
  17040. std::string body = "----------\r\n"
  17041. "Content-Disposition: form-data; name=\"file1\"; "
  17042. "filename*=\"Utf-8''" +
  17043. long_filename +
  17044. "\"\r\n"
  17045. "\r\n"
  17046. "hello\r\n"
  17047. "------------\r\n";
  17048. auto req = "POST /test HTTP/1.1\r\n"
  17049. "Host: localhost\r\n"
  17050. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17051. "Content-Length: " +
  17052. std::to_string(body.size()) + "\r\n\r\n" + body;
  17053. ASSERT_TRUE(send_request(1, req));
  17054. }
  17055. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17056. auto handled = false;
  17057. Server svr;
  17058. svr.Post("/test", [&](const Request &req, Response &) {
  17059. ASSERT_EQ(2u, req.form.fields.size());
  17060. const auto &text1 = req.form.get_field("text1");
  17061. ASSERT_EQ("text1", text1);
  17062. const auto &text2 = req.form.get_field("text2");
  17063. ASSERT_EQ("text2", text2);
  17064. handled = true;
  17065. });
  17066. thread t = thread([&] { svr.listen(HOST, PORT); });
  17067. auto se = detail::scope_exit([&] {
  17068. svr.stop();
  17069. t.join();
  17070. ASSERT_FALSE(svr.is_running());
  17071. ASSERT_TRUE(handled);
  17072. });
  17073. svr.wait_until_ready();
  17074. auto req = "POST /test HTTP/1.1\r\n"
  17075. "Host: localhost\r\n"
  17076. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17077. "Content-Length: 146\r\n"
  17078. "\r\n----------\r\n"
  17079. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17080. "\r\n"
  17081. "text1"
  17082. "\r\n----------\r\n"
  17083. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17084. "\r\n"
  17085. "text2"
  17086. "\r\n------------";
  17087. std::string response;
  17088. ASSERT_TRUE(send_request(1, req, &response));
  17089. ASSERT_EQ("200", response.substr(9, 3));
  17090. }
  17091. TEST(MultipartFormDataTest, ContentLength) {
  17092. auto handled = false;
  17093. Server svr;
  17094. svr.Post("/test", [&](const Request &req, Response &) {
  17095. ASSERT_EQ(2u, req.form.fields.size());
  17096. const auto &text1 = req.form.get_field("text1");
  17097. ASSERT_EQ("text1", text1);
  17098. const auto &text2 = req.form.get_field("text2");
  17099. ASSERT_EQ("text2", text2);
  17100. handled = true;
  17101. });
  17102. thread t = thread([&] { svr.listen(HOST, PORT); });
  17103. auto se = detail::scope_exit([&] {
  17104. svr.stop();
  17105. t.join();
  17106. ASSERT_FALSE(svr.is_running());
  17107. ASSERT_TRUE(handled);
  17108. });
  17109. svr.wait_until_ready();
  17110. auto req = "POST /test HTTP/1.1\r\n"
  17111. "Host: localhost\r\n"
  17112. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17113. "Content-Length: 167\r\n"
  17114. "\r\n----------\r\n"
  17115. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17116. "Content-Length: 5\r\n"
  17117. "\r\n"
  17118. "text1"
  17119. "\r\n----------\r\n"
  17120. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17121. "\r\n"
  17122. "text2"
  17123. "\r\n------------\r\n";
  17124. std::string response;
  17125. ASSERT_TRUE(send_request(1, req, &response));
  17126. ASSERT_EQ("200", response.substr(9, 3));
  17127. }
  17128. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17129. auto handled = false;
  17130. Server svr;
  17131. svr.Post("/test", [&](const Request &req, Response &) {
  17132. ASSERT_EQ(2u, req.form.fields.size());
  17133. const auto &text1 = req.form.get_field("text1");
  17134. ASSERT_EQ("text1", text1);
  17135. // TODO: Add header access for text fields if needed
  17136. const auto &text2 = req.form.get_field("text2");
  17137. ASSERT_EQ("text2", text2);
  17138. // TODO: Header access for text fields needs to be implemented
  17139. // auto &headers = it->second.headers;
  17140. // ASSERT_EQ(3U, headers.size());
  17141. // auto custom_header = headers.find("x-whatever");
  17142. // ASSERT_TRUE(custom_header != headers.end());
  17143. // ASSERT_NE("customvalue", custom_header->second);
  17144. // ASSERT_EQ("CustomValue", custom_header->second);
  17145. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17146. handled = true;
  17147. });
  17148. thread t = thread([&] { svr.listen(HOST, PORT); });
  17149. auto se = detail::scope_exit([&] {
  17150. svr.stop();
  17151. t.join();
  17152. ASSERT_FALSE(svr.is_running());
  17153. ASSERT_TRUE(handled);
  17154. });
  17155. svr.wait_until_ready();
  17156. auto req = "POST /test HTTP/1.1\r\n"
  17157. "Host: localhost\r\n"
  17158. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17159. "Content-Length: 232\r\n"
  17160. "\r\n----------\r\n"
  17161. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17162. "Content-Length: 5\r\n"
  17163. "X-Test: 1\r\n"
  17164. "\r\n"
  17165. "text1"
  17166. "\r\n----------\r\n"
  17167. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17168. "Content-Type: text/plain\r\n"
  17169. "X-Whatever: CustomValue\r\n"
  17170. "\r\n"
  17171. "text2"
  17172. "\r\n------------\r\n"
  17173. "That should be disregarded. Not even read";
  17174. std::string response;
  17175. ASSERT_TRUE(send_request(1, req, &response));
  17176. ASSERT_EQ("200", response.substr(9, 3));
  17177. }
  17178. TEST(MultipartFormDataTest, LargeHeader) {
  17179. auto handled = false;
  17180. Server svr;
  17181. svr.Post("/test", [&](const Request &req, Response &) {
  17182. ASSERT_EQ(1u, req.form.fields.size());
  17183. const auto &text = req.form.get_field("name1");
  17184. ASSERT_EQ("text1", text);
  17185. handled = true;
  17186. });
  17187. thread t = thread([&] { svr.listen(HOST, PORT); });
  17188. auto se = detail::scope_exit([&] {
  17189. svr.stop();
  17190. t.join();
  17191. ASSERT_FALSE(svr.is_running());
  17192. ASSERT_TRUE(handled);
  17193. });
  17194. svr.wait_until_ready();
  17195. auto boundary = std::string("cpp-httplib-multipart-data");
  17196. std::string content = "--" + boundary +
  17197. "\r\n"
  17198. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17199. "\r\n"
  17200. "text1\r\n"
  17201. "--" +
  17202. boundary + "--\r\n";
  17203. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17204. "Host: localhost\r\n"
  17205. "Content-Type: multipart/form-data;boundary=" +
  17206. boundary +
  17207. "\r\n"
  17208. "Content-Length: " +
  17209. std::to_string(content.size()) +
  17210. "\r\n"
  17211. "Dummy-Header: ";
  17212. std::string header_suffix = "\r\n"
  17213. "\r\n";
  17214. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17215. size_t header_dummy_size =
  17216. read_buff_size -
  17217. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17218. auto header_dummy = std::string(header_dummy_size, '@');
  17219. auto req = header_prefix + header_dummy + header_suffix + content;
  17220. std::string response;
  17221. ASSERT_TRUE(send_request(1, req, &response));
  17222. ASSERT_EQ("200", response.substr(9, 3));
  17223. }
  17224. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17225. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17226. // (not chunked Transfer-Encoding) after the streaming refactor.
  17227. auto handled = false;
  17228. Server svr;
  17229. svr.Post("/upload", [&](const Request &req, Response &res) {
  17230. auto cl_it = req.headers.find("Content-Length");
  17231. EXPECT_TRUE(cl_it != req.headers.end());
  17232. auto te_it = req.headers.find("Transfer-Encoding");
  17233. EXPECT_TRUE(te_it == req.headers.end());
  17234. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17235. res.set_content("ok", "text/plain");
  17236. handled = true;
  17237. });
  17238. auto port = svr.bind_to_any_port(HOST);
  17239. auto t = thread([&] { svr.listen_after_bind(); });
  17240. auto se = detail::scope_exit([&] {
  17241. svr.stop();
  17242. t.join();
  17243. ASSERT_FALSE(svr.is_running());
  17244. ASSERT_TRUE(handled);
  17245. });
  17246. svr.wait_until_ready();
  17247. UploadFormDataItems items = {
  17248. {"field1", "hello", "", "text/plain"},
  17249. {"file1", "world", "test.txt", "application/octet-stream"},
  17250. };
  17251. Client cli(HOST, port);
  17252. auto res = cli.Post("/upload", {}, items);
  17253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17254. EXPECT_EQ(StatusCode::OK_200, res->status);
  17255. }
  17256. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17257. // Verify that make_multipart_content_provider coalesces many small segments
  17258. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17259. constexpr size_t kItemCount = 1000;
  17260. UploadFormDataItems items;
  17261. items.reserve(kItemCount);
  17262. for (size_t i = 0; i < kItemCount; i++) {
  17263. items.push_back(
  17264. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17265. }
  17266. const std::string boundary = "----test-boundary";
  17267. auto content_length = detail::get_multipart_content_length(items, boundary);
  17268. auto provider = detail::make_multipart_content_provider(items, boundary);
  17269. // Drive the provider the same way write_content_with_progress does
  17270. size_t write_count = 0;
  17271. size_t total_bytes = 0;
  17272. DataSink sink;
  17273. size_t offset = 0;
  17274. sink.write = [&](const char *d, size_t l) -> bool {
  17275. (void)d;
  17276. write_count++;
  17277. total_bytes += l;
  17278. offset += l;
  17279. return true;
  17280. };
  17281. sink.is_writable = []() -> bool { return true; };
  17282. while (offset < content_length) {
  17283. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17284. }
  17285. EXPECT_EQ(content_length, total_bytes);
  17286. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17287. // With buffering into 64KB blocks, write_count should be much smaller.
  17288. auto segment_count = 3 * kItemCount + 1;
  17289. EXPECT_LT(write_count, segment_count / 10);
  17290. }
  17291. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17292. // Integration test: send many UploadFormDataItems and verify the server
  17293. // receives all of them correctly (#2410).
  17294. constexpr size_t kItemCount = 500;
  17295. auto handled = false;
  17296. Server svr;
  17297. svr.Post("/upload", [&](const Request &req, Response &res) {
  17298. EXPECT_EQ(kItemCount, req.form.fields.size());
  17299. for (size_t i = 0; i < kItemCount; i++) {
  17300. auto key = "field" + std::to_string(i);
  17301. auto val = "value" + std::to_string(i);
  17302. auto it = req.form.fields.find(key);
  17303. if (it != req.form.fields.end()) {
  17304. EXPECT_EQ(val, it->second.content);
  17305. } else {
  17306. ADD_FAILURE() << "Missing field: " << key;
  17307. }
  17308. }
  17309. res.set_content("ok", "text/plain");
  17310. handled = true;
  17311. });
  17312. auto port = svr.bind_to_any_port(HOST);
  17313. auto t = thread([&] { svr.listen_after_bind(); });
  17314. auto se = detail::scope_exit([&] {
  17315. svr.stop();
  17316. t.join();
  17317. ASSERT_FALSE(svr.is_running());
  17318. ASSERT_TRUE(handled);
  17319. });
  17320. svr.wait_until_ready();
  17321. UploadFormDataItems items;
  17322. items.reserve(kItemCount);
  17323. for (size_t i = 0; i < kItemCount; i++) {
  17324. items.push_back(
  17325. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17326. }
  17327. Client cli(HOST, port);
  17328. auto res = cli.Post("/upload", items);
  17329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17330. EXPECT_EQ(StatusCode::OK_200, res->status);
  17331. }
  17332. TEST(MultipartFormDataTest, MakeFileProvider) {
  17333. // Verify make_file_provider sends a file's contents correctly.
  17334. const std::string file_content(4096, 'Z');
  17335. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17336. {
  17337. std::ofstream ofs(tmp_path, std::ios::binary);
  17338. ofs.write(file_content.data(),
  17339. static_cast<std::streamsize>(file_content.size()));
  17340. }
  17341. auto handled = false;
  17342. Server svr;
  17343. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17344. const ContentReader &content_reader) {
  17345. ASSERT_TRUE(req.is_multipart_form_data());
  17346. std::vector<FormData> items;
  17347. content_reader(
  17348. [&](const FormData &file) {
  17349. items.push_back(file);
  17350. return true;
  17351. },
  17352. [&](const char *data, size_t data_length) {
  17353. items.back().content.append(data, data_length);
  17354. return true;
  17355. });
  17356. ASSERT_EQ(1u, items.size());
  17357. EXPECT_EQ("myfile", items[0].name);
  17358. EXPECT_EQ("data.bin", items[0].filename);
  17359. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17360. EXPECT_EQ(file_content, items[0].content);
  17361. handled = true;
  17362. });
  17363. auto port = svr.bind_to_any_port(HOST);
  17364. auto t = thread([&] { svr.listen_after_bind(); });
  17365. auto se = detail::scope_exit([&] {
  17366. svr.stop();
  17367. t.join();
  17368. ASSERT_FALSE(svr.is_running());
  17369. ASSERT_TRUE(handled);
  17370. std::remove(tmp_path.c_str());
  17371. });
  17372. svr.wait_until_ready();
  17373. FormDataProviderItems providers;
  17374. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17375. "application/octet-stream"));
  17376. Client cli(HOST, port);
  17377. auto res = cli.Post("/upload", {}, {}, providers);
  17378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17379. EXPECT_EQ(StatusCode::OK_200, res->status);
  17380. }
  17381. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17382. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17383. // (100) headers is rejected with a 400 Bad Request response.
  17384. Server svr;
  17385. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17386. res.set_content("ok", "text/plain");
  17387. });
  17388. thread t = thread([&] { svr.listen(HOST, PORT); });
  17389. auto se = detail::scope_exit([&] {
  17390. svr.stop();
  17391. t.join();
  17392. ASSERT_FALSE(svr.is_running());
  17393. });
  17394. svr.wait_until_ready();
  17395. // Build a multipart part with 101 custom headers (exceeding
  17396. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17397. std::stringstream body;
  17398. body << "--simpleboundary\r\n"
  17399. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17400. for (int i = 0; i < 101; i++) {
  17401. body << "X-Custom-Header-" << i << ": value\r\n";
  17402. }
  17403. body << "\r\n"
  17404. << "value1\r\n"
  17405. << "--simpleboundary--\r\n";
  17406. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17407. Client cli(HOST, PORT);
  17408. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17410. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17411. }
  17412. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17413. // A body that never contains the declared boundary must not be accumulated
  17414. // while the parser waits for it. Buffering it would also make every read
  17415. // rescan everything seen so far, which is quadratic in the body size.
  17416. Server svr;
  17417. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17418. res.set_content("ok", "text/plain");
  17419. });
  17420. auto port = svr.bind_to_any_port(HOST);
  17421. thread t = thread([&] { svr.listen_after_bind(); });
  17422. auto se = detail::scope_exit([&] {
  17423. svr.stop();
  17424. t.join();
  17425. ASSERT_FALSE(svr.is_running());
  17426. });
  17427. svr.wait_until_ready();
  17428. Client cli(HOST, port);
  17429. cli.set_read_timeout(60, 0);
  17430. cli.set_write_timeout(60, 0);
  17431. // '-' is the worst case: it matches the first character of the boundary, so
  17432. // every position has to be checked against it.
  17433. auto post_dashes = [&](size_t size) {
  17434. const std::string body(size, '-');
  17435. auto start = std::chrono::steady_clock::now();
  17436. auto res =
  17437. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17438. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17439. std::chrono::steady_clock::now() - start)
  17440. .count();
  17441. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17442. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17443. return ms;
  17444. };
  17445. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17446. // Windows.
  17447. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17448. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17449. // Comparing the two sizes rather than checking an absolute duration keeps
  17450. // this meaningful across build types and CI load, both of which move the
  17451. // absolute numbers by more than an order of magnitude. Four times the bytes
  17452. // costs about four times the time when parsing is linear, and about sixteen
  17453. // times when the body is buffered and rescanned.
  17454. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17455. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17456. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17457. << "ms, which suggests the body is being buffered and rescanned";
  17458. }
  17459. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17460. // A boundary can only be followed by CRLF or by "--", so anything else is
  17461. // malformed no matter what comes next. The parser must say so right away
  17462. // instead of buffering the rest of the declared body.
  17463. Server svr;
  17464. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17465. res.set_content("ok", "text/plain");
  17466. });
  17467. auto port = svr.bind_to_any_port(HOST);
  17468. thread t = thread([&] { svr.listen_after_bind(); });
  17469. auto se = detail::scope_exit([&] {
  17470. svr.stop();
  17471. t.join();
  17472. ASSERT_FALSE(svr.is_running());
  17473. });
  17474. svr.wait_until_ready();
  17475. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17476. // buffers instead of failing would still be waiting for the remaining bytes.
  17477. const std::string body = "--zzzz\r\n"
  17478. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17479. "\r\n"
  17480. "text1"
  17481. "\r\n--zzzzXX";
  17482. const std::string req = "POST /post HTTP/1.1\r\n"
  17483. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17484. "Content-Length: 1048576\r\n"
  17485. "\r\n" +
  17486. body;
  17487. std::string response;
  17488. ASSERT_TRUE(send_request(3, req, &response, port));
  17489. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17490. EXPECT_EQ("400", response.substr(9, 3));
  17491. }
  17492. // Posts a multipart body split into two writes, so that the server sees the
  17493. // split at whatever offset the caller chose, and expects the single "text1"
  17494. // field to come through.
  17495. static void expect_split_multipart_ok(const std::string &body1,
  17496. const std::string &body2) {
  17497. auto handled = false;
  17498. Server svr;
  17499. svr.Post("/post", [&](const Request &req, Response &) {
  17500. EXPECT_EQ(1u, req.form.fields.size());
  17501. EXPECT_EQ("text1", req.form.get_field("text1"));
  17502. handled = true;
  17503. });
  17504. auto port = svr.bind_to_any_port(HOST);
  17505. thread t = thread([&] { svr.listen_after_bind(); });
  17506. auto se = detail::scope_exit([&] {
  17507. svr.stop();
  17508. t.join();
  17509. ASSERT_FALSE(svr.is_running());
  17510. ASSERT_TRUE(handled);
  17511. });
  17512. svr.wait_until_ready();
  17513. // "Connection: close" makes the server close once it has answered, so the
  17514. // response drain ends immediately instead of idling until the read timeout.
  17515. const std::string head =
  17516. "POST /post HTTP/1.1\r\n"
  17517. "Host: localhost\r\n"
  17518. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17519. "Connection: close\r\n"
  17520. "Content-Length: " +
  17521. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17522. std::string response;
  17523. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17524. ASSERT_GE(response.size(), 12u) << "no response";
  17525. EXPECT_EQ("200", response.substr(9, 3));
  17526. }
  17527. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17528. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17529. // ignored, including when it does not arrive in the same read as the
  17530. // close-delimiter itself.
  17531. expect_split_multipart_ok("--zzzz\r\n"
  17532. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17533. "\r\n"
  17534. "text1"
  17535. "\r\n--zzzz--",
  17536. "\r\nthis epilogue must be ignored\r\n");
  17537. }
  17538. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17539. // The initial boundary may be preceded by a preamble of any length and may
  17540. // straddle a read boundary. Discarding data while waiting for it must not
  17541. // throw away a partial boundary sitting at the end of the buffer.
  17542. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17543. "zz\r\n"
  17544. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17545. "\r\n"
  17546. "text1"
  17547. "\r\n--zzzz--\r\n");
  17548. }
  17549. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17550. // The received boundary was only checked for being non-empty, so it could be
  17551. // as long as a header is allowed to be. The parser scans the body for
  17552. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17553. // costs a nearly full comparison at nearly every position, making the
  17554. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17555. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17556. Server svr;
  17557. svr.Post("/post", [](const Request &req, Response &res) {
  17558. EXPECT_EQ(1u, req.form.fields.size());
  17559. EXPECT_EQ("text1", req.form.get_field("text1"));
  17560. res.set_content("ok", "text/plain");
  17561. });
  17562. auto port = svr.bind_to_any_port(HOST);
  17563. thread t = thread([&] { svr.listen_after_bind(); });
  17564. auto se = detail::scope_exit([&] {
  17565. svr.stop();
  17566. t.join();
  17567. ASSERT_FALSE(svr.is_running());
  17568. });
  17569. svr.wait_until_ready();
  17570. Client cli(HOST, port);
  17571. auto post_with_boundary_of_length = [&](size_t len) {
  17572. const std::string boundary(len, 'a');
  17573. const std::string body =
  17574. "--" + boundary +
  17575. "\r\n"
  17576. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17577. "\r\n"
  17578. "text1"
  17579. "\r\n--" +
  17580. boundary + "--\r\n";
  17581. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17582. };
  17583. auto res = post_with_boundary_of_length(70);
  17584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17585. EXPECT_EQ(StatusCode::OK_200, res->status);
  17586. res = post_with_boundary_of_length(71);
  17587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17588. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17589. }
  17590. TEST(MakeFileBodyTest, Basic) {
  17591. const std::string file_content(4096, 'Z');
  17592. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17593. {
  17594. std::ofstream ofs(tmp_path, std::ios::binary);
  17595. ofs.write(file_content.data(),
  17596. static_cast<std::streamsize>(file_content.size()));
  17597. }
  17598. auto handled = false;
  17599. Server svr;
  17600. svr.Post("/upload", [&](const Request &req, Response &res) {
  17601. EXPECT_EQ(file_content, req.body);
  17602. handled = true;
  17603. res.status = StatusCode::OK_200;
  17604. });
  17605. auto port = svr.bind_to_any_port(HOST);
  17606. auto t = thread([&] { svr.listen_after_bind(); });
  17607. auto se = detail::scope_exit([&] {
  17608. svr.stop();
  17609. t.join();
  17610. ASSERT_FALSE(svr.is_running());
  17611. ASSERT_TRUE(handled);
  17612. std::remove(tmp_path.c_str());
  17613. });
  17614. svr.wait_until_ready();
  17615. auto fb = make_file_body(tmp_path);
  17616. ASSERT_GT(fb.first, 0u);
  17617. Client cli(HOST, port);
  17618. auto res =
  17619. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17621. EXPECT_EQ(StatusCode::OK_200, res->status);
  17622. }
  17623. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17624. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17625. {
  17626. std::ofstream ofs(path, std::ios::binary);
  17627. const std::string content(100, 'A');
  17628. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17629. }
  17630. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17631. auto body = make_file_body(path);
  17632. ASSERT_EQ(100u, body.first);
  17633. ASSERT_TRUE(static_cast<bool>(body.second));
  17634. // Rewritten shorter after its length was measured - and, on a server, after
  17635. // that length has already gone out as Content-Length.
  17636. {
  17637. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17638. const std::string content(10, 'A');
  17639. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17640. }
  17641. std::string written;
  17642. DataSink sink;
  17643. sink.write = [&](const char *d, size_t l) {
  17644. written.append(d, l);
  17645. return true;
  17646. };
  17647. // The provider has to report failure. write_content_with_progress() advances
  17648. // its offset only by what was written, so a provider that returns true
  17649. // without completing the length it promised is called again straight away,
  17650. // and again.
  17651. EXPECT_FALSE(body.second(0, body.first, sink));
  17652. EXPECT_EQ(std::string(10, 'A'), written);
  17653. }
  17654. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17655. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17656. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17657. {
  17658. std::ofstream ofs(path, std::ios::binary);
  17659. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17660. }
  17661. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17662. auto body = make_file_body(path);
  17663. ASSERT_EQ(content.size(), body.first);
  17664. ASSERT_TRUE(static_cast<bool>(body.second));
  17665. std::string written;
  17666. DataSink sink;
  17667. sink.write = [&](const char *d, size_t l) {
  17668. written.append(d, l);
  17669. return true;
  17670. };
  17671. EXPECT_TRUE(body.second(0, body.first, sink));
  17672. EXPECT_EQ(content, written);
  17673. }
  17674. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17675. static constexpr unsigned int number_of_tasks{1000000};
  17676. std::atomic_uint count{0};
  17677. std::unique_ptr<TaskQueue> task_queue{
  17678. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17679. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17680. auto queued = task_queue->enqueue(
  17681. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17682. EXPECT_TRUE(queued);
  17683. }
  17684. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17685. task_queue->shutdown();
  17686. #else
  17687. EXPECT_NO_THROW(task_queue->shutdown());
  17688. #endif
  17689. EXPECT_EQ(number_of_tasks, count.load());
  17690. }
  17691. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17692. static constexpr unsigned int number_of_tasks{1000000};
  17693. static constexpr unsigned int qlimit{2};
  17694. unsigned int queued_count{0};
  17695. std::atomic_uint count{0};
  17696. std::unique_ptr<TaskQueue> task_queue{
  17697. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17698. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17699. if (task_queue->enqueue(
  17700. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17701. queued_count++;
  17702. }
  17703. }
  17704. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17705. task_queue->shutdown();
  17706. #else
  17707. EXPECT_NO_THROW(task_queue->shutdown());
  17708. #endif
  17709. EXPECT_EQ(queued_count, count.load());
  17710. EXPECT_TRUE(queued_count <= number_of_tasks);
  17711. EXPECT_TRUE(queued_count >= qlimit);
  17712. }
  17713. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17714. // Use a short idle timeout so a dynamic thread spawns, times out and
  17715. // exits during the test, and the pool keeps working afterwards.
  17716. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17717. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17718. /*idle_timeout_sec=*/1}};
  17719. std::atomic_uint count{0};
  17720. std::condition_variable cv;
  17721. std::mutex mtx;
  17722. bool release = false;
  17723. // Block the base thread so the second task spawns a dynamic thread.
  17724. EXPECT_TRUE(task_queue->enqueue([&] {
  17725. std::unique_lock<std::mutex> lock(mtx);
  17726. while (!release) {
  17727. cv.wait(lock);
  17728. }
  17729. count++;
  17730. }));
  17731. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17732. // Let the dynamic thread finish its task and exceed the idle timeout.
  17733. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17734. {
  17735. std::unique_lock<std::mutex> lock(mtx);
  17736. release = true;
  17737. }
  17738. cv.notify_all();
  17739. // The pool must still accept and run tasks after the dynamic thread exited.
  17740. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17741. task_queue->shutdown();
  17742. EXPECT_EQ(3u, count.load());
  17743. }
  17744. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17745. static constexpr size_t number_of_tasks{32};
  17746. std::unique_ptr<TaskQueue> task_queue{
  17747. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17748. // Let the base threads go idle so the burst below finds them waiting.
  17749. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17750. std::mutex mtx;
  17751. std::condition_variable cv;
  17752. size_t running = 0;
  17753. bool release = false;
  17754. for (size_t i = 0; i < number_of_tasks; i++) {
  17755. EXPECT_TRUE(task_queue->enqueue([&] {
  17756. std::unique_lock<std::mutex> lock(mtx);
  17757. running++;
  17758. cv.notify_all();
  17759. cv.wait(lock, [&] { return release; });
  17760. }));
  17761. }
  17762. {
  17763. std::unique_lock<std::mutex> lock(mtx);
  17764. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17765. [&] { return running == number_of_tasks; }));
  17766. release = true;
  17767. }
  17768. cv.notify_all();
  17769. task_queue->shutdown();
  17770. }
  17771. TEST(TaskQueueTest, MaxQueuedRequests) {
  17772. static constexpr unsigned int qlimit{3};
  17773. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17774. std::condition_variable sem_cv;
  17775. std::mutex sem_mtx;
  17776. int credits = 0;
  17777. bool queued;
  17778. /* Fill up the queue with tasks that will block until we give them credits to
  17779. * complete. */
  17780. for (unsigned int n = 0; n <= qlimit;) {
  17781. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17782. std::unique_lock<std::mutex> lock(sem_mtx);
  17783. while (credits <= 0) {
  17784. sem_cv.wait(lock);
  17785. }
  17786. /* Consume the credit and signal the test code if they are all gone. */
  17787. if (--credits == 0) { sem_cv.notify_one(); }
  17788. });
  17789. if (n < qlimit) {
  17790. /* The first qlimit enqueues must succeed. */
  17791. EXPECT_TRUE(queued);
  17792. } else {
  17793. /* The last one will succeed only when the worker thread
  17794. * starts and dequeues the first blocking task. Although
  17795. * not necessary for the correctness of this test, we sleep for
  17796. * a short while to avoid busy waiting. */
  17797. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17798. }
  17799. if (queued) { n++; }
  17800. }
  17801. /* Further enqueues must fail since the queue is full. */
  17802. for (auto i = 0; i < 4; i++) {
  17803. queued = task_queue->enqueue([] {});
  17804. EXPECT_FALSE(queued);
  17805. }
  17806. /* Give the credits to allow the previous tasks to complete. */
  17807. {
  17808. std::unique_lock<std::mutex> lock(sem_mtx);
  17809. credits += qlimit + 1;
  17810. }
  17811. sem_cv.notify_all();
  17812. /* Wait for all the credits to be consumed. */
  17813. {
  17814. std::unique_lock<std::mutex> lock(sem_mtx);
  17815. while (credits > 0) {
  17816. sem_cv.wait(lock);
  17817. }
  17818. }
  17819. /* Check that we are able again to enqueue at least qlimit tasks. */
  17820. for (unsigned int i = 0; i < qlimit; i++) {
  17821. queued = task_queue->enqueue([] {});
  17822. EXPECT_TRUE(queued);
  17823. }
  17824. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17825. task_queue->shutdown();
  17826. #else
  17827. EXPECT_NO_THROW(task_queue->shutdown());
  17828. #endif
  17829. }
  17830. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17831. Server svr;
  17832. std::string method;
  17833. std::string body;
  17834. auto has_content_length = false;
  17835. auto has_transfer_encoding = false;
  17836. std::atomic<int> bad_requests{0};
  17837. // Leftover body bytes get parsed as a malformed request and answered with
  17838. // 400
  17839. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17840. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17841. });
  17842. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17843. res.set_redirect("/down", StatusCode::SeeOther_303);
  17844. });
  17845. svr.Get("/down", [&](const Request &req, Response &res) {
  17846. method = req.method;
  17847. body = req.body;
  17848. has_content_length = req.has_header("Content-Length");
  17849. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17850. res.set_content("ok", "text/plain");
  17851. });
  17852. auto port = svr.bind_to_any_port(HOST);
  17853. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17854. auto se = detail::scope_exit([&] {
  17855. svr.stop();
  17856. thread.join();
  17857. ASSERT_FALSE(svr.is_running());
  17858. });
  17859. svr.wait_until_ready();
  17860. const std::string payload = "SECRET-BODY";
  17861. auto check = [&](Client &cli, const Result &res) {
  17862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17863. EXPECT_EQ(StatusCode::OK_200, res->status);
  17864. EXPECT_EQ("ok", res->body);
  17865. EXPECT_EQ("GET", method);
  17866. EXPECT_TRUE(body.empty());
  17867. EXPECT_FALSE(has_content_length);
  17868. EXPECT_FALSE(has_transfer_encoding);
  17869. // Nothing of the original body may be left on the connection
  17870. auto res2 = cli.Get("/down");
  17871. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17872. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17873. EXPECT_EQ("ok", res2->body);
  17874. EXPECT_EQ(0, bad_requests);
  17875. };
  17876. // With content length
  17877. {
  17878. Client cli(HOST, port);
  17879. cli.set_keep_alive(true);
  17880. cli.set_follow_location(true);
  17881. auto res = cli.Post(
  17882. "/up", payload.size(),
  17883. [&](size_t offset, size_t length, DataSink &sink) {
  17884. return sink.write(payload.data() + offset, length);
  17885. },
  17886. "text/plain");
  17887. check(cli, res);
  17888. }
  17889. // Without content length (chunked)
  17890. {
  17891. Client cli(HOST, port);
  17892. cli.set_keep_alive(true);
  17893. cli.set_follow_location(true);
  17894. auto res = cli.Post(
  17895. "/up",
  17896. [&](size_t /*offset*/, DataSink &sink) {
  17897. sink.write(payload.data(), payload.size());
  17898. sink.done();
  17899. return true;
  17900. },
  17901. "text/plain");
  17902. check(cli, res);
  17903. }
  17904. }
  17905. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17906. Server svr;
  17907. std::string target;
  17908. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17909. // Echo the still-encoded name back in the Location
  17910. const std::string prefix = "/start/";
  17911. res.status = StatusCode::Found_302;
  17912. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17913. });
  17914. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17915. target = req.target;
  17916. res.set_content("ok", "text/plain");
  17917. });
  17918. auto port = svr.bind_to_any_port(HOST);
  17919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17920. auto se = detail::scope_exit([&] {
  17921. svr.stop();
  17922. thread.join();
  17923. ASSERT_FALSE(svr.is_running());
  17924. });
  17925. svr.wait_until_ready();
  17926. // Decoding the Location path would turn the first four into a path
  17927. // separator, a query delimiter, a fragment delimiter and a different
  17928. // percent-encoded octet. The rest must keep reaching the server as they are.
  17929. const std::vector<std::string> names = {
  17930. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17931. };
  17932. for (auto path_encode : {true, false}) {
  17933. Client cli(HOST, port);
  17934. cli.set_follow_location(true);
  17935. cli.set_path_encode(path_encode);
  17936. for (const auto &name : names) {
  17937. target.clear();
  17938. auto res = cli.Get("/start/" + name);
  17939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17940. EXPECT_EQ(StatusCode::OK_200, res->status);
  17941. EXPECT_EQ("/dest/" + name, target);
  17942. }
  17943. }
  17944. }
  17945. TEST(RedirectTest, NotModifiedIsReturned) {
  17946. Server svr;
  17947. svr.Get("/cached", [](const Request &, Response &res) {
  17948. res.status = StatusCode::NotModified_304;
  17949. });
  17950. auto port = svr.bind_to_any_port(HOST);
  17951. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17952. auto se = detail::scope_exit([&] {
  17953. svr.stop();
  17954. thread.join();
  17955. ASSERT_FALSE(svr.is_running());
  17956. });
  17957. svr.wait_until_ready();
  17958. Client cli(HOST, port);
  17959. cli.set_follow_location(true);
  17960. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17962. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17963. }
  17964. TEST(RedirectTest, NoLocationIsReturned) {
  17965. Server svr;
  17966. svr.Get("/no-location", [](const Request &, Response &res) {
  17967. res.status = StatusCode::Found_302;
  17968. res.set_content("no location", "text/plain");
  17969. });
  17970. auto port = svr.bind_to_any_port(HOST);
  17971. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17972. auto se = detail::scope_exit([&] {
  17973. svr.stop();
  17974. thread.join();
  17975. ASSERT_FALSE(svr.is_running());
  17976. });
  17977. svr.wait_until_ready();
  17978. Client cli(HOST, port);
  17979. cli.set_follow_location(true);
  17980. auto res = cli.Get("/no-location");
  17981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17982. EXPECT_EQ(StatusCode::Found_302, res->status);
  17983. EXPECT_EQ("no location", res->body);
  17984. // The callbacks see the body of the response that is returned
  17985. auto handler_called = false;
  17986. auto progress_called = false;
  17987. std::string body;
  17988. auto res2 = cli.Get(
  17989. "/no-location",
  17990. [&](const Response &) {
  17991. handler_called = true;
  17992. return true;
  17993. },
  17994. [&](const char *data, size_t data_length) {
  17995. body.append(data, data_length);
  17996. return true;
  17997. },
  17998. [&](size_t, size_t) {
  17999. progress_called = true;
  18000. return true;
  18001. });
  18002. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18003. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18004. EXPECT_TRUE(handler_called);
  18005. EXPECT_TRUE(progress_called);
  18006. EXPECT_EQ("no location", body);
  18007. }
  18008. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18009. Server svr;
  18010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18011. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18012. });
  18013. svr.Get("/hello", [](const Request &req, Response &res) {
  18014. res.set_content(req.get_param_value("key"), "text/plain");
  18015. });
  18016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18017. auto se = detail::scope_exit([&] {
  18018. svr.stop();
  18019. thread.join();
  18020. ASSERT_FALSE(svr.is_running());
  18021. });
  18022. svr.wait_until_ready();
  18023. {
  18024. Client cli(HOST, PORT);
  18025. cli.set_follow_location(true);
  18026. auto res = cli.Get("/");
  18027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18028. EXPECT_EQ(StatusCode::OK_200, res->status);
  18029. EXPECT_EQ("val&key2=val2", res->body);
  18030. }
  18031. }
  18032. #endif
  18033. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18034. Server svr;
  18035. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18036. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18037. });
  18038. svr.Get("/hello", [](const Request &req, Response &res) {
  18039. res.set_content(req.get_param_value("key"), "text/plain");
  18040. });
  18041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18042. auto se = detail::scope_exit([&] {
  18043. svr.stop();
  18044. thread.join();
  18045. ASSERT_FALSE(svr.is_running());
  18046. });
  18047. svr.wait_until_ready();
  18048. {
  18049. Client cli(HOST, PORT);
  18050. cli.set_follow_location(true);
  18051. auto res = cli.Get("/");
  18052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18053. EXPECT_EQ(StatusCode::OK_200, res->status);
  18054. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18055. }
  18056. }
  18057. TEST(RedirectTest, RedirectWithPlusInPath) {
  18058. Server svr;
  18059. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18060. res.set_redirect("/a+b");
  18061. });
  18062. // Route pattern uses regex; escape + as \\+
  18063. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18064. res.set_content(req.path, "text/plain");
  18065. });
  18066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18067. auto se = detail::scope_exit([&] {
  18068. svr.stop();
  18069. thread.join();
  18070. ASSERT_FALSE(svr.is_running());
  18071. });
  18072. svr.wait_until_ready();
  18073. {
  18074. Client cli(HOST, PORT);
  18075. cli.set_follow_location(true);
  18076. auto res = cli.Get("/");
  18077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18078. EXPECT_EQ(StatusCode::OK_200, res->status);
  18079. EXPECT_EQ("/a+b", res->body);
  18080. }
  18081. }
  18082. TEST(RedirectTest, ResolveRelativeLocation) {
  18083. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18084. const std::vector<std::pair<std::string, std::string>> cases = {
  18085. {"g", "/b/c/g"},
  18086. {"./g", "/b/c/g"},
  18087. {"g/", "/b/c/g/"},
  18088. {"?y", "/b/c/d;p?y"},
  18089. {"g?y", "/b/c/g?y"},
  18090. {"#s", "/b/c/d;p?q#s"},
  18091. {"g#s", "/b/c/g#s"},
  18092. {"g?y#s", "/b/c/g?y#s"},
  18093. {";x", "/b/c/;x"},
  18094. {"g;x", "/b/c/g;x"},
  18095. {".", "/b/c/"},
  18096. {"./", "/b/c/"},
  18097. {"..", "/b/"},
  18098. {"../", "/b/"},
  18099. {"../g", "/b/g"},
  18100. {"../..", "/"},
  18101. {"../../", "/"},
  18102. {"../../g", "/g"},
  18103. {"../../../g", "/g"},
  18104. {"g.", "/b/c/g."},
  18105. {".g", "/b/c/.g"},
  18106. {"g..", "/b/c/g.."},
  18107. {"..g", "/b/c/..g"},
  18108. {"./../g", "/b/g"},
  18109. {"./g/.", "/b/c/g/"},
  18110. {"g/./h", "/b/c/g/h"},
  18111. {"g/../h", "/b/c/h"},
  18112. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18113. {"g;x=1/../y", "/b/c/y"},
  18114. {"g?y/./x", "/b/c/g?y/./x"},
  18115. {"g#s/../x", "/b/c/g#s/../x"},
  18116. // Not relative-path references, so left for parse_url.
  18117. {"/g", "/g"},
  18118. {"//g", "//g"},
  18119. {"http://g/x", "http://g/x"},
  18120. {"g:h", "g:h"},
  18121. };
  18122. for (const auto &c : cases) {
  18123. EXPECT_EQ(c.second,
  18124. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18125. << c.first;
  18126. }
  18127. // A result starting with "//" is still a path, not a network-path reference
  18128. EXPECT_EQ("/.//g",
  18129. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18130. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18131. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18132. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18133. }
  18134. TEST(RedirectTest, RemoveDotSegments) {
  18135. // RFC 3986 section 5.2.4
  18136. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18137. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18138. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18139. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18140. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18141. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18142. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18143. }
  18144. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18145. Server svr;
  18146. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18147. res.set_redirect("/dir/../target?x=1");
  18148. });
  18149. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18150. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18151. "/dir/./../target");
  18152. });
  18153. svr.Get("/target", [](const Request &req, Response &res) {
  18154. res.set_content(req.path, "text/plain");
  18155. });
  18156. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18157. auto se = detail::scope_exit([&] {
  18158. svr.stop();
  18159. th.join();
  18160. ASSERT_FALSE(svr.is_running());
  18161. });
  18162. svr.wait_until_ready();
  18163. Client cli("localhost", PORT);
  18164. cli.set_follow_location(true);
  18165. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18166. auto res = cli.Get(path);
  18167. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18168. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18169. EXPECT_EQ("/target", res->body) << path;
  18170. }
  18171. }
  18172. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18173. Server svr;
  18174. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18175. res.set_redirect(req.get_param_value("to"));
  18176. });
  18177. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18178. res.set_content(req.target, "text/plain");
  18179. });
  18180. svr.Get("/other", [](const Request &req, Response &res) {
  18181. res.set_content(req.target, "text/plain");
  18182. });
  18183. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18184. auto se = detail::scope_exit([&] {
  18185. svr.stop();
  18186. thread.join();
  18187. ASSERT_FALSE(svr.is_running());
  18188. });
  18189. svr.wait_until_ready();
  18190. const std::vector<std::pair<std::string, std::string>> cases = {
  18191. {"next", "/dir/next"},
  18192. {"./next?x=1", "/dir/next?x=1"},
  18193. {"../other", "/other"},
  18194. };
  18195. for (const auto &c : cases) {
  18196. Client cli(HOST, PORT);
  18197. cli.set_follow_location(true);
  18198. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18199. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18200. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18201. EXPECT_EQ(c.second, res->body) << c.first;
  18202. }
  18203. }
  18204. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18205. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18206. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18207. Server other;
  18208. std::atomic<int> other_hits{0};
  18209. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18210. other_hits++;
  18211. res.set_content("other", "text/plain");
  18212. });
  18213. auto other_port = other.bind_to_any_port("127.0.0.1");
  18214. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18215. Server svr;
  18216. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18217. res.set_redirect(req.get_param_value("to"));
  18218. });
  18219. svr.Get(".*", [](const Request &req, Response &res) {
  18220. res.set_content(req.path, "text/plain");
  18221. });
  18222. auto port = svr.bind_to_any_port(HOST);
  18223. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18224. auto se = detail::scope_exit([&] {
  18225. svr.stop();
  18226. thread.join();
  18227. other.stop();
  18228. other_thread.join();
  18229. ASSERT_FALSE(svr.is_running());
  18230. ASSERT_FALSE(other.is_running());
  18231. });
  18232. svr.wait_until_ready();
  18233. other.wait_until_ready();
  18234. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18235. for (const auto &to :
  18236. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18237. Client cli(HOST, port);
  18238. cli.set_follow_location(true);
  18239. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18240. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18241. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18242. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18243. }
  18244. EXPECT_EQ(0, other_hits.load());
  18245. }
  18246. #ifdef CPPHTTPLIB_SSL_ENABLED
  18247. TEST(RedirectTest, Issue2185_Online) {
  18248. SSLClient client("github.com");
  18249. client.set_follow_location(true);
  18250. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18251. "Coollab-Windows.zip");
  18252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18253. EXPECT_EQ(StatusCode::OK_200, res->status);
  18254. EXPECT_EQ(9920427U, res->body.size());
  18255. }
  18256. #endif
  18257. TEST(VulnerabilityTest, CRLFInjection) {
  18258. Server svr;
  18259. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18260. res.set_content("Hello 1", "text/plain");
  18261. });
  18262. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18263. res.set_content("Hello 2", "text/plain");
  18264. });
  18265. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18266. res.set_content("Hello 3", "text/plain");
  18267. });
  18268. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18269. res.set_content("Hello 4", "text/plain");
  18270. });
  18271. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18272. for (const auto &x : req.headers) {
  18273. auto key = x.first;
  18274. EXPECT_STRNE("evil", key.c_str());
  18275. }
  18276. });
  18277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18278. auto se = detail::scope_exit([&] {
  18279. svr.stop();
  18280. thread.join();
  18281. ASSERT_FALSE(svr.is_running());
  18282. });
  18283. svr.wait_until_ready();
  18284. {
  18285. Client cli(HOST, PORT);
  18286. cli.Post("/test1", "A=B",
  18287. "application/x-www-form-urlencoded\r\nevil: hello1");
  18288. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18289. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18290. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18291. }
  18292. }
  18293. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18294. auto server_thread = std::thread([] {
  18295. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18296. default_socket_options(srv);
  18297. sockaddr_in addr{};
  18298. addr.sin_family = AF_INET;
  18299. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18300. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18301. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18302. ::listen(srv, 1);
  18303. sockaddr_in cli_addr{};
  18304. socklen_t cli_len = sizeof(cli_addr);
  18305. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18306. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18307. std::string buf_all;
  18308. char buf[2048];
  18309. ssize_t n;
  18310. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18311. buf_all.append(buf, static_cast<size_t>(n));
  18312. size_t pos;
  18313. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18314. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18315. auto e = request_block.find("\r\n");
  18316. if (e != std::string::npos) {
  18317. auto request_line = request_block.substr(0, e);
  18318. std::string msg =
  18319. "CRLF injection detected in request line: '" + request_line + "'";
  18320. EXPECT_FALSE(true) << msg;
  18321. }
  18322. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18323. ::send(cli,
  18324. #ifdef _WIN32
  18325. static_cast<const char *>(resp.c_str()),
  18326. static_cast<int>(resp.size()),
  18327. #else
  18328. resp.c_str(), resp.size(),
  18329. #endif
  18330. 0);
  18331. buf_all.erase(0, pos + 4);
  18332. }
  18333. }
  18334. detail::close_socket(cli);
  18335. detail::close_socket(srv);
  18336. });
  18337. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18338. auto cli = Client("127.0.0.1", PORT + 1);
  18339. auto headers = Headers{
  18340. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18341. {"Connection", "keep-alive"}};
  18342. auto res = cli.Get("/hi", headers);
  18343. EXPECT_FALSE(res);
  18344. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18345. server_thread.join();
  18346. }
  18347. // A request rejected before any byte reaches the socket must fail right away
  18348. // instead of waiting for a response the server will never send.
  18349. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18350. // The kernel completes the TCP handshake from the listen backlog, so the
  18351. // client connects, but nothing ever reads, responds or closes.
  18352. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18353. default_socket_options(srv);
  18354. sockaddr_in addr{};
  18355. addr.sin_family = AF_INET;
  18356. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18357. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18358. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18359. ASSERT_EQ(0, ::listen(srv, 8));
  18360. auto cli = Client("127.0.0.1", PORT + 1);
  18361. cli.set_read_timeout(10, 0);
  18362. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18363. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18364. std::chrono::steady_clock::now() - start)
  18365. .count();
  18366. };
  18367. {
  18368. Request req;
  18369. req.method = "GE T";
  18370. req.path = "/";
  18371. auto start = std::chrono::steady_clock::now();
  18372. auto res = cli.send(req);
  18373. EXPECT_FALSE(res);
  18374. EXPECT_EQ(Error::Write, res.error());
  18375. EXPECT_LT(elapsed_ms(start), 1000);
  18376. }
  18377. {
  18378. auto start = std::chrono::steady_clock::now();
  18379. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18380. EXPECT_FALSE(res);
  18381. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18382. EXPECT_LT(elapsed_ms(start), 1000);
  18383. }
  18384. EXPECT_FALSE(cli.is_socket_open());
  18385. detail::close_socket(srv);
  18386. }
  18387. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18388. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18389. default_socket_options(srv);
  18390. sockaddr_in addr{};
  18391. addr.sin_family = AF_INET;
  18392. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18393. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18394. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18395. ASSERT_EQ(0, ::listen(srv, 1));
  18396. std::string received;
  18397. auto server_thread = std::thread([&] {
  18398. auto sock = ::accept(srv, nullptr, nullptr);
  18399. if (sock == INVALID_SOCKET) { return; }
  18400. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18401. char buf[2048];
  18402. ssize_t n;
  18403. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18404. received.append(buf, static_cast<size_t>(n));
  18405. }
  18406. detail::close_socket(sock);
  18407. });
  18408. {
  18409. auto cli = Client("127.0.0.1", PORT + 1);
  18410. // "Z" sorts after the default headers, so writing straight to the socket
  18411. // would have sent the request line and those headers before the rejection.
  18412. auto handle =
  18413. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18414. EXPECT_FALSE(handle.is_valid());
  18415. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18416. }
  18417. server_thread.join();
  18418. detail::close_socket(srv);
  18419. EXPECT_TRUE(received.empty()) << received;
  18420. }
  18421. TEST(PathParamsTest, StaticMatch) {
  18422. const auto pattern = "/users/all";
  18423. detail::PathParamsMatcher matcher(pattern);
  18424. Request request;
  18425. request.path = "/users/all";
  18426. ASSERT_TRUE(matcher.match(request));
  18427. std::unordered_map<std::string, std::string> expected_params = {};
  18428. EXPECT_EQ(request.path_params, expected_params);
  18429. }
  18430. TEST(PathParamsTest, StaticMismatch) {
  18431. const auto pattern = "/users/all";
  18432. detail::PathParamsMatcher matcher(pattern);
  18433. Request request;
  18434. request.path = "/users/1";
  18435. ASSERT_FALSE(matcher.match(request));
  18436. }
  18437. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18438. const auto pattern = "/users/:id/subscriptions";
  18439. detail::PathParamsMatcher matcher(pattern);
  18440. Request request;
  18441. request.path = "/users/42/subscriptions";
  18442. ASSERT_TRUE(matcher.match(request));
  18443. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18444. EXPECT_EQ(request.path_params, expected_params);
  18445. }
  18446. TEST(PathParamsTest, SingleParamInTheEnd) {
  18447. const auto pattern = "/users/:id";
  18448. detail::PathParamsMatcher matcher(pattern);
  18449. Request request;
  18450. request.path = "/users/24";
  18451. ASSERT_TRUE(matcher.match(request));
  18452. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18453. EXPECT_EQ(request.path_params, expected_params);
  18454. }
  18455. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18456. const auto pattern = "/users/:id/";
  18457. detail::PathParamsMatcher matcher(pattern);
  18458. Request request;
  18459. request.path = "/users/42/";
  18460. ASSERT_TRUE(matcher.match(request));
  18461. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18462. EXPECT_EQ(request.path_params, expected_params);
  18463. }
  18464. TEST(PathParamsTest, EmptyParam) {
  18465. const auto pattern = "/users/:id/";
  18466. detail::PathParamsMatcher matcher(pattern);
  18467. Request request;
  18468. request.path = "/users//";
  18469. ASSERT_TRUE(matcher.match(request));
  18470. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18471. EXPECT_EQ(request.path_params, expected_params);
  18472. }
  18473. TEST(PathParamsTest, FragmentMismatch) {
  18474. const auto pattern = "/users/:id/";
  18475. detail::PathParamsMatcher matcher(pattern);
  18476. Request request;
  18477. request.path = "/admins/24/";
  18478. ASSERT_FALSE(matcher.match(request));
  18479. }
  18480. TEST(PathParamsTest, ExtraFragments) {
  18481. const auto pattern = "/users/:id";
  18482. detail::PathParamsMatcher matcher(pattern);
  18483. Request request;
  18484. request.path = "/users/42/subscriptions";
  18485. ASSERT_FALSE(matcher.match(request));
  18486. }
  18487. TEST(PathParamsTest, MissingTrailingParam) {
  18488. const auto pattern = "/users/:id";
  18489. detail::PathParamsMatcher matcher(pattern);
  18490. Request request;
  18491. request.path = "/users";
  18492. ASSERT_FALSE(matcher.match(request));
  18493. }
  18494. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18495. const auto pattern = "/users/:id/subscriptions";
  18496. detail::PathParamsMatcher matcher(pattern);
  18497. Request request;
  18498. request.path = "/users/subscriptions";
  18499. ASSERT_FALSE(matcher.match(request));
  18500. }
  18501. TEST(PathParamsTest, MultipleParams) {
  18502. const auto pattern = "/users/:userid/subscriptions/:subid";
  18503. detail::PathParamsMatcher matcher(pattern);
  18504. Request request;
  18505. request.path = "/users/42/subscriptions/2";
  18506. ASSERT_TRUE(matcher.match(request));
  18507. std::unordered_map<std::string, std::string> expected_params = {
  18508. {"userid", "42"}, {"subid", "2"}};
  18509. EXPECT_EQ(request.path_params, expected_params);
  18510. }
  18511. TEST(PathParamsTest, SequenceOfParams) {
  18512. const auto pattern = "/values/:x/:y/:z";
  18513. detail::PathParamsMatcher matcher(pattern);
  18514. Request request;
  18515. request.path = "/values/1/2/3";
  18516. ASSERT_TRUE(matcher.match(request));
  18517. std::unordered_map<std::string, std::string> expected_params = {
  18518. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18519. EXPECT_EQ(request.path_params, expected_params);
  18520. }
  18521. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18522. const auto pattern = "/prefix:suffix";
  18523. detail::PathParamsMatcher matcher(pattern);
  18524. Request request;
  18525. request.path = "/prefix:suffix";
  18526. ASSERT_TRUE(matcher.match(request));
  18527. const std::unordered_map<std::string, std::string> expected_params = {};
  18528. EXPECT_EQ(request.path_params, expected_params);
  18529. }
  18530. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18531. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18532. // calling thread's stack on a long enough path for a quantified pattern;
  18533. // RegexMatcher must refuse to run regex matching on paths beyond
  18534. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18535. detail::RegexMatcher matcher("/files/(.*)");
  18536. Request within_limit;
  18537. within_limit.path = "/files/" + std::string(10, 'A');
  18538. EXPECT_TRUE(matcher.match(within_limit));
  18539. Request over_limit;
  18540. over_limit.path =
  18541. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18542. EXPECT_FALSE(matcher.match(over_limit));
  18543. }
  18544. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18545. Server svr;
  18546. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18547. res.set_content("ok", "text/plain");
  18548. });
  18549. auto port = svr.bind_to_any_port(HOST);
  18550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18551. auto se = detail::scope_exit([&] {
  18552. svr.stop();
  18553. thread.join();
  18554. ASSERT_FALSE(svr.is_running());
  18555. });
  18556. svr.wait_until_ready();
  18557. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18558. // request URI limit; this used to be able to crash the process.
  18559. std::string path =
  18560. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18561. std::string req = "GET " + path +
  18562. " HTTP/1.1\r\n"
  18563. "Host: " +
  18564. std::string(HOST) + ":" + std::to_string(port) +
  18565. "\r\n"
  18566. "Connection: close\r\n"
  18567. "\r\n";
  18568. std::string response;
  18569. ASSERT_TRUE(send_request(5, req, &response, port));
  18570. EXPECT_NE(std::string::npos, response.find("404"));
  18571. }
  18572. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18573. Server svr;
  18574. auto handler = [](const Request & /*req*/, Response &res) {
  18575. res.set_content("hit", "text/plain");
  18576. };
  18577. // No regex metacharacter, so this one is compared literally
  18578. svr.Get("/literal/route", handler);
  18579. // '.' is a regex metacharacter, so this one must keep regex semantics
  18580. svr.Get("/a.c", handler);
  18581. auto port = svr.bind_to_any_port(HOST);
  18582. std::thread t([&]() { svr.listen_after_bind(); });
  18583. auto se = detail::scope_exit([&] {
  18584. svr.stop();
  18585. t.join();
  18586. ASSERT_FALSE(svr.is_running());
  18587. });
  18588. svr.wait_until_ready();
  18589. Client cli(HOST, port);
  18590. struct {
  18591. const char *path;
  18592. int status;
  18593. } cases[] = {
  18594. {"/literal/route", StatusCode::OK_200},
  18595. {"/literal/routes", StatusCode::NotFound_404},
  18596. {"/literal/rout", StatusCode::NotFound_404},
  18597. {"/abc", StatusCode::OK_200},
  18598. {"/a.c", StatusCode::OK_200},
  18599. };
  18600. for (const auto &x : cases) {
  18601. auto res = cli.Get(x.path);
  18602. ASSERT_TRUE(res) << x.path;
  18603. EXPECT_EQ(x.status, res->status) << x.path;
  18604. }
  18605. }
  18606. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18607. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18608. // from exhausting the stack, so it must only constrain routes that actually
  18609. // run a regular expression. A literal route is matched by comparison and
  18610. // stays usable at any length.
  18611. Server svr;
  18612. const std::string pattern =
  18613. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18614. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18615. res.set_content("hit", "text/plain");
  18616. });
  18617. auto port = svr.bind_to_any_port(HOST);
  18618. std::thread t([&]() { svr.listen_after_bind(); });
  18619. auto se = detail::scope_exit([&] {
  18620. svr.stop();
  18621. t.join();
  18622. ASSERT_FALSE(svr.is_running());
  18623. });
  18624. svr.wait_until_ready();
  18625. Client cli(HOST, port);
  18626. auto res = cli.Get(pattern);
  18627. ASSERT_TRUE(res);
  18628. EXPECT_EQ(StatusCode::OK_200, res->status);
  18629. }
  18630. TEST(ParseUrlTest, VariousPatterns) {
  18631. {
  18632. detail::UrlComponents uc;
  18633. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18634. EXPECT_EQ("http", uc.scheme);
  18635. EXPECT_EQ("example.com", uc.host);
  18636. EXPECT_EQ("8080", uc.port);
  18637. EXPECT_EQ("/path", uc.path);
  18638. EXPECT_EQ("?q=1", uc.query);
  18639. }
  18640. {
  18641. detail::UrlComponents uc;
  18642. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18643. EXPECT_EQ("https", uc.scheme);
  18644. EXPECT_EQ("example.com", uc.host);
  18645. EXPECT_TRUE(uc.port.empty());
  18646. EXPECT_EQ("/path", uc.path);
  18647. }
  18648. {
  18649. detail::UrlComponents uc;
  18650. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18651. EXPECT_EQ("::1", uc.host);
  18652. EXPECT_EQ("8080", uc.port);
  18653. EXPECT_EQ("/path", uc.path);
  18654. }
  18655. {
  18656. detail::UrlComponents uc;
  18657. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18658. }
  18659. {
  18660. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18661. // the path while the connection still targets the bracketed host.
  18662. detail::UrlComponents uc;
  18663. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18664. }
  18665. {
  18666. detail::UrlComponents uc;
  18667. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18668. }
  18669. {
  18670. detail::UrlComponents uc;
  18671. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18672. EXPECT_EQ("::1", uc.host);
  18673. EXPECT_TRUE(uc.port.empty());
  18674. EXPECT_EQ("/path", uc.path);
  18675. }
  18676. {
  18677. detail::UrlComponents uc;
  18678. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18679. EXPECT_TRUE(uc.scheme.empty());
  18680. EXPECT_EQ("example.com", uc.host);
  18681. EXPECT_EQ("/path", uc.path);
  18682. EXPECT_EQ("?q=1", uc.query);
  18683. }
  18684. {
  18685. detail::UrlComponents uc;
  18686. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18687. EXPECT_TRUE(uc.host.empty());
  18688. EXPECT_EQ("/path", uc.path);
  18689. EXPECT_EQ("?q=1", uc.query);
  18690. }
  18691. {
  18692. detail::UrlComponents uc;
  18693. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18694. EXPECT_EQ("example.com", uc.host);
  18695. EXPECT_EQ("8080", uc.port);
  18696. }
  18697. {
  18698. // Unix socket path — must not be parsed as host
  18699. detail::UrlComponents uc;
  18700. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18701. EXPECT_TRUE(uc.host.empty());
  18702. }
  18703. {
  18704. detail::UrlComponents uc;
  18705. ASSERT_TRUE(detail::parse_url("", uc));
  18706. EXPECT_TRUE(uc.host.empty());
  18707. EXPECT_TRUE(uc.path.empty());
  18708. }
  18709. {
  18710. detail::UrlComponents uc;
  18711. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18712. EXPECT_EQ("http", uc.scheme);
  18713. }
  18714. {
  18715. detail::UrlComponents uc;
  18716. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18717. }
  18718. {
  18719. // Accepted by parse_url; callers restrict to http/https
  18720. detail::UrlComponents uc;
  18721. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18722. EXPECT_EQ("ftp", uc.scheme);
  18723. }
  18724. {
  18725. detail::UrlComponents uc;
  18726. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18727. }
  18728. {
  18729. detail::UrlComponents uc;
  18730. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18731. }
  18732. }
  18733. TEST(ParseUrlTest, FragmentHandling) {
  18734. {
  18735. detail::UrlComponents uc;
  18736. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18737. EXPECT_EQ("/path", uc.path);
  18738. EXPECT_TRUE(uc.query.empty());
  18739. }
  18740. {
  18741. detail::UrlComponents uc;
  18742. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18743. EXPECT_TRUE(uc.path.empty());
  18744. EXPECT_TRUE(uc.query.empty());
  18745. }
  18746. }
  18747. TEST(ParseUrlTest, UserinfoHandling) {
  18748. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18749. // parsers would see evil.com as the host.
  18750. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18751. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18752. for (auto url : urls) {
  18753. detail::UrlComponents uc;
  18754. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18755. }
  18756. }
  18757. TEST(ParseUrlTest, IPv6EdgeCases) {
  18758. {
  18759. detail::UrlComponents uc;
  18760. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18761. EXPECT_TRUE(uc.scheme.empty());
  18762. EXPECT_EQ("::1", uc.host);
  18763. EXPECT_EQ("8080", uc.port);
  18764. }
  18765. {
  18766. // Zone ID '%25' is not in [a-fA-F0-9:]
  18767. detail::UrlComponents uc;
  18768. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18769. }
  18770. }
  18771. TEST(ParseUrlTest, SchemeEdgeCases) {
  18772. {
  18773. detail::UrlComponents uc;
  18774. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18775. }
  18776. {
  18777. detail::UrlComponents uc;
  18778. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18779. }
  18780. {
  18781. detail::UrlComponents uc;
  18782. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18783. }
  18784. {
  18785. detail::UrlComponents uc;
  18786. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18787. EXPECT_EQ("https", uc.scheme);
  18788. }
  18789. }
  18790. TEST(ParseUrlTest, PortEdgeCases) {
  18791. {
  18792. detail::UrlComponents uc;
  18793. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18794. EXPECT_TRUE(uc.port.empty());
  18795. EXPECT_EQ("/path", uc.path);
  18796. }
  18797. {
  18798. // parse_url accepts any port string; validation is done by parse_port
  18799. detail::UrlComponents uc;
  18800. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18801. EXPECT_EQ("abc", uc.port);
  18802. }
  18803. }
  18804. TEST(ParseUrlTest, WebSocketPatterns) {
  18805. {
  18806. detail::UrlComponents uc;
  18807. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18808. EXPECT_EQ("ws", uc.scheme);
  18809. EXPECT_EQ("echo.example.com", uc.host);
  18810. EXPECT_EQ("8080", uc.port);
  18811. EXPECT_EQ("/ws", uc.path);
  18812. }
  18813. {
  18814. detail::UrlComponents uc;
  18815. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18816. EXPECT_EQ("wss", uc.scheme);
  18817. EXPECT_EQ("echo.example.com", uc.host);
  18818. EXPECT_TRUE(uc.port.empty());
  18819. EXPECT_EQ("/ws", uc.path);
  18820. }
  18821. }
  18822. TEST(ParseUrlTest, QueryOnly) {
  18823. detail::UrlComponents uc;
  18824. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18825. EXPECT_TRUE(uc.host.empty());
  18826. EXPECT_TRUE(uc.path.empty());
  18827. EXPECT_EQ("?q=1&r=2", uc.query);
  18828. }
  18829. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18830. detail::UrlComponents uc;
  18831. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18832. EXPECT_TRUE(uc.scheme.empty());
  18833. EXPECT_EQ("example.com", uc.host);
  18834. EXPECT_EQ("443", uc.port);
  18835. EXPECT_EQ("/path", uc.path);
  18836. }
  18837. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18838. // If ipv6 regex working, regex match codepath is taken.
  18839. // else port will default to 80 in Client impl
  18840. int clientImplMagicPort = 80;
  18841. int port = 4321;
  18842. // above ports must be different to avoid false negative
  18843. EXPECT_NE(clientImplMagicPort, port);
  18844. std::string ipV6TestURL = "http://[ff06::c3]";
  18845. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18846. CLIENT_PRIVATE_KEY_FILE);
  18847. EXPECT_EQ(cli.port(), port);
  18848. }
  18849. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18850. auto file_path = "./www/dir/index.html";
  18851. auto dir_path = "./www/dir";
  18852. detail::FileStat stat_file(file_path);
  18853. EXPECT_TRUE(stat_file.is_file());
  18854. EXPECT_FALSE(stat_file.is_dir());
  18855. detail::FileStat stat_dir(dir_path);
  18856. EXPECT_FALSE(stat_dir.is_file());
  18857. EXPECT_TRUE(stat_dir.is_dir());
  18858. }
  18859. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18860. // IPv4 with default HTTP port (80)
  18861. EXPECT_EQ("example.com",
  18862. detail::make_host_and_port_string("example.com", 80, false));
  18863. // IPv4 with default HTTPS port (443)
  18864. EXPECT_EQ("example.com",
  18865. detail::make_host_and_port_string("example.com", 443, true));
  18866. // IPv4 with non-default HTTP port
  18867. EXPECT_EQ("example.com:8080",
  18868. detail::make_host_and_port_string("example.com", 8080, false));
  18869. // IPv4 with non-default HTTPS port
  18870. EXPECT_EQ("example.com:8443",
  18871. detail::make_host_and_port_string("example.com", 8443, true));
  18872. // IPv6 with default HTTP port (80)
  18873. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18874. // IPv6 with default HTTPS port (443)
  18875. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18876. // IPv6 with non-default HTTP port
  18877. EXPECT_EQ("[::1]:8080",
  18878. detail::make_host_and_port_string("::1", 8080, false));
  18879. // IPv6 with non-default HTTPS port
  18880. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18881. // IPv6 full address with default port
  18882. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18883. detail::make_host_and_port_string(
  18884. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18885. // IPv6 full address with non-default port
  18886. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18887. detail::make_host_and_port_string(
  18888. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18889. // IPv6 localhost with non-default port
  18890. EXPECT_EQ("[::1]:3000",
  18891. detail::make_host_and_port_string("::1", 3000, false));
  18892. // IPv6 with zone ID (link-local address) with default port
  18893. EXPECT_EQ("[fe80::1%eth0]",
  18894. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18895. // IPv6 with zone ID (link-local address) with non-default port
  18896. EXPECT_EQ("[fe80::1%eth0]:8080",
  18897. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18898. // Edge case: Port 443 with is_ssl=false (should add port)
  18899. EXPECT_EQ("example.com:443",
  18900. detail::make_host_and_port_string("example.com", 443, false));
  18901. // Edge case: Port 80 with is_ssl=true (should add port)
  18902. EXPECT_EQ("example.com:80",
  18903. detail::make_host_and_port_string("example.com", 80, true));
  18904. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18905. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18906. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18907. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18908. // Security fix: Already bracketed IPv6 should not get double brackets
  18909. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18910. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18911. EXPECT_EQ("[::1]:8080",
  18912. detail::make_host_and_port_string("[::1]", 8080, false));
  18913. EXPECT_EQ("[2001:db8::1]:8080",
  18914. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18915. EXPECT_EQ("[fe80::1%eth0]",
  18916. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18917. EXPECT_EQ("[fe80::1%eth0]:8080",
  18918. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18919. // Edge case: Empty host (should return as-is)
  18920. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18921. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18922. // This is a known limitation but shouldn't crash
  18923. EXPECT_EQ("[host:name]",
  18924. detail::make_host_and_port_string("host:name", 80, false));
  18925. // Port number edge cases (no validation, but should not crash)
  18926. EXPECT_EQ("example.com:0",
  18927. detail::make_host_and_port_string("example.com", 0, false));
  18928. EXPECT_EQ("example.com:-1",
  18929. detail::make_host_and_port_string("example.com", -1, false));
  18930. EXPECT_EQ("example.com:65535",
  18931. detail::make_host_and_port_string("example.com", 65535, false));
  18932. EXPECT_EQ("example.com:65536",
  18933. detail::make_host_and_port_string("example.com", 65536, false));
  18934. }
  18935. namespace httplib {
  18936. namespace detail {
  18937. std::string
  18938. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18939. const std::string &host, int port);
  18940. } // namespace detail
  18941. } // namespace httplib
  18942. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18943. std::map<std::string, std::string> addr_map = {
  18944. {"ipv4.example", "192.0.2.10"},
  18945. {"ipv6.example", "2001:db8::1"},
  18946. {"name.example", "internal.example.lan"},
  18947. {"empty.example", ""}};
  18948. EXPECT_EQ("192.0.2.10:443",
  18949. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18950. EXPECT_EQ("[2001:db8::1]:443",
  18951. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18952. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18953. addr_map, "name.example", 8443));
  18954. // An empty or absent mapping keeps the hostname as the target
  18955. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18956. addr_map, "empty.example", 443));
  18957. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18958. addr_map, "other.example", 443));
  18959. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18960. }
  18961. #ifdef CPPHTTPLIB_SSL_ENABLED
  18962. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18963. httplib::SSLClient cli("roblox.com", 443);
  18964. cli.set_follow_location(true);
  18965. auto res = cli.Get("/");
  18966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18967. EXPECT_EQ(StatusCode::OK_200, res->status);
  18968. }
  18969. #endif
  18970. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18971. Server svr;
  18972. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18973. EXPECT_EQ(res.status, 400);
  18974. });
  18975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18976. auto se = detail::scope_exit([&] {
  18977. svr.stop();
  18978. thread.join();
  18979. ASSERT_FALSE(svr.is_running());
  18980. });
  18981. svr.wait_until_ready();
  18982. Client cli(HOST, PORT);
  18983. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18984. }
  18985. TEST(InvalidHeaderCharsTest, is_field_name) {
  18986. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18987. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18988. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18989. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18990. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18991. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18992. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18993. EXPECT_FALSE(detail::fields::is_field_name(""));
  18994. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18995. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18996. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18997. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18998. }
  18999. TEST(InvalidHeaderCharsTest, is_field_value) {
  19000. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19001. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19002. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19003. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19004. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19005. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19006. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19007. EXPECT_TRUE(detail::fields::is_field_value(""));
  19008. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19009. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19010. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19011. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19012. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19013. }
  19014. TEST(InvalidHeaderCharsTest, OnServer) {
  19015. Server svr;
  19016. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19017. std::string header = "Not Set";
  19018. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19019. res.set_header(header, "value");
  19020. res.set_content("Page Content Page Content", "text/plain");
  19021. });
  19022. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19023. std::string header = "Not Set";
  19024. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19025. res.set_header("X-Test", header);
  19026. res.set_content("Page Content Page Content", "text/plain");
  19027. });
  19028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19029. auto se = detail::scope_exit([&] {
  19030. svr.stop();
  19031. thread.join();
  19032. ASSERT_FALSE(svr.is_running());
  19033. });
  19034. svr.wait_until_ready();
  19035. Client cli(HOST, PORT);
  19036. {
  19037. auto res = cli.Get(
  19038. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19040. EXPECT_EQ("Page Content Page Content", res->body);
  19041. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19042. }
  19043. {
  19044. auto res = cli.Get(
  19045. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19047. EXPECT_EQ("Page Content Page Content", res->body);
  19048. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19049. }
  19050. }
  19051. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19052. auto handled = false;
  19053. Server svr;
  19054. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19055. thread t = thread([&] { svr.listen(HOST, PORT); });
  19056. auto se = detail::scope_exit([&] {
  19057. svr.stop();
  19058. t.join();
  19059. ASSERT_FALSE(svr.is_running());
  19060. ASSERT_FALSE(handled);
  19061. });
  19062. svr.wait_until_ready();
  19063. auto req = "POST /test HTTP/1.1\r\n"
  19064. "Content-Length: x\r\n"
  19065. "\r\n";
  19066. std::string response;
  19067. ASSERT_TRUE(send_request(1, req, &response));
  19068. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19069. response.substr(0, response.find("\r\n")));
  19070. }
  19071. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19072. // case-insensitive, and a server that receives a 100-continue expectation in
  19073. // an HTTP/1.0 request MUST ignore it.
  19074. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19075. std::string response;
  19076. ASSERT_TRUE(send_request(1, req, &response, port));
  19077. *got_100 = response.find("100 Continue") != std::string::npos;
  19078. }
  19079. class ExpectTokenTest : public ::testing::Test {
  19080. protected:
  19081. void SetUp() override {
  19082. svr_.Post("/p", [](const Request &, Response &res) {
  19083. res.set_content("ok", "text/plain");
  19084. });
  19085. port_ = svr_.bind_to_any_port(HOST);
  19086. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19087. svr_.wait_until_ready();
  19088. }
  19089. void TearDown() override {
  19090. svr_.stop();
  19091. if (thread_.joinable()) { thread_.join(); }
  19092. }
  19093. std::string request(const char *version, const char *expect_value) const {
  19094. return std::string("POST /p ") + version +
  19095. "\r\n"
  19096. "Host: localhost\r\n"
  19097. "Content-Length: 2\r\n"
  19098. "Connection: close\r\n"
  19099. "Expect: " +
  19100. expect_value +
  19101. "\r\n"
  19102. "\r\n"
  19103. "hi";
  19104. }
  19105. Server svr_;
  19106. int port_ = 0;
  19107. thread thread_;
  19108. };
  19109. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19110. bool got_100 = false;
  19111. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19112. EXPECT_TRUE(got_100);
  19113. }
  19114. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19115. bool got_100 = true;
  19116. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19117. EXPECT_FALSE(got_100);
  19118. }
  19119. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19120. bool got_100 = false;
  19121. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19122. EXPECT_TRUE(got_100);
  19123. }
  19124. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19125. bool got_100 = false;
  19126. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19127. EXPECT_TRUE(got_100);
  19128. }
  19129. // `100 Continue` is sent only when the server starts reading the body, so a
  19130. // request rejected before that never invites the client to send it. The
  19131. // requests below carry the expectation but withhold the body, as a client
  19132. // waiting for `100 Continue` would.
  19133. // A POST that expects `100 Continue` and withholds its two-byte body.
  19134. static std::string expect_headers_only(const std::string &path) {
  19135. return "POST " + path +
  19136. " HTTP/1.1\r\n"
  19137. "Host: localhost\r\n"
  19138. "Content-Length: 2\r\n"
  19139. "Expect: 100-continue\r\n"
  19140. "\r\n";
  19141. }
  19142. class ExpectLazyContinueTest : public ::testing::Test {
  19143. protected:
  19144. void SetUp() override {
  19145. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19146. if (req.path == "/pre-routing") {
  19147. res.status = StatusCode::Unauthorized_401;
  19148. return Server::HandlerResponse::Handled;
  19149. }
  19150. return Server::HandlerResponse::Unhandled;
  19151. });
  19152. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19153. if (req.matched_route == "/pre-request") {
  19154. res.status = StatusCode::Forbidden_403;
  19155. return Server::HandlerResponse::Handled;
  19156. }
  19157. return Server::HandlerResponse::Unhandled;
  19158. });
  19159. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19160. res.set_content("ok", "text/plain");
  19161. });
  19162. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19163. res.set_content("ok", "text/plain");
  19164. });
  19165. svr_.Post("/reader-used", [](const Request &, Response &res,
  19166. const ContentReader &content_reader) {
  19167. std::string body;
  19168. content_reader([&](const char *data, size_t len) {
  19169. body.append(data, len);
  19170. return true;
  19171. });
  19172. res.set_content(body, "text/plain");
  19173. });
  19174. svr_.Post("/reader-unused",
  19175. [](const Request &, Response &res, const ContentReader &) {
  19176. res.set_content("ignored", "text/plain");
  19177. });
  19178. port_ = svr_.bind_to_any_port(HOST);
  19179. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19180. svr_.wait_until_ready();
  19181. }
  19182. void TearDown() override {
  19183. svr_.stop();
  19184. if (thread_.joinable()) { thread_.join(); }
  19185. }
  19186. // Sends `req` and reads until the server closes the connection. Returns
  19187. // false if the read had to wait for the client-side timeout instead.
  19188. bool send_until_closed(const std::string &req, std::string *resp) const {
  19189. auto start = std::chrono::steady_clock::now();
  19190. if (!send_request(3, req, resp, port_)) { return false; }
  19191. auto elapsed = std::chrono::steady_clock::now() - start;
  19192. return elapsed < std::chrono::seconds(2);
  19193. }
  19194. // The final response comes without `100 Continue`, and the server closes
  19195. // the connection since the body may or may not follow.
  19196. void expect_final_without_interim(const std::string &path,
  19197. const char *status_line) const {
  19198. std::string resp;
  19199. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19200. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19201. EXPECT_EQ(0u, resp.find(status_line));
  19202. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19203. }
  19204. Server svr_;
  19205. int port_ = 0;
  19206. thread thread_;
  19207. };
  19208. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19209. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19210. }
  19211. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19212. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19213. }
  19214. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19215. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19216. }
  19217. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19218. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19219. }
  19220. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19221. // The body follows once `100 Continue` has had time to arrive.
  19222. auto req = expect_headers_only("/reader-used");
  19223. req.insert(req.size() - 2, "Connection: close\r\n");
  19224. std::string resp;
  19225. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19226. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19227. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19228. EXPECT_NE(std::string::npos, resp.find("hi"));
  19229. }
  19230. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19231. // Large enough for the client to add `Expect: 100-continue` itself.
  19232. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19233. std::atomic<bool> body_sent{false};
  19234. Client cli(HOST, port_);
  19235. auto res = cli.Post(
  19236. "/pre-request", length,
  19237. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19238. body_sent = true;
  19239. std::string chunk(len, 'x');
  19240. sink.write(chunk.data(), chunk.size());
  19241. return true;
  19242. },
  19243. "application/octet-stream");
  19244. ASSERT_TRUE(res);
  19245. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19246. EXPECT_FALSE(body_sent);
  19247. }
  19248. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19249. Server svr;
  19250. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19251. return StatusCode::ExpectationFailed_417;
  19252. });
  19253. svr.Post("/p", [](const Request &, Response &res) {
  19254. res.set_content("ok", "text/plain");
  19255. });
  19256. auto port = svr.bind_to_any_port(HOST);
  19257. thread t = thread([&] { svr.listen_after_bind(); });
  19258. auto se = detail::scope_exit([&] {
  19259. svr.stop();
  19260. t.join();
  19261. });
  19262. svr.wait_until_ready();
  19263. std::string resp;
  19264. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19265. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19266. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19267. // Exactly one response: the route handler must not run after the 417.
  19268. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19269. }
  19270. #ifndef _WIN32
  19271. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19272. static constexpr char reject[] = "Unauthorized";
  19273. static constexpr char accept[] = "Upload accepted";
  19274. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19275. Server svr;
  19276. svr.set_expect_100_continue_handler(
  19277. [](const Request & /*req*/, Response &res) {
  19278. res.status = StatusCode::Unauthorized_401;
  19279. res.set_content(reject, "text/plain");
  19280. return res.status;
  19281. });
  19282. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19283. res.set_content(accept, "text/plain");
  19284. });
  19285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19286. auto se = detail::scope_exit([&] {
  19287. svr.stop();
  19288. thread.join();
  19289. ASSERT_FALSE(svr.is_running());
  19290. });
  19291. svr.wait_until_ready();
  19292. {
  19293. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19294. curl_easy_init(), &curl_easy_cleanup};
  19295. ASSERT_NE(curl, nullptr);
  19296. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19297. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19298. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19299. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19300. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19301. &curl_slist_free_all};
  19302. ASSERT_NE(list, nullptr);
  19303. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19304. struct read_data {
  19305. uint64_t read_size;
  19306. uint64_t total_size;
  19307. } data = {0, total_size};
  19308. using read_callback_t =
  19309. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19310. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19311. void *userdata) -> size_t {
  19312. read_data *d = (read_data *)userdata;
  19313. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19314. std::fill_n(ptr, size * nmemb, 'A');
  19315. d->read_size += size * nmemb;
  19316. return size * nmemb;
  19317. };
  19318. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19319. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19320. std::vector<char> buffer;
  19321. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19322. using write_callback_t =
  19323. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19324. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19325. void *userdata) -> size_t {
  19326. std::vector<char> *buf = (std::vector<char> *)userdata;
  19327. buf->reserve(buf->size() + size * nmemb + 1);
  19328. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19329. return size * nmemb;
  19330. };
  19331. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19332. {
  19333. const auto res = curl_easy_perform(curl.get());
  19334. ASSERT_EQ(res, CURLE_OK);
  19335. }
  19336. {
  19337. auto response_code = long{};
  19338. const auto res =
  19339. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19340. ASSERT_EQ(res, CURLE_OK);
  19341. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19342. }
  19343. {
  19344. auto dl = curl_off_t{};
  19345. const auto res =
  19346. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19347. ASSERT_EQ(res, CURLE_OK);
  19348. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19349. }
  19350. {
  19351. buffer.push_back('\0');
  19352. ASSERT_STRCASEEQ(buffer.data(), reject);
  19353. }
  19354. }
  19355. }
  19356. #endif
  19357. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19358. // Regression test for #2458.
  19359. //
  19360. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19361. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19362. // ticket can make the client socket spuriously readable during the
  19363. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19364. // the client withholds the body and then blocks reading a response that never
  19365. // comes, failing with `Failed to read connection`.
  19366. //
  19367. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19368. // within the timeout. This raw OpenSSL server deliberately never sends
  19369. // `100 Continue`; the client must still deliver the body and receive 200.
  19370. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19371. signal(SIGPIPE, SIG_IGN);
  19372. const auto port = PORT + 4;
  19373. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19374. ASSERT_NE(srv, INVALID_SOCKET);
  19375. int opt = 1;
  19376. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19377. sockaddr_in addr{};
  19378. addr.sin_family = AF_INET;
  19379. addr.sin_port = htons(static_cast<uint16_t>(port));
  19380. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19381. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19382. ASSERT_EQ(0, ::listen(srv, 1));
  19383. std::atomic<size_t> server_body_bytes{0};
  19384. auto server_thread = std::thread([&] {
  19385. sockaddr_in cli_addr{};
  19386. socklen_t cli_len = sizeof(cli_addr);
  19387. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19388. if (cli == INVALID_SOCKET) { return; }
  19389. // Bound the lifetime of the server side so a buggy client (which never
  19390. // sends the body) cannot make this thread block forever on join.
  19391. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19392. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19393. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19394. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19395. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19396. SSL *ssl = SSL_new(ctx);
  19397. SSL_set_fd(ssl, static_cast<int>(cli));
  19398. if (SSL_accept(ssl) > 0) {
  19399. // Read the request headers. Reading here also flushes the TLS 1.3
  19400. // session tickets to the client. Deliberately do NOT send
  19401. // `100 Continue`.
  19402. std::string buf;
  19403. char tmp[1024];
  19404. while (buf.find("\r\n\r\n") == std::string::npos) {
  19405. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19406. if (n <= 0) { break; }
  19407. buf.append(tmp, static_cast<size_t>(n));
  19408. }
  19409. // A correct client sends the body now; count what arrives.
  19410. auto pos = buf.find("\r\n\r\n");
  19411. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19412. while (body < 4096) {
  19413. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19414. if (n <= 0) { break; }
  19415. body += static_cast<size_t>(n);
  19416. }
  19417. server_body_bytes = body;
  19418. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19419. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19420. SSL_shutdown(ssl);
  19421. }
  19422. SSL_free(ssl);
  19423. detail::close_socket(cli);
  19424. SSL_CTX_free(ctx);
  19425. });
  19426. auto se = detail::scope_exit([&] {
  19427. server_thread.join();
  19428. detail::close_socket(srv);
  19429. });
  19430. SSLClient cli("127.0.0.1", port);
  19431. cli.enable_server_certificate_verification(false);
  19432. cli.set_connection_timeout(5, 0);
  19433. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19434. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19435. std::string body(4096, 'A');
  19436. auto res = cli.Put("/api/test", body, "application/json");
  19437. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19438. EXPECT_EQ(StatusCode::OK_200, res->status);
  19439. EXPECT_EQ(body.size(), server_body_bytes.load());
  19440. }
  19441. #endif
  19442. template <typename S, typename C>
  19443. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19444. svr.Get("/stream", [&](const Request &, Response &res) {
  19445. auto data = new std::string("01234567890123456789");
  19446. res.set_content_provider(
  19447. data->size(), "text/plain",
  19448. [&, data](size_t offset, size_t length, DataSink &sink) {
  19449. const size_t DATA_CHUNK_SIZE = 4;
  19450. const auto &d = *data;
  19451. std::this_thread::sleep_for(std::chrono::seconds(1));
  19452. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19453. return true;
  19454. },
  19455. [data](bool success) {
  19456. EXPECT_FALSE(success);
  19457. delete data;
  19458. });
  19459. });
  19460. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19461. auto i = new size_t(0);
  19462. res.set_content_provider(
  19463. "text/plain",
  19464. [i](size_t, DataSink &sink) {
  19465. if (*i < 5) {
  19466. std::this_thread::sleep_for(std::chrono::seconds(1));
  19467. sink.write("abcd", 4);
  19468. (*i)++;
  19469. } else {
  19470. sink.done();
  19471. }
  19472. return true;
  19473. },
  19474. [i](bool success) {
  19475. EXPECT_FALSE(success);
  19476. delete i;
  19477. });
  19478. });
  19479. svr.Get("/chunked", [&](const Request &, Response &res) {
  19480. auto i = new size_t(0);
  19481. res.set_chunked_content_provider(
  19482. "text/plain",
  19483. [i](size_t, DataSink &sink) {
  19484. if (*i < 5) {
  19485. std::this_thread::sleep_for(std::chrono::seconds(1));
  19486. sink.os << "abcd";
  19487. (*i)++;
  19488. } else {
  19489. sink.done();
  19490. }
  19491. return true;
  19492. },
  19493. [i](bool success) {
  19494. EXPECT_FALSE(success);
  19495. delete i;
  19496. });
  19497. });
  19498. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19499. auto se = detail::scope_exit([&] {
  19500. svr.stop();
  19501. listen_thread.join();
  19502. ASSERT_FALSE(svr.is_running());
  19503. });
  19504. svr.wait_until_ready();
  19505. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19506. {
  19507. auto start = std::chrono::steady_clock::now();
  19508. auto res = cli.Get("/stream");
  19509. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19510. std::chrono::steady_clock::now() - start)
  19511. .count();
  19512. ASSERT_FALSE(res);
  19513. EXPECT_EQ(Error::Read, res.error());
  19514. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19515. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19516. }
  19517. {
  19518. auto start = std::chrono::steady_clock::now();
  19519. auto res = cli.Get("/stream_without_length");
  19520. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19521. std::chrono::steady_clock::now() - start)
  19522. .count();
  19523. ASSERT_FALSE(res);
  19524. EXPECT_EQ(Error::Read, res.error());
  19525. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19526. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19527. }
  19528. {
  19529. auto start = std::chrono::steady_clock::now();
  19530. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19531. EXPECT_EQ("abcd", string(data, data_length));
  19532. return true;
  19533. });
  19534. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19535. std::chrono::steady_clock::now() - start)
  19536. .count();
  19537. ASSERT_FALSE(res);
  19538. EXPECT_EQ(Error::Read, res.error());
  19539. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19540. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19541. }
  19542. }
  19543. TEST(MaxTimeoutTest, ContentStream) {
  19544. time_t timeout = 2000;
  19545. time_t threshold = 200;
  19546. Server svr;
  19547. Client cli("localhost", PORT);
  19548. max_timeout_test(svr, cli, timeout, threshold);
  19549. }
  19550. #ifdef CPPHTTPLIB_SSL_ENABLED
  19551. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19552. time_t timeout = 2000;
  19553. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19555. SSLClient cli("localhost", PORT);
  19556. cli.enable_server_certificate_verification(false);
  19557. max_timeout_test(svr, cli, timeout, threshold);
  19558. }
  19559. #endif
  19560. class EventDispatcher {
  19561. public:
  19562. EventDispatcher() {}
  19563. bool wait_event(DataSink *sink) {
  19564. unique_lock<mutex> lk(m_);
  19565. int id = id_;
  19566. // Wait with timeout to prevent hanging if client disconnects
  19567. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19568. [&] { return cid_ == id; })) {
  19569. return false; // Timeout occurred
  19570. }
  19571. sink->write(message_.data(), message_.size());
  19572. return true;
  19573. }
  19574. void send_event(const string &message) {
  19575. lock_guard<mutex> lk(m_);
  19576. cid_ = id_++;
  19577. message_ = message;
  19578. cv_.notify_all();
  19579. }
  19580. private:
  19581. mutex m_;
  19582. condition_variable cv_;
  19583. atomic_int id_{0};
  19584. atomic_int cid_{-1};
  19585. string message_;
  19586. };
  19587. TEST(ClientInThreadTest, Issue2068) {
  19588. EventDispatcher ed;
  19589. Server svr;
  19590. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19591. res.set_chunked_content_provider("text/event-stream",
  19592. [&](size_t /*offset*/, DataSink &sink) {
  19593. return ed.wait_event(&sink);
  19594. });
  19595. });
  19596. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19597. svr.wait_until_ready();
  19598. thread event_thread([&] {
  19599. int id = 0;
  19600. while (svr.is_running()) {
  19601. this_thread::sleep_for(chrono::milliseconds(500));
  19602. std::stringstream ss;
  19603. ss << "data: " << id << "\n\n";
  19604. ed.send_event(ss.str());
  19605. id++;
  19606. }
  19607. });
  19608. auto se = detail::scope_exit([&] {
  19609. svr.stop();
  19610. listen_thread.join();
  19611. event_thread.join();
  19612. ASSERT_FALSE(svr.is_running());
  19613. });
  19614. {
  19615. auto client = detail::make_unique<Client>(HOST, PORT);
  19616. client->set_read_timeout(std::chrono::minutes(10));
  19617. std::atomic<bool> stop{false};
  19618. std::thread t([&] {
  19619. client->Get("/event1",
  19620. [&](const char *, size_t) -> bool { return !stop; });
  19621. });
  19622. std::this_thread::sleep_for(std::chrono::seconds(2));
  19623. stop = true;
  19624. client->stop();
  19625. t.join();
  19626. // Reset client after thread has finished
  19627. client.reset();
  19628. }
  19629. }
  19630. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19631. auto handled = false;
  19632. Server svr;
  19633. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19635. auto se = detail::scope_exit([&] {
  19636. svr.stop();
  19637. t.join();
  19638. ASSERT_FALSE(svr.is_running());
  19639. ASSERT_FALSE(handled);
  19640. });
  19641. svr.wait_until_ready();
  19642. // Two Content-Length headers with different values — must be rejected
  19643. auto req = "POST /test HTTP/1.1\r\n"
  19644. "Content-Length: 5\r\n"
  19645. "Content-Length: 10\r\n"
  19646. "\r\n"
  19647. "hello";
  19648. std::string response;
  19649. ASSERT_TRUE(send_request(1, req, &response));
  19650. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19651. response.substr(0, response.find("\r\n")));
  19652. }
  19653. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19654. auto handled = false;
  19655. Server svr;
  19656. svr.Post("/test", [&](const Request &, Response &res) {
  19657. handled = true;
  19658. res.set_content("ok", "text/plain");
  19659. });
  19660. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19661. auto se = detail::scope_exit([&] {
  19662. svr.stop();
  19663. t.join();
  19664. ASSERT_FALSE(svr.is_running());
  19665. ASSERT_TRUE(handled);
  19666. });
  19667. svr.wait_until_ready();
  19668. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19669. auto req = "POST /test HTTP/1.1\r\n"
  19670. "Host: localhost\r\n"
  19671. "Content-Length: 5\r\n"
  19672. "Content-Length: 5\r\n"
  19673. "\r\n"
  19674. "hello";
  19675. std::string response;
  19676. ASSERT_TRUE(send_request(1, req, &response));
  19677. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19678. }
  19679. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19680. Server svr;
  19681. svr.Get("/test", [](const Request &, Response &res) {
  19682. res.set_content("ok", "text/plain");
  19683. });
  19684. auto port = svr.bind_to_any_port(HOST);
  19685. thread t = thread([&] { svr.listen_after_bind(); });
  19686. auto se = detail::scope_exit([&] {
  19687. svr.stop();
  19688. t.join();
  19689. ASSERT_FALSE(svr.is_running());
  19690. });
  19691. svr.wait_until_ready();
  19692. auto status_line = [&](const std::string &host_lines) {
  19693. std::string res;
  19694. send_request(
  19695. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19696. &res, port);
  19697. return res.substr(0, res.find("\r\n"));
  19698. };
  19699. const char *accepted[] = {
  19700. "Host: localhost\r\n",
  19701. "Host: a.example:8080\r\n",
  19702. "Host: my_service\r\n",
  19703. "Host: [::1]:8080\r\n",
  19704. "Host: [fe80::1%25eth0]\r\n",
  19705. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19706. };
  19707. for (auto host_lines : accepted) {
  19708. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19709. }
  19710. const char *rejected[] = {
  19711. "Host: a.example\r\nHost: b.example\r\n",
  19712. "Host: a.example\r\nHost: a.example\r\n",
  19713. "Host: a@b.example\r\n",
  19714. "Host: a.example/b\r\n",
  19715. "Host: a.example\\b\r\n",
  19716. "Host: a.example?b\r\n",
  19717. "Host: a.example#b\r\n",
  19718. "Host: a.example b.example\r\n",
  19719. };
  19720. for (auto host_lines : rejected) {
  19721. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19722. << host_lines;
  19723. }
  19724. }
  19725. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19726. Server svr;
  19727. svr.Get("/", [](const Request &req, Response &res) {
  19728. EXPECT_EQ(2U, req.trailers.size());
  19729. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19730. // Denied
  19731. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19732. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19733. // Accepted
  19734. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19735. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19736. EXPECT_TRUE(req.has_trailer("X-World"));
  19737. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19738. res.set_content("ok", "text/plain");
  19739. });
  19740. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19741. auto se = detail::scope_exit([&] {
  19742. svr.stop();
  19743. t.join();
  19744. ASSERT_FALSE(svr.is_running());
  19745. });
  19746. svr.wait_until_ready();
  19747. const std::string req = "GET / HTTP/1.1\r\n"
  19748. "Transfer-Encoding: chunked\r\n"
  19749. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19750. "\r\n"
  19751. "0\r\n"
  19752. "Content-Length: 10\r\n"
  19753. "Host: internal.local\r\n"
  19754. "Content-Type: malicious/content\r\n"
  19755. "Cookie: any\r\n"
  19756. "Set-Cookie: any\r\n"
  19757. "X-Forwarded-For: attacker.com\r\n"
  19758. "X-Real-Ip: 1.1.1.1\r\n"
  19759. "X-Hello: hello\r\n"
  19760. "X-World: world\r\n"
  19761. "\r\n";
  19762. std::string res;
  19763. ASSERT_TRUE(send_request(1, req, &res));
  19764. }
  19765. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19766. // several field lines, and the combined value is what has to be parsed. A
  19767. // Trailer field split across lines therefore declares every name it lists;
  19768. // reading only the first line silently drops the trailers the later lines
  19769. // declare. The prohibited-trailer filter still applies to every line.
  19770. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19771. Server svr;
  19772. size_t observed_trailer_count = 0;
  19773. std::string observed_hello;
  19774. std::string observed_world;
  19775. bool observed_content_length = true;
  19776. svr.Get("/", [&](const Request &req, Response &res) {
  19777. observed_trailer_count = req.trailers.size();
  19778. observed_hello = req.get_trailer_value("X-Hello");
  19779. observed_world = req.get_trailer_value("X-World");
  19780. observed_content_length = req.has_trailer("Content-Length");
  19781. res.set_content("ok", "text/plain");
  19782. });
  19783. auto port = svr.bind_to_any_port(HOST);
  19784. thread t = thread([&]() { svr.listen_after_bind(); });
  19785. auto se = detail::scope_exit([&] {
  19786. svr.stop();
  19787. t.join();
  19788. ASSERT_FALSE(svr.is_running());
  19789. });
  19790. svr.wait_until_ready();
  19791. const std::string req = "GET / HTTP/1.1\r\n"
  19792. "Host: localhost\r\n"
  19793. "Transfer-Encoding: chunked\r\n"
  19794. "Trailer: X-Hello\r\n"
  19795. "Trailer: X-World, Content-Length\r\n"
  19796. "\r\n"
  19797. "0\r\n"
  19798. "X-Hello: hello\r\n"
  19799. "X-World: world\r\n"
  19800. "Content-Length: 10\r\n"
  19801. "\r\n";
  19802. std::string res;
  19803. ASSERT_TRUE(send_request(1, req, &res, port));
  19804. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19805. // Accepted: both field lines contribute to the declared set
  19806. EXPECT_EQ(2U, observed_trailer_count);
  19807. EXPECT_EQ(observed_hello, "hello");
  19808. EXPECT_EQ(observed_world, "world");
  19809. // Denied: a prohibited name stays prohibited on a later field line
  19810. EXPECT_FALSE(observed_content_length);
  19811. }
  19812. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19813. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19814. // unbounded run of fields that are never declared, because the counter would
  19815. // only advance for declared fields.
  19816. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19817. Server svr;
  19818. bool handler_called = false;
  19819. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19820. handler_called = true;
  19821. res.set_content("ok", "text/plain");
  19822. });
  19823. auto port = svr.bind_to_any_port(HOST);
  19824. thread t = thread([&]() { svr.listen_after_bind(); });
  19825. auto se = detail::scope_exit([&] {
  19826. svr.stop();
  19827. t.join();
  19828. ASSERT_FALSE(svr.is_running());
  19829. });
  19830. svr.wait_until_ready();
  19831. // Declare nothing, then send far more undeclared trailer fields than the
  19832. // header-count limit. Parsing must stop and reject the request rather than
  19833. // read every line.
  19834. std::string req = "GET / HTTP/1.1\r\n"
  19835. "Transfer-Encoding: chunked\r\n"
  19836. "\r\n"
  19837. "0\r\n";
  19838. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19839. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19840. }
  19841. req += "\r\n";
  19842. std::string res;
  19843. ASSERT_TRUE(send_request(1, req, &res, port));
  19844. // The request is rejected before the handler runs.
  19845. EXPECT_FALSE(handler_called);
  19846. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19847. }
  19848. // The set of declared trailer names is capped so a peer cannot grow it without
  19849. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19850. // declared past the cap is not honored, even if the field is actually sent.
  19851. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19852. Server svr;
  19853. // One name inside the cap and one past it, so the test tracks the cap rather
  19854. // than a fixed count.
  19855. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19856. const std::string within_cap_name = "X-T-0";
  19857. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19858. bool observed_within_cap = false;
  19859. bool observed_past_cap = false;
  19860. svr.Get("/", [&](const Request &req, Response &res) {
  19861. observed_within_cap = req.has_trailer(within_cap_name);
  19862. observed_past_cap = req.has_trailer(past_cap_name);
  19863. res.set_content("ok", "text/plain");
  19864. });
  19865. auto port = svr.bind_to_any_port(HOST);
  19866. thread t = thread([&]() { svr.listen_after_bind(); });
  19867. auto se = detail::scope_exit([&] {
  19868. svr.stop();
  19869. t.join();
  19870. ASSERT_FALSE(svr.is_running());
  19871. });
  19872. svr.wait_until_ready();
  19873. // Declare more trailer names than the cap in a single Trailer field, then
  19874. // actually send the first (within the cap) and the last (past it).
  19875. std::string trailer_decl = "Trailer: ";
  19876. for (int i = 0; i < declared_count; i++) {
  19877. if (i != 0) { trailer_decl += ", "; }
  19878. trailer_decl += "X-T-" + std::to_string(i);
  19879. }
  19880. trailer_decl += "\r\n";
  19881. const std::string req = "GET / HTTP/1.1\r\n"
  19882. "Host: localhost\r\n"
  19883. "Transfer-Encoding: chunked\r\n" +
  19884. trailer_decl +
  19885. "\r\n"
  19886. "0\r\n" +
  19887. within_cap_name + ": a\r\n" + past_cap_name +
  19888. ": b\r\n"
  19889. "\r\n";
  19890. std::string res;
  19891. ASSERT_TRUE(send_request(1, req, &res, port));
  19892. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19893. // A name within the cap is honored; one declared past the cap is dropped.
  19894. EXPECT_TRUE(observed_within_cap);
  19895. EXPECT_FALSE(observed_past_cap);
  19896. }
  19897. // A direct client that is not listed in trusted_proxies must not be able to
  19898. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19899. // the peer address on the actual TCP connection determines whether the
  19900. // header is honored.
  19901. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19902. Server svr;
  19903. // Deliberately does NOT include the loopback address the test client
  19904. // actually connects from, so the direct connection is not a trusted proxy.
  19905. svr.set_trusted_proxies({"203.0.113.66"});
  19906. std::string observed_remote_addr;
  19907. svr.Get("/ip", [&](const Request &req, Response &res) {
  19908. observed_remote_addr = req.remote_addr;
  19909. res.set_content("ok", "text/plain");
  19910. });
  19911. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19912. auto se = detail::scope_exit([&] {
  19913. svr.stop();
  19914. t.join();
  19915. ASSERT_FALSE(svr.is_running());
  19916. });
  19917. svr.wait_until_ready();
  19918. Client cli(HOST, PORT);
  19919. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19921. EXPECT_EQ(StatusCode::OK_200, res->status);
  19922. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19923. // ignored entirely and the real connection-level address retained.
  19924. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19925. observed_remote_addr == "127.0.0.1");
  19926. }
  19927. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19928. Server svr;
  19929. std::string observed_remote_addr;
  19930. std::string observed_xff;
  19931. svr.Get("/ip", [&](const Request &req, Response &res) {
  19932. observed_remote_addr = req.remote_addr;
  19933. observed_xff = req.get_header_value("X-Forwarded-For");
  19934. res.set_content("ok", "text/plain");
  19935. });
  19936. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19937. auto se = detail::scope_exit([&] {
  19938. svr.stop();
  19939. t.join();
  19940. ASSERT_FALSE(svr.is_running());
  19941. });
  19942. svr.wait_until_ready();
  19943. Client cli(HOST, PORT);
  19944. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19946. EXPECT_EQ(StatusCode::OK_200, res->status);
  19947. EXPECT_EQ(observed_xff, "203.0.113.66");
  19948. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19949. observed_remote_addr == "127.0.0.1");
  19950. }
  19951. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19952. Server svr;
  19953. svr.set_trusted_proxies({"203.0.113.66"});
  19954. std::string observed_remote_addr;
  19955. std::string observed_xff;
  19956. svr.Get("/ip", [&](const Request &req, Response &res) {
  19957. observed_remote_addr = req.remote_addr;
  19958. observed_xff = req.get_header_value("X-Forwarded-For");
  19959. res.set_content("ok", "text/plain");
  19960. });
  19961. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19962. auto se = detail::scope_exit([&] {
  19963. svr.stop();
  19964. t.join();
  19965. ASSERT_FALSE(svr.is_running());
  19966. });
  19967. svr.wait_until_ready();
  19968. Client cli(HOST, PORT);
  19969. auto res = cli.Get("/ip");
  19970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19971. EXPECT_EQ(StatusCode::OK_200, res->status);
  19972. EXPECT_EQ(observed_xff, "");
  19973. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19974. observed_remote_addr == "127.0.0.1");
  19975. }
  19976. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19977. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19978. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19979. Server svr;
  19980. svr.set_trusted_proxies({"127.0.0.1"});
  19981. svr.Get("/ip", [](const Request &req, Response &res) {
  19982. res.set_content(req.remote_addr, "text/plain");
  19983. });
  19984. auto port = svr.bind_to_any_port("::");
  19985. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19986. thread t = thread([&] { svr.listen_after_bind(); });
  19987. auto se = detail::scope_exit([&] {
  19988. svr.stop();
  19989. t.join();
  19990. ASSERT_FALSE(svr.is_running());
  19991. });
  19992. svr.wait_until_ready();
  19993. Client cli("127.0.0.1", port);
  19994. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19996. EXPECT_EQ("198.51.100.23", res->body);
  19997. }
  19998. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19999. Server svr;
  20000. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20001. svr.Get("/ip", [](const Request &req, Response &res) {
  20002. res.set_content(req.remote_addr, "text/plain");
  20003. });
  20004. auto port = svr.bind_to_any_port(HOST);
  20005. ASSERT_GT(port, 0);
  20006. thread t = thread([&] { svr.listen_after_bind(); });
  20007. auto se = detail::scope_exit([&] {
  20008. svr.stop();
  20009. t.join();
  20010. ASSERT_FALSE(svr.is_running());
  20011. });
  20012. svr.wait_until_ready();
  20013. Client cli(HOST, port);
  20014. auto res = cli.Get(
  20015. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20017. EXPECT_EQ("198.51.100.23", res->body);
  20018. }
  20019. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20020. Server svr;
  20021. // Include the loopback address the test client actually connects from, so
  20022. // the direct connection itself is recognized as the trusted proxy hop.
  20023. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20024. std::string observed_remote_addr;
  20025. std::string observed_xff;
  20026. svr.Get("/ip", [&](const Request &req, Response &res) {
  20027. observed_remote_addr = req.remote_addr;
  20028. observed_xff = req.get_header_value("X-Forwarded-For");
  20029. res.set_content("ok", "text/plain");
  20030. });
  20031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20032. auto se = detail::scope_exit([&] {
  20033. svr.stop();
  20034. t.join();
  20035. ASSERT_FALSE(svr.is_running());
  20036. });
  20037. svr.wait_until_ready();
  20038. Client cli(HOST, PORT);
  20039. auto res = cli.Get(
  20040. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20042. EXPECT_EQ(StatusCode::OK_200, res->status);
  20043. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20044. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20045. }
  20046. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20047. Server svr;
  20048. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20049. std::string observed_remote_addr;
  20050. std::string observed_xff;
  20051. svr.Get("/ip", [&](const Request &req, Response &res) {
  20052. observed_remote_addr = req.remote_addr;
  20053. observed_xff = req.get_header_value("X-Forwarded-For");
  20054. res.set_content("ok", "text/plain");
  20055. });
  20056. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20057. auto se = detail::scope_exit([&] {
  20058. svr.stop();
  20059. t.join();
  20060. ASSERT_FALSE(svr.is_running());
  20061. });
  20062. svr.wait_until_ready();
  20063. Client cli(HOST, PORT);
  20064. auto res = cli.Get(
  20065. "/ip",
  20066. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20068. EXPECT_EQ(StatusCode::OK_200, res->status);
  20069. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20070. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20071. }
  20072. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20073. Server svr;
  20074. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20075. std::string observed_remote_addr;
  20076. std::string observed_xff;
  20077. svr.Get("/ip", [&](const Request &req, Response &res) {
  20078. observed_remote_addr = req.remote_addr;
  20079. observed_xff = req.get_header_value("X-Forwarded-For");
  20080. res.set_content("ok", "text/plain");
  20081. });
  20082. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20083. auto se = detail::scope_exit([&] {
  20084. svr.stop();
  20085. t.join();
  20086. ASSERT_FALSE(svr.is_running());
  20087. });
  20088. svr.wait_until_ready();
  20089. Client cli(HOST, PORT);
  20090. auto res = cli.Get(
  20091. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20093. EXPECT_EQ(StatusCode::OK_200, res->status);
  20094. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20095. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20096. // and must not be selected.
  20097. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20098. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20099. }
  20100. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20101. Server svr;
  20102. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20103. std::string observed_remote_addr;
  20104. svr.Get("/ip", [&](const Request &req, Response &res) {
  20105. observed_remote_addr = req.remote_addr;
  20106. res.set_content("ok", "text/plain");
  20107. });
  20108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20109. auto se = detail::scope_exit([&] {
  20110. svr.stop();
  20111. t.join();
  20112. ASSERT_FALSE(svr.is_running());
  20113. });
  20114. svr.wait_until_ready();
  20115. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20116. // a forged address and the trusted proxy's own address; the forged value must
  20117. // not win over the address the trusted proxy actually recorded.
  20118. Client cli(HOST, PORT);
  20119. auto res = cli.Get(
  20120. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20122. EXPECT_EQ(StatusCode::OK_200, res->status);
  20123. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20124. }
  20125. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20126. Server svr;
  20127. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20128. std::string observed_remote_addr;
  20129. std::string observed_xff;
  20130. svr.Get("/ip", [&](const Request &req, Response &res) {
  20131. observed_remote_addr = req.remote_addr;
  20132. observed_xff = req.get_header_value("X-Forwarded-For");
  20133. res.set_content("ok", "text/plain");
  20134. });
  20135. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20136. auto se = detail::scope_exit([&] {
  20137. svr.stop();
  20138. t.join();
  20139. ASSERT_FALSE(svr.is_running());
  20140. });
  20141. svr.wait_until_ready();
  20142. Client cli(HOST, PORT);
  20143. auto res = cli.Get(
  20144. "/ip",
  20145. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20147. EXPECT_EQ(StatusCode::OK_200, res->status);
  20148. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20149. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20150. }
  20151. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20152. Server svr;
  20153. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20154. std::string observed_remote_addr;
  20155. std::string observed_xff;
  20156. svr.Get("/ip", [&](const Request &req, Response &res) {
  20157. observed_remote_addr = req.remote_addr;
  20158. observed_xff = req.get_header_value("X-Forwarded-For");
  20159. res.set_content("ok", "text/plain");
  20160. });
  20161. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20162. auto se = detail::scope_exit([&] {
  20163. svr.stop();
  20164. t.join();
  20165. ASSERT_FALSE(svr.is_running());
  20166. });
  20167. svr.wait_until_ready();
  20168. std::string raw_req =
  20169. "GET /ip HTTP/1.1\r\n"
  20170. "Host: localhost\r\n"
  20171. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20172. "Connection: close\r\n"
  20173. "\r\n";
  20174. std::string out;
  20175. ASSERT_TRUE(send_request(5, raw_req, &out));
  20176. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20177. // Header parser trims surrounding whitespace of the header value
  20178. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20179. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20180. }
  20181. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20182. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20183. // their own X-Forwarded-For as a separate field line rather than extending the
  20184. // one the client sent, so every occurrence has to be taken into account.
  20185. // Reading only the first one hands back the address the client chose.
  20186. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20187. Server svr;
  20188. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20189. std::string observed_remote_addr;
  20190. size_t observed_xff_count = 0;
  20191. svr.Get("/ip", [&](const Request &req, Response &res) {
  20192. observed_remote_addr = req.remote_addr;
  20193. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20194. res.set_content("ok", "text/plain");
  20195. });
  20196. auto port = svr.bind_to_any_port(HOST);
  20197. thread t = thread([&]() { svr.listen_after_bind(); });
  20198. auto se = detail::scope_exit([&] {
  20199. svr.stop();
  20200. t.join();
  20201. ASSERT_FALSE(svr.is_running());
  20202. });
  20203. svr.wait_until_ready();
  20204. // The client supplies the first field line; the trusted proxy appends the
  20205. // address it observed as a second one.
  20206. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20207. "Host: localhost\r\n"
  20208. "X-Forwarded-For: 1.2.3.4\r\n"
  20209. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20210. "Connection: close\r\n"
  20211. "\r\n";
  20212. std::string out;
  20213. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20214. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20215. EXPECT_EQ(observed_xff_count, 2U);
  20216. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20217. // The same chain spread over one field line per hop derives the same client
  20218. // address, i.e. the split and the comma-joined representations agree.
  20219. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20220. "Host: localhost\r\n"
  20221. "X-Forwarded-For: 1.2.3.4\r\n"
  20222. "X-Forwarded-For: 198.51.100.23\r\n"
  20223. "X-Forwarded-For: 192.0.2.45\r\n"
  20224. "Connection: close\r\n"
  20225. "\r\n";
  20226. out.clear();
  20227. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20228. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20229. EXPECT_EQ(observed_xff_count, 3U);
  20230. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20231. }
  20232. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20233. // crash the server (it used to call front() on an empty vector inside
  20234. // get_client_ip). The connection-level remote address must be retained instead.
  20235. static void run_malformed_xff_test(const std::string &xff_value) {
  20236. Server svr;
  20237. svr.set_trusted_proxies({"192.0.2.45"});
  20238. std::string observed_remote_addr;
  20239. svr.Get("/ip", [&](const Request &req, Response &res) {
  20240. observed_remote_addr = req.remote_addr;
  20241. res.set_content("ok", "text/plain");
  20242. });
  20243. int port = 0;
  20244. thread t = thread([&]() {
  20245. port = svr.bind_to_any_port(HOST);
  20246. svr.listen_after_bind();
  20247. });
  20248. auto se = detail::scope_exit([&] {
  20249. svr.stop();
  20250. t.join();
  20251. ASSERT_FALSE(svr.is_running());
  20252. });
  20253. svr.wait_until_ready();
  20254. Client cli(HOST, port);
  20255. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20257. EXPECT_EQ(StatusCode::OK_200, res->status);
  20258. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20259. observed_remote_addr == "127.0.0.1");
  20260. }
  20261. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20262. run_malformed_xff_test("");
  20263. }
  20264. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20265. run_malformed_xff_test(",");
  20266. }
  20267. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20268. run_malformed_xff_test(", , ,");
  20269. }
  20270. // The same rule applies to Accept: a request whose acceptable types are spread
  20271. // over several field lines must be negotiated against all of them.
  20272. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20273. // case-insensitive connection options. Comparing the whole field value against
  20274. // one option misses a client that sends several of them, and misses every
  20275. // casing but the one written in the comparison.
  20276. //
  20277. // Sends req, reads the response, then reuses the same socket for a second
  20278. // request to find out whether the server kept the connection.
  20279. static void probe_connection_reuse(int port, const std::string &req,
  20280. bool *announced_close, bool *reusable) {
  20281. auto error = Error::Success;
  20282. auto sock = detail::create_client_socket(
  20283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20284. /*connection_timeout_sec=*/5, 0,
  20285. /*read_timeout_sec=*/1, 0,
  20286. /*write_timeout_sec=*/5, 0, std::string(), error);
  20287. ASSERT_NE(sock, INVALID_SOCKET);
  20288. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20289. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20290. "Host: localhost\r\n"
  20291. "Connection: close\r\n"
  20292. "\r\n";
  20293. std::string first_response;
  20294. std::string second_response;
  20295. detail::process_client_socket(
  20296. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20297. [&](Stream &strm) {
  20298. if (strm.write(req.data(), req.size()) !=
  20299. static_cast<ssize_t>(req.size())) {
  20300. return false;
  20301. }
  20302. char buf[512];
  20303. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20304. // Headers plus the two-byte body of the handler below
  20305. while (reader.getline()) {
  20306. first_response += reader.ptr();
  20307. if (first_response.find("ok") != std::string::npos) { break; }
  20308. }
  20309. if (strm.write(second.data(), second.size()) !=
  20310. static_cast<ssize_t>(second.size())) {
  20311. return true;
  20312. }
  20313. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20314. while (reader2.getline()) {
  20315. second_response += reader2.ptr();
  20316. if (second_response.find("ok") != std::string::npos) { break; }
  20317. }
  20318. return true;
  20319. });
  20320. *announced_close =
  20321. first_response.find("Connection: close") != std::string::npos;
  20322. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20323. }
  20324. class ConnectionTokenTest : public ::testing::Test {
  20325. protected:
  20326. void SetUp() override {
  20327. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20328. res.set_content("ok", "text/plain");
  20329. });
  20330. port_ = svr_.bind_to_any_port(HOST);
  20331. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20332. svr_.wait_until_ready();
  20333. }
  20334. void TearDown() override {
  20335. svr_.stop();
  20336. if (thread_.joinable()) { thread_.join(); }
  20337. }
  20338. Server svr_;
  20339. int port_ = 0;
  20340. thread thread_;
  20341. };
  20342. // "close" alongside another option still closes the connection, and the
  20343. // response says so rather than leaving the peer to discover it.
  20344. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20345. bool announced_close = false;
  20346. bool reusable = true;
  20347. probe_connection_reuse(port_,
  20348. "GET /keepalive HTTP/1.1\r\n"
  20349. "Host: localhost\r\n"
  20350. "Connection: keep-alive, close\r\n"
  20351. "\r\n",
  20352. &announced_close, &reusable);
  20353. EXPECT_TRUE(announced_close);
  20354. EXPECT_FALSE(reusable);
  20355. }
  20356. // "close" split over two field lines is the same list, so it is honored too.
  20357. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20358. bool announced_close = false;
  20359. bool reusable = true;
  20360. probe_connection_reuse(port_,
  20361. "GET /keepalive HTTP/1.1\r\n"
  20362. "Host: localhost\r\n"
  20363. "Connection: keep-alive\r\n"
  20364. "Connection: close\r\n"
  20365. "\r\n",
  20366. &announced_close, &reusable);
  20367. EXPECT_TRUE(announced_close);
  20368. EXPECT_FALSE(reusable);
  20369. }
  20370. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20371. // keep-alive in the spelling everyone actually sends keeps its connection.
  20372. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20373. bool announced_close = false;
  20374. bool reusable = false;
  20375. probe_connection_reuse(port_,
  20376. "GET /keepalive HTTP/1.0\r\n"
  20377. "Host: localhost\r\n"
  20378. "Connection: keep-alive\r\n"
  20379. "\r\n",
  20380. &announced_close, &reusable);
  20381. EXPECT_FALSE(announced_close);
  20382. EXPECT_TRUE(reusable);
  20383. }
  20384. // A token the value merely contains is not the token itself.
  20385. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20386. bool announced_close = false;
  20387. bool reusable = false;
  20388. probe_connection_reuse(port_,
  20389. "GET /keepalive HTTP/1.1\r\n"
  20390. "Host: localhost\r\n"
  20391. "Connection: notclose\r\n"
  20392. "\r\n",
  20393. &announced_close, &reusable);
  20394. EXPECT_FALSE(announced_close);
  20395. EXPECT_TRUE(reusable);
  20396. }
  20397. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20398. Server svr;
  20399. std::vector<std::string> observed_types;
  20400. svr.Get("/", [&](const Request &req, Response &res) {
  20401. observed_types = req.accept_content_types;
  20402. res.set_content("ok", "text/plain");
  20403. });
  20404. auto port = svr.bind_to_any_port(HOST);
  20405. thread t = thread([&]() { svr.listen_after_bind(); });
  20406. auto se = detail::scope_exit([&] {
  20407. svr.stop();
  20408. t.join();
  20409. ASSERT_FALSE(svr.is_running());
  20410. });
  20411. svr.wait_until_ready();
  20412. Client cli(HOST, port);
  20413. Headers headers;
  20414. headers.emplace("Accept", "text/plain;q=0.5");
  20415. headers.emplace("Accept", "application/json");
  20416. auto res = cli.Get("/", headers);
  20417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20418. EXPECT_EQ(StatusCode::OK_200, res->status);
  20419. // Sorted by q-value, so the second field line's type comes first
  20420. ASSERT_EQ(2U, observed_types.size());
  20421. EXPECT_EQ("application/json", observed_types[0]);
  20422. EXPECT_EQ("text/plain", observed_types[1]);
  20423. }
  20424. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20425. // empty field line must not contribute a bare comma to the combined value.
  20426. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20427. Server svr;
  20428. std::vector<std::string> observed_types;
  20429. svr.Get("/", [&](const Request &req, Response &res) {
  20430. observed_types = req.accept_content_types;
  20431. res.set_content("ok", "text/plain");
  20432. });
  20433. auto port = svr.bind_to_any_port(HOST);
  20434. thread t = thread([&]() { svr.listen_after_bind(); });
  20435. auto se = detail::scope_exit([&] {
  20436. svr.stop();
  20437. t.join();
  20438. ASSERT_FALSE(svr.is_running());
  20439. });
  20440. svr.wait_until_ready();
  20441. // Empty first field line, then a real one
  20442. std::string raw_req = "GET / HTTP/1.1\r\n"
  20443. "Host: localhost\r\n"
  20444. "Accept:\r\n"
  20445. "Accept: application/json\r\n"
  20446. "Connection: close\r\n"
  20447. "\r\n";
  20448. std::string out;
  20449. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20450. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20451. ASSERT_EQ(1U, observed_types.size());
  20452. EXPECT_EQ("application/json", observed_types[0]);
  20453. }
  20454. // The skip in get_combined_header_value() is what keeps an empty field line
  20455. // from contributing a bare comma. Only a trailing empty field line exercises
  20456. // it: a leading one is already covered by the "combined is still empty" check,
  20457. // and parse_accept_header() now ignores the empty element either way, so the
  20458. // request-level test above can no longer tell the two apart.
  20459. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20460. Headers headers;
  20461. headers.emplace("Accept", "text/html");
  20462. headers.emplace("Accept", "");
  20463. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20464. headers.clear();
  20465. headers.emplace("Accept", "");
  20466. headers.emplace("Accept", "application/json");
  20467. EXPECT_EQ("application/json",
  20468. detail::get_combined_header_value(headers, "Accept"));
  20469. }
  20470. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20471. // An encoding offered on a later Accept-Encoding field line is still offered.
  20472. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20473. Server svr;
  20474. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20475. res.set_content(std::string(1024, 'x'), "text/plain");
  20476. });
  20477. auto port = svr.bind_to_any_port(HOST);
  20478. thread t = thread([&]() { svr.listen_after_bind(); });
  20479. auto se = detail::scope_exit([&] {
  20480. svr.stop();
  20481. t.join();
  20482. ASSERT_FALSE(svr.is_running());
  20483. });
  20484. svr.wait_until_ready();
  20485. Client cli(HOST, port);
  20486. cli.set_decompress(false);
  20487. Headers headers;
  20488. headers.emplace("Accept-Encoding", "identity");
  20489. headers.emplace("Accept-Encoding", "gzip");
  20490. auto res = cli.Get("/", headers);
  20491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20492. EXPECT_EQ(StatusCode::OK_200, res->status);
  20493. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20494. }
  20495. #endif
  20496. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20497. // Transfer-Encoding is not its body.
  20498. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20499. Server svr;
  20500. svr.set_payload_max_length(8);
  20501. svr.Post("/test", [](const Request &, Response &res) {
  20502. res.set_content("ok", "text/plain");
  20503. });
  20504. auto port = svr.bind_to_any_port(HOST);
  20505. ASSERT_GT(port, 0);
  20506. thread t = thread([&] { svr.listen_after_bind(); });
  20507. auto se = detail::scope_exit([&] {
  20508. svr.stop();
  20509. t.join();
  20510. ASSERT_FALSE(svr.is_running());
  20511. });
  20512. svr.wait_until_ready();
  20513. std::string resp;
  20514. ASSERT_TRUE(send_request(1,
  20515. "POST /test HTTP/1.1\r\n"
  20516. "Host: localhost\r\n"
  20517. "Connection: close\r\n"
  20518. "\r\n" +
  20519. std::string(16, 'X'),
  20520. &resp, port));
  20521. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20522. }
  20523. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20524. Server svr;
  20525. svr.Post("/post", [&](const Request &req, Response &res) {
  20526. res.set_content(req.body, "text/plain");
  20527. });
  20528. svr.Put("/put", [&](const Request &req, Response &res) {
  20529. res.set_content(req.body, "text/plain");
  20530. });
  20531. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20532. res.set_content(req.body, "text/plain");
  20533. });
  20534. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20535. res.set_content(req.body, "text/plain");
  20536. });
  20537. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20538. auto se = detail::scope_exit([&] {
  20539. svr.stop();
  20540. t.join();
  20541. ASSERT_FALSE(svr.is_running());
  20542. });
  20543. svr.wait_until_ready();
  20544. std::string resp;
  20545. // POST without Content-Length
  20546. ASSERT_TRUE(send_request(5,
  20547. "POST /post HTTP/1.1\r\n"
  20548. "Host: localhost\r\n"
  20549. "Connection: close\r\n"
  20550. "\r\n",
  20551. &resp));
  20552. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20553. // PUT without Content-Length
  20554. resp.clear();
  20555. ASSERT_TRUE(send_request(5,
  20556. "PUT /put HTTP/1.1\r\n"
  20557. "Host: localhost\r\n"
  20558. "Connection: close\r\n"
  20559. "\r\n",
  20560. &resp));
  20561. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20562. // PATCH without Content-Length
  20563. resp.clear();
  20564. ASSERT_TRUE(send_request(5,
  20565. "PATCH /patch HTTP/1.1\r\n"
  20566. "Host: localhost\r\n"
  20567. "Connection: close\r\n"
  20568. "\r\n",
  20569. &resp));
  20570. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20571. // DELETE without Content-Length
  20572. resp.clear();
  20573. ASSERT_TRUE(send_request(5,
  20574. "DELETE /delete HTTP/1.1\r\n"
  20575. "Host: localhost\r\n"
  20576. "Connection: close\r\n"
  20577. "\r\n",
  20578. &resp));
  20579. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20580. }
  20581. //==============================================================================
  20582. // open_stream() Tests
  20583. //==============================================================================
  20584. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20585. std::string result;
  20586. char buf[8192];
  20587. ssize_t n;
  20588. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20589. result.append(buf, static_cast<size_t>(n));
  20590. }
  20591. return result;
  20592. }
  20593. // Mock stream for unit tests
  20594. class MockStream : public Stream {
  20595. public:
  20596. std::string data;
  20597. size_t pos = 0;
  20598. ssize_t error_after = -1; // -1 = no error
  20599. explicit MockStream(const std::string &d, ssize_t err = -1)
  20600. : data(d), error_after(err) {}
  20601. bool is_readable() const override { return true; }
  20602. bool wait_readable() const override { return true; }
  20603. bool wait_writable() const override { return true; }
  20604. ssize_t read(char *ptr, size_t size) override {
  20605. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20606. if (pos >= data.size()) return 0;
  20607. size_t limit =
  20608. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20609. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20610. std::memcpy(ptr, data.data() + pos, to_read);
  20611. pos += to_read;
  20612. return static_cast<ssize_t>(to_read);
  20613. }
  20614. ssize_t write(const char *, size_t) override { return -1; }
  20615. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20616. ip = "127.0.0.1";
  20617. port = 0;
  20618. }
  20619. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20620. ip = "127.0.0.1";
  20621. port = 0;
  20622. }
  20623. socket_t socket() const override { return INVALID_SOCKET; }
  20624. time_t duration() const override { return 0; }
  20625. };
  20626. TEST(StreamHandleTest, Basic) {
  20627. ClientImpl::StreamHandle handle;
  20628. EXPECT_FALSE(handle.is_valid());
  20629. handle.response = detail::make_unique<Response>();
  20630. handle.error = Error::Connection;
  20631. EXPECT_FALSE(handle.is_valid());
  20632. handle.error = Error::Success;
  20633. EXPECT_TRUE(handle.is_valid());
  20634. }
  20635. TEST(BodyReaderTest, Basic) {
  20636. MockStream stream("Hello, World!");
  20637. detail::BodyReader reader;
  20638. reader.stream = &stream;
  20639. reader.content_length = 13;
  20640. char buf[32];
  20641. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20642. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20643. EXPECT_TRUE(reader.eof);
  20644. }
  20645. TEST(BodyReaderTest, NoStream) {
  20646. detail::BodyReader reader;
  20647. char buf[32];
  20648. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20649. EXPECT_EQ(Error::Connection, reader.last_error);
  20650. }
  20651. TEST(BodyReaderTest, Error) {
  20652. MockStream stream("Hello, World!", 5);
  20653. detail::BodyReader reader;
  20654. reader.stream = &stream;
  20655. reader.content_length = 13;
  20656. char buf[32];
  20657. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20658. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20659. EXPECT_EQ(Error::Read, reader.last_error);
  20660. }
  20661. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20662. // Mock-based StreamHandle tests relying on private internals are removed.
  20663. class OpenStreamTest : public ::testing::Test {
  20664. protected:
  20665. void SetUp() override {
  20666. svr_.Get("/hello", [](const Request &, Response &res) {
  20667. res.set_content("Hello World!", "text/plain");
  20668. });
  20669. svr_.Get("/large", [](const Request &, Response &res) {
  20670. res.set_content(std::string(10000, 'X'), "text/plain");
  20671. });
  20672. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20673. res.set_content("Hello World!", "image/jpeg");
  20674. res.set_header("Content-Encoding", "UTF-8");
  20675. });
  20676. svr_.Get("/chunked", [](const Request &, Response &res) {
  20677. res.set_chunked_content_provider("text/plain",
  20678. [](size_t offset, DataSink &sink) {
  20679. if (offset < 15) {
  20680. sink.write("chunk", 5);
  20681. return true;
  20682. }
  20683. sink.done();
  20684. return true;
  20685. });
  20686. });
  20687. svr_.Get("/compressible", [](const Request &, Response &res) {
  20688. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20689. DataSink &sink) {
  20690. if (offset < 100 * 1024) {
  20691. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20692. sink.write(chunk.data(), chunk.size());
  20693. return true;
  20694. }
  20695. sink.done();
  20696. return true;
  20697. });
  20698. });
  20699. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20700. [](const Request & /*req*/, Response &res) {
  20701. auto i = new int(0);
  20702. res.set_header("Trailer", "Content-Length, X-Allowed");
  20703. res.set_chunked_content_provider(
  20704. "text/plain",
  20705. [i](size_t /*offset*/, DataSink &sink) {
  20706. switch (*i) {
  20707. case 0: sink.os << "123"; break;
  20708. case 1: sink.os << "456"; break;
  20709. case 2: sink.os << "789"; break;
  20710. case 3: {
  20711. sink.done_with_trailer(
  20712. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20713. } break;
  20714. }
  20715. (*i)++;
  20716. return true;
  20717. },
  20718. [i](bool success) {
  20719. EXPECT_TRUE(success);
  20720. delete i;
  20721. });
  20722. });
  20723. // Echo headers endpoint for header-related tests
  20724. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20725. std::string body;
  20726. for (const auto &h : req.headers) {
  20727. body.append(h.first);
  20728. body.push_back(':');
  20729. body.append(h.second);
  20730. body.push_back('\n');
  20731. }
  20732. res.set_content(body, "text/plain");
  20733. });
  20734. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20735. std::string body;
  20736. for (const auto &h : req.headers) {
  20737. body.append(h.first);
  20738. body.push_back(':');
  20739. body.append(h.second);
  20740. body.push_back('\n');
  20741. }
  20742. res.set_content(body, "text/plain");
  20743. });
  20744. port_ = svr_.bind_to_any_port("127.0.0.1");
  20745. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20746. svr_.wait_until_ready();
  20747. }
  20748. void TearDown() override {
  20749. svr_.stop();
  20750. if (thread_.joinable()) thread_.join();
  20751. }
  20752. Server svr_;
  20753. std::thread thread_;
  20754. int port_ = 0;
  20755. };
  20756. TEST_F(OpenStreamTest, Basic) {
  20757. Client cli("127.0.0.1", port_);
  20758. auto handle = cli.open_stream("GET", "/hello");
  20759. EXPECT_TRUE(handle.is_valid());
  20760. EXPECT_EQ("Hello World!", read_all(handle));
  20761. }
  20762. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20763. Client cli("127.0.0.1", port_);
  20764. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20765. ASSERT_TRUE(handle.is_valid());
  20766. EXPECT_EQ("Hello World!", read_all(handle));
  20767. }
  20768. TEST_F(OpenStreamTest, SmallBuffer) {
  20769. Client cli("127.0.0.1", port_);
  20770. auto handle = cli.open_stream("GET", "/hello");
  20771. std::string result;
  20772. char buf[4];
  20773. ssize_t n;
  20774. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20775. result.append(buf, static_cast<size_t>(n));
  20776. EXPECT_EQ("Hello World!", result);
  20777. }
  20778. TEST_F(OpenStreamTest, DefaultHeaders) {
  20779. Client cli("127.0.0.1", port_);
  20780. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20781. {
  20782. auto handle = cli.open_stream("GET", "/echo-headers");
  20783. ASSERT_TRUE(handle.is_valid());
  20784. auto body = read_all(handle);
  20785. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20786. std::string::npos);
  20787. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20788. std::string::npos);
  20789. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20790. }
  20791. // open_stream POST with body and no explicit content_type should NOT add
  20792. // text/plain Content-Type (behavior differs from non-streaming path), but
  20793. // should include Content-Length
  20794. {
  20795. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20796. ASSERT_TRUE(handle.is_valid());
  20797. auto body = read_all(handle);
  20798. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20799. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20800. }
  20801. // open_stream POST with explicit Content-Type should preserve it
  20802. {
  20803. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20804. {{"Content-Type", "application/custom"}},
  20805. "{}", "application/custom");
  20806. ASSERT_TRUE(handle.is_valid());
  20807. auto body = read_all(handle);
  20808. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20809. }
  20810. // User-specified User-Agent must not be overwritten for stream API
  20811. {
  20812. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20813. {{"User-Agent", "MyAgent/1.2"}});
  20814. ASSERT_TRUE(handle.is_valid());
  20815. auto body = read_all(handle);
  20816. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20817. }
  20818. }
  20819. TEST_F(OpenStreamTest, Large) {
  20820. Client cli("127.0.0.1", port_);
  20821. auto handle = cli.open_stream("GET", "/large");
  20822. EXPECT_EQ(10000u, read_all(handle).size());
  20823. }
  20824. TEST_F(OpenStreamTest, ConnectionError) {
  20825. Client cli("127.0.0.1", 9999);
  20826. auto handle = cli.open_stream("GET", "/hello");
  20827. EXPECT_FALSE(handle.is_valid());
  20828. }
  20829. TEST_F(OpenStreamTest, Chunked) {
  20830. Client cli("127.0.0.1", port_);
  20831. auto handle = cli.open_stream("GET", "/chunked");
  20832. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20833. "Transfer-Encoding") == "chunked");
  20834. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20835. }
  20836. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20837. Client cli("127.0.0.1", port_);
  20838. auto handle =
  20839. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20840. ASSERT_TRUE(handle.is_valid());
  20841. // Consume body to allow trailers to be received/parsed
  20842. auto body = read_all(handle);
  20843. // Explicitly parse trailers (ensure trailers are available for assertion)
  20844. handle.parse_trailers_if_needed();
  20845. EXPECT_EQ(std::string("123456789"), body);
  20846. // The response should include a Trailer header declaring both names
  20847. ASSERT_TRUE(handle.response);
  20848. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20849. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20850. handle.response->get_header_value("Trailer"));
  20851. // Prohibited trailer must not be present
  20852. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20853. // Allowed trailer should be present
  20854. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20855. EXPECT_EQ(std::string("yes"),
  20856. handle.response->get_trailer_value("X-Allowed"));
  20857. // Verify trailers are NOT present as regular headers
  20858. EXPECT_EQ(std::string(""),
  20859. handle.response->get_header_value("Content-Length"));
  20860. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20861. }
  20862. // Accepts one connection on an OS-assigned port, which it hands over through
  20863. // port_promise, reads the request head and sends back response. after_send,
  20864. // if given, runs on the connection before it is closed.
  20865. static std::thread
  20866. serve_single_response(std::promise<int> &port_promise,
  20867. const std::string &response,
  20868. std::function<void(socket_t)> after_send = nullptr) {
  20869. return std::thread([&port_promise, response, after_send] {
  20870. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20871. default_socket_options(srv);
  20872. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20874. sockaddr_in addr{};
  20875. addr.sin_family = AF_INET;
  20876. addr.sin_port = htons(0); // Let OS assign a free port
  20877. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20878. int opt = 1;
  20879. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20880. #ifdef _WIN32
  20881. reinterpret_cast<const char *>(&opt),
  20882. #else
  20883. &opt,
  20884. #endif
  20885. sizeof(opt));
  20886. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20887. ::listen(srv, 1) != 0) {
  20888. port_promise.set_value(-1);
  20889. detail::close_socket(srv);
  20890. return;
  20891. }
  20892. socklen_t addr_len = sizeof(addr);
  20893. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20894. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20895. sockaddr_in cli_addr{};
  20896. socklen_t cli_len = sizeof(cli_addr);
  20897. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20898. if (cli != INVALID_SOCKET) {
  20899. // Read the complete HTTP request (until the blank line that terminates
  20900. // headers) before sending the response. If the server closes the socket
  20901. // while the client's request data is still unread in the kernel receive
  20902. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20903. // connection on both sides: it discards the client's receive buffer
  20904. // (which already holds our response) and causes any in-progress write on
  20905. // the client to fail with ECONNRESET. Reading all request data first
  20906. // ensures close() emits a graceful FIN.
  20907. {
  20908. char rbuf[256];
  20909. std::string req;
  20910. while (req.find("\r\n\r\n") == std::string::npos) {
  20911. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20912. if (n <= 0) { break; }
  20913. req.append(rbuf, static_cast<size_t>(n));
  20914. }
  20915. }
  20916. ::send(cli,
  20917. #ifdef _WIN32
  20918. static_cast<const char *>(response.c_str()),
  20919. static_cast<int>(response.size()),
  20920. #else
  20921. response.c_str(), response.size(),
  20922. #endif
  20923. 0);
  20924. if (after_send) { after_send(cli); }
  20925. detail::close_socket(cli);
  20926. }
  20927. detail::close_socket(srv);
  20928. });
  20929. }
  20930. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20931. #ifndef _WIN32
  20932. signal(SIGPIPE, SIG_IGN);
  20933. #endif
  20934. std::promise<int> port_promise;
  20935. auto port_future = port_promise.get_future();
  20936. auto server_thread =
  20937. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20938. "Content-Type: text/plain\r\n"
  20939. "Content-Length: not-a-number\r\n"
  20940. "Connection: close\r\n"
  20941. "\r\n"
  20942. "hello");
  20943. auto port = port_future.get();
  20944. ASSERT_GT(port, 0);
  20945. Client cli("127.0.0.1", port);
  20946. auto handle = cli.open_stream("GET", "/");
  20947. EXPECT_FALSE(handle.is_valid());
  20948. server_thread.join();
  20949. }
  20950. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20951. #ifndef _WIN32
  20952. signal(SIGPIPE, SIG_IGN);
  20953. #endif
  20954. std::promise<int> port_promise;
  20955. auto port_future = port_promise.get_future();
  20956. auto server_thread = serve_single_response(
  20957. port_promise, "HTTP/1.1 200 OK\r\n"
  20958. "Content-Type: text/plain\r\n"
  20959. "Content-Length: 99999999999999999999999999\r\n"
  20960. "Connection: close\r\n"
  20961. "\r\n"
  20962. "hello");
  20963. auto port = port_future.get();
  20964. ASSERT_GT(port, 0);
  20965. // Historically std::stoull would throw std::out_of_range here and crash
  20966. // the process, then parsing silently clamped to a bogus framing length and
  20967. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20968. // so the stream fails to open, matching the not-a-number case above. The
  20969. // process still must NOT terminate.
  20970. Client cli("127.0.0.1", port);
  20971. auto handle = cli.open_stream("GET", "/");
  20972. EXPECT_FALSE(handle.is_valid());
  20973. server_thread.join();
  20974. }
  20975. #ifndef _WIN32
  20976. // As above for the body of a streamed request: a send() cut short by the write
  20977. // timeout must not leave the rest of the body unsent.
  20978. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20979. signal(SIGPIPE, SIG_IGN);
  20980. Server svr;
  20981. svr.set_socket_options([](socket_t sock) {
  20982. int size = 8192;
  20983. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20984. reinterpret_cast<const char *>(&size), sizeof(size));
  20985. });
  20986. svr.Post("/size", [](const Request &, Response &res,
  20987. const ContentReader &content_reader) {
  20988. // Outlast the client's write timeout before reading the body.
  20989. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20990. size_t received = 0;
  20991. content_reader([&](const char *, size_t len) {
  20992. received += len;
  20993. return true;
  20994. });
  20995. res.set_content(std::to_string(received), "text/plain");
  20996. });
  20997. auto port = svr.bind_to_any_port(HOST);
  20998. std::thread t([&]() { svr.listen_after_bind(); });
  20999. auto se = detail::scope_exit([&] {
  21000. svr.stop();
  21001. t.join();
  21002. });
  21003. svr.wait_until_ready();
  21004. Client cli(HOST, port);
  21005. cli.set_write_timeout(0, 500000);
  21006. cli.set_socket_options([](socket_t sock) {
  21007. int size = 8192;
  21008. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21009. reinterpret_cast<const char *>(&size), sizeof(size));
  21010. });
  21011. const std::string body(4 * 1024 * 1024, 'A');
  21012. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21013. "application/octet-stream");
  21014. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21015. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21016. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21017. }
  21018. #endif
  21019. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21020. std::promise<void> slow_started;
  21021. auto slow_started_future = slow_started.get_future();
  21022. Server svr;
  21023. svr.Get("/slow", [&](const Request &, Response &res) {
  21024. slow_started.set_value();
  21025. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21026. res.set_content("slow", "text/plain");
  21027. });
  21028. svr.Get("/fast", [](const Request &, Response &res) {
  21029. res.set_content("fast", "text/plain");
  21030. });
  21031. auto port = svr.bind_to_any_port(HOST);
  21032. std::thread t([&]() { svr.listen_after_bind(); });
  21033. auto se = detail::scope_exit([&] {
  21034. svr.stop();
  21035. t.join();
  21036. });
  21037. svr.wait_until_ready();
  21038. Client cli(HOST, port);
  21039. std::string slow_body;
  21040. std::thread slow_thread([&] {
  21041. auto res = cli.Get("/slow");
  21042. if (res) { slow_body = res->body; }
  21043. });
  21044. slow_started_future.wait();
  21045. auto result = stream::Get(cli, "/fast");
  21046. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21047. slow_thread.join();
  21048. EXPECT_EQ("slow", slow_body);
  21049. EXPECT_EQ("fast", fast_body);
  21050. }
  21051. // Serves `response` to the single request `fn` makes with a fresh client.
  21052. template <typename Fn>
  21053. static void with_single_response(const std::string &response, Fn fn) {
  21054. #ifndef _WIN32
  21055. signal(SIGPIPE, SIG_IGN);
  21056. #endif
  21057. std::promise<int> port_promise;
  21058. auto port_future = port_promise.get_future();
  21059. auto server_thread = serve_single_response(port_promise, response);
  21060. auto se = detail::scope_exit([&] { server_thread.join(); });
  21061. auto port = port_future.get();
  21062. ASSERT_GT(port, 0);
  21063. Client cli("127.0.0.1", port);
  21064. fn(cli);
  21065. }
  21066. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21067. // too, also in a build without the decoder for the advertised coding.
  21068. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21069. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21070. const auto response = "HTTP/1.1 200 OK\r\n"
  21071. "Content-Encoding: gzip\r\n"
  21072. "Content-Length: " +
  21073. std::to_string(gzipped.size()) +
  21074. "\r\n"
  21075. "Connection: close\r\n\r\n" +
  21076. gzipped;
  21077. with_single_response(response, [&](Client &cli) {
  21078. cli.set_decompress(false);
  21079. auto handle = cli.open_stream("GET", "/");
  21080. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21081. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21082. EXPECT_EQ(gzipped, read_all(handle));
  21083. EXPECT_FALSE(handle.has_read_error());
  21084. });
  21085. with_single_response(response, [&](Client &cli) {
  21086. cli.set_decompress(false);
  21087. auto res = stream::Get(cli, "/", 7);
  21088. ASSERT_TRUE(res) << to_string(res.error());
  21089. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21090. EXPECT_EQ(gzipped, res.read_all());
  21091. EXPECT_FALSE(res.has_read_error());
  21092. });
  21093. }
  21094. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21095. // Neither Content-Length nor chunked: the body ends at the close
  21096. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21097. "Connection: close\r\n"
  21098. "\r\n"
  21099. "hello";
  21100. with_single_response(close_delimited, [](Client &cli) {
  21101. auto handle = cli.open_stream("GET", "/");
  21102. ASSERT_TRUE(handle.is_valid());
  21103. EXPECT_EQ("hello", read_all(handle));
  21104. EXPECT_FALSE(handle.has_read_error());
  21105. });
  21106. // A close before the end of the Content-Length is still an error
  21107. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21108. "Content-Length: 10\r\n"
  21109. "\r\n"
  21110. "hello";
  21111. with_single_response(short_content_length, [](Client &cli) {
  21112. auto handle = cli.open_stream("GET", "/");
  21113. ASSERT_TRUE(handle.is_valid());
  21114. read_all(handle);
  21115. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21116. });
  21117. // So is a close before the last chunk
  21118. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21119. "Transfer-Encoding: chunked\r\n"
  21120. "\r\n"
  21121. "5\r\nhello\r\n";
  21122. with_single_response(short_chunked, [](Client &cli) {
  21123. auto handle = cli.open_stream("GET", "/");
  21124. ASSERT_TRUE(handle.is_valid());
  21125. read_all(handle);
  21126. EXPECT_TRUE(handle.has_read_error());
  21127. });
  21128. }
  21129. #ifdef CPPHTTPLIB_SSL_ENABLED
  21130. // Serves `response` to one request, then closes with or without a close_notify
  21131. template <typename Fn>
  21132. static void with_single_tls_response(const std::string &response,
  21133. bool close_notify, Fn fn) {
  21134. #ifndef _WIN32
  21135. signal(SIGPIPE, SIG_IGN);
  21136. #endif
  21137. std::promise<int> port_promise;
  21138. auto port_future = port_promise.get_future();
  21139. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21140. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21141. default_socket_options(srv);
  21142. sockaddr_in addr{};
  21143. addr.sin_family = AF_INET;
  21144. addr.sin_port = htons(0);
  21145. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21146. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21147. ::listen(srv, 1) != 0) {
  21148. port_promise.set_value(-1);
  21149. detail::close_socket(srv);
  21150. return;
  21151. }
  21152. socklen_t addr_len = sizeof(addr);
  21153. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21154. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21155. auto cli = ::accept(srv, nullptr, nullptr);
  21156. if (cli != INVALID_SOCKET) {
  21157. auto ctx = tls::create_server_context();
  21158. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21159. nullptr);
  21160. auto session = tls::create_session(ctx, cli);
  21161. tls::TlsError err;
  21162. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21163. // The request head first, so that closing the socket sends a FIN
  21164. // rather than an RST for the unread bytes.
  21165. std::string req;
  21166. char buf[256];
  21167. while (req.find("\r\n\r\n") == std::string::npos) {
  21168. auto n = tls::read(session, buf, sizeof(buf), err);
  21169. if (n <= 0) { break; }
  21170. req.append(buf, static_cast<size_t>(n));
  21171. }
  21172. size_t sent = 0;
  21173. while (sent < response.size()) {
  21174. auto n = tls::write(session, response.data() + sent,
  21175. response.size() - sent, err);
  21176. if (n <= 0) { break; }
  21177. sent += static_cast<size_t>(n);
  21178. }
  21179. if (close_notify) { tls::shutdown(session, true); }
  21180. }
  21181. tls::free_session(session);
  21182. detail::close_socket(cli);
  21183. tls::free_context(ctx);
  21184. }
  21185. detail::close_socket(srv);
  21186. });
  21187. auto se = detail::scope_exit([&] { server_thread.join(); });
  21188. auto port = port_future.get();
  21189. ASSERT_GT(port, 0);
  21190. SSLClient cli("127.0.0.1", port);
  21191. cli.enable_server_certificate_verification(false);
  21192. fn(cli);
  21193. }
  21194. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21195. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21196. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21197. "Connection: close\r\n"
  21198. "\r\n"
  21199. "hello";
  21200. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21201. auto res = cli.Get("/");
  21202. ASSERT_TRUE(res) << to_string(res.error());
  21203. EXPECT_EQ("hello", res->body);
  21204. });
  21205. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21206. auto res = cli.Get("/");
  21207. ASSERT_FALSE(res);
  21208. EXPECT_EQ(Error::Read, res.error());
  21209. });
  21210. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21211. auto handle = cli.open_stream("GET", "/");
  21212. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21213. read_all(handle);
  21214. EXPECT_TRUE(handle.has_read_error());
  21215. });
  21216. // A framed body ends where its framing says, with or without the alert
  21217. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21218. "Content-Length: 5\r\n"
  21219. "Connection: close\r\n"
  21220. "\r\n"
  21221. "hello";
  21222. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21223. auto res = cli.Get("/");
  21224. ASSERT_TRUE(res) << to_string(res.error());
  21225. EXPECT_EQ("hello", res->body);
  21226. });
  21227. }
  21228. #endif
  21229. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21230. const char *responses[] = {
  21231. "HTTP/1.1 103 Early Hints\r\n"
  21232. "Link: </style.css>; rel=preload\r\n"
  21233. "\r\n"
  21234. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21235. "HTTP/1.1 100 Continue\r\n"
  21236. "X-Note: interim\r\n"
  21237. "\r\n"
  21238. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21239. };
  21240. for (auto response : responses) {
  21241. with_single_response(response, [](Client &cli) {
  21242. auto res = cli.Get("/");
  21243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21244. EXPECT_EQ(StatusCode::OK_200, res->status);
  21245. EXPECT_EQ("ok", res->body);
  21246. });
  21247. }
  21248. }
  21249. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21250. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21251. const std::string final_response =
  21252. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21253. std::string interims;
  21254. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21255. interims += interim;
  21256. }
  21257. with_single_response(interims + final_response, [](Client &cli) {
  21258. auto res = cli.Get("/");
  21259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21260. EXPECT_EQ("ok", res->body);
  21261. });
  21262. with_single_response(interims + interim + final_response, [](Client &cli) {
  21263. auto res = cli.Get("/");
  21264. ASSERT_FALSE(res);
  21265. EXPECT_EQ(Error::Read, res.error());
  21266. });
  21267. }
  21268. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21269. #ifndef _WIN32
  21270. signal(SIGPIPE, SIG_IGN);
  21271. #endif
  21272. // The server answers the head without asking for the body. Bytes it then
  21273. // reads on the connection would be taken for the body the request declared.
  21274. auto closed_by_client = false;
  21275. std::promise<int> port_promise;
  21276. auto server_thread = serve_single_response(
  21277. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21278. [&](socket_t sock) {
  21279. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21280. char buf[256];
  21281. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21282. });
  21283. Client cli("127.0.0.1", port_promise.get_future().get());
  21284. cli.set_keep_alive(true);
  21285. cli.set_read_timeout(1, 0);
  21286. // Long enough for the client to send Expect: 100-continue.
  21287. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21289. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21290. cli.Get("/second");
  21291. server_thread.join();
  21292. EXPECT_TRUE(closed_by_client);
  21293. }
  21294. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21295. // Long enough for the client to send Expect: 100-continue
  21296. with_single_response(
  21297. "HTTP/1.1 103 Early Hints\r\n"
  21298. "Link: </style.css>; rel=preload\r\n"
  21299. "\r\n"
  21300. "HTTP/1.1 401 Unauthorized\r\n"
  21301. "Content-Length: 0\r\n\r\n",
  21302. [](Client &cli) {
  21303. cli.set_read_timeout(2, 0);
  21304. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21306. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21307. });
  21308. }
  21309. #ifdef CPPHTTPLIB_SSL_ENABLED
  21310. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21311. #ifndef _WIN32
  21312. signal(SIGPIPE, SIG_IGN);
  21313. #endif
  21314. auto reused = false;
  21315. std::promise<int> port_promise;
  21316. auto server_thread = serve_single_response(
  21317. port_promise,
  21318. "HTTP/1.1 401 Unauthorized\r\n"
  21319. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21320. "Content-Length: 0\r\n\r\n",
  21321. [&](socket_t sock) {
  21322. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21323. char buf[256];
  21324. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21325. });
  21326. Client cli("127.0.0.1", port_promise.get_future().get());
  21327. cli.set_keep_alive(true);
  21328. cli.set_digest_auth("user", "pass");
  21329. cli.set_read_timeout(1, 0);
  21330. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21331. server_thread.join();
  21332. EXPECT_FALSE(reused);
  21333. }
  21334. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21335. // Any other answer to CONNECT would read as the origin's response.
  21336. struct {
  21337. const char *response;
  21338. bool passed_on;
  21339. } cases[] = {
  21340. {"HTTP/1.1 201 Created\r\n"
  21341. "Set-Cookie: session=from-proxy\r\n"
  21342. "Content-Length: 0\r\n\r\n",
  21343. false},
  21344. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21345. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21346. "Content-Length: 0\r\n\r\n",
  21347. true},
  21348. };
  21349. for (const auto &c : cases) {
  21350. std::promise<int> port_promise;
  21351. auto server_thread = serve_single_response(port_promise, c.response);
  21352. SSLClient cli("example.com", 443);
  21353. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21354. auto res = cli.Get("/");
  21355. server_thread.join();
  21356. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21357. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21358. if (res) {
  21359. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21360. }
  21361. }
  21362. }
  21363. #endif
  21364. // Records the client's error logger calls as "error METHOD path", or
  21365. // "error null" for a call without a request
  21366. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21367. return [&log](const Error &err, const Request *req) {
  21368. log.push_back(to_string(err) + " " +
  21369. (req ? req->method + " " + req->path : "null"));
  21370. };
  21371. }
  21372. // A failed request is reported once, with the request the caller made
  21373. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21374. Server svr;
  21375. svr.Get("/big", [](const Request &, Response &res) {
  21376. res.set_content(std::string(100000, 'b'), "text/plain");
  21377. });
  21378. auto port = svr.bind_to_any_port(HOST);
  21379. std::thread t([&]() { svr.listen_after_bind(); });
  21380. auto se = detail::scope_exit([&] {
  21381. svr.stop();
  21382. t.join();
  21383. });
  21384. svr.wait_until_ready();
  21385. Client cli(HOST, port);
  21386. std::vector<std::string> log;
  21387. cli.set_error_logger(record_errors(log));
  21388. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21389. cli.Get("/big", [](const char *, size_t) { return false; });
  21390. EXPECT_EQ(expected, log);
  21391. log.clear();
  21392. cli.Get("/big", [](size_t, size_t) { return false; });
  21393. EXPECT_EQ(expected, log);
  21394. }
  21395. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21396. // Fails while the body is read
  21397. auto broken = [](const Request &, Response &res) {
  21398. res.set_content_provider(10, "text/plain",
  21399. [](size_t, size_t, DataSink &) { return false; });
  21400. };
  21401. Server other;
  21402. other.Get("/broken", broken);
  21403. auto other_port = other.bind_to_any_port(HOST);
  21404. std::thread other_t([&]() { other.listen_after_bind(); });
  21405. auto other_se = detail::scope_exit([&] {
  21406. other.stop();
  21407. other_t.join();
  21408. });
  21409. other.wait_until_ready();
  21410. Server svr;
  21411. svr.Get("/broken", broken);
  21412. svr.Get("/same-origin",
  21413. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21414. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21415. res.set_redirect("http://" + std::string(HOST) + ":" +
  21416. std::to_string(other_port) + "/broken");
  21417. });
  21418. auto port = svr.bind_to_any_port(HOST);
  21419. std::thread t([&]() { svr.listen_after_bind(); });
  21420. auto se = detail::scope_exit([&] {
  21421. svr.stop();
  21422. t.join();
  21423. });
  21424. svr.wait_until_ready();
  21425. Client cli(HOST, port);
  21426. cli.set_follow_location(true);
  21427. std::vector<std::string> log;
  21428. cli.set_error_logger(record_errors(log));
  21429. for (auto path : {"/same-origin", "/cross-origin"}) {
  21430. log.clear();
  21431. auto res = cli.Get(path);
  21432. ASSERT_FALSE(res);
  21433. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21434. log);
  21435. }
  21436. }
  21437. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21438. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21439. std::vector<std::string> log;
  21440. cli.set_error_logger(record_errors(log));
  21441. auto handle = cli.open_stream("GET", "/x");
  21442. EXPECT_FALSE(handle.is_valid());
  21443. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21444. log);
  21445. });
  21446. }
  21447. #ifdef CPPHTTPLIB_SSL_ENABLED
  21448. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21449. // Not a TLS server, so the handshake fails. It waits for a request line in
  21450. // the handshake bytes, so a short read timeout lets it close quickly.
  21451. Server svr;
  21452. svr.set_read_timeout(0, 100000);
  21453. svr.Get("/x", [](const Request &, Response &res) {
  21454. res.set_content("x", "text/plain");
  21455. });
  21456. auto port = svr.bind_to_any_port(HOST);
  21457. std::thread t([&]() { svr.listen_after_bind(); });
  21458. auto se = detail::scope_exit([&] {
  21459. svr.stop();
  21460. t.join();
  21461. });
  21462. svr.wait_until_ready();
  21463. std::vector<std::string> log;
  21464. SSLClient cli(HOST, port);
  21465. cli.enable_server_certificate_verification(false);
  21466. cli.set_error_logger(record_errors(log));
  21467. auto res = cli.Get("/x");
  21468. ASSERT_FALSE(res);
  21469. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21470. log.clear();
  21471. auto handle = cli.open_stream("GET", "/x");
  21472. EXPECT_FALSE(handle.is_valid());
  21473. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21474. log.clear();
  21475. SSLClient no_ca(HOST, port);
  21476. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21477. no_ca.set_error_logger(record_errors(log));
  21478. res = no_ca.Get("/x");
  21479. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21480. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21481. }
  21482. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21483. #ifndef _WIN32
  21484. signal(SIGPIPE, SIG_IGN);
  21485. #endif
  21486. // Refused, answered with a challenge, or closed without an answer
  21487. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21488. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21489. "Content-Length: 0\r\n\r\n",
  21490. ""}) {
  21491. std::promise<int> port_promise;
  21492. auto server_thread = serve_single_response(port_promise, response);
  21493. SSLClient cli("example.com", 443);
  21494. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21495. std::vector<std::string> log;
  21496. cli.set_error_logger(record_errors(log));
  21497. auto res = cli.Get("/");
  21498. server_thread.join();
  21499. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21500. << response;
  21501. }
  21502. }
  21503. #endif
  21504. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21505. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21506. // the chunked coding and drop Content-Length, so a front-end that trusts
  21507. // Content-Length would disagree about where the body ends (response
  21508. // smuggling). The client must reject such a response.
  21509. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21510. for (const char *te : {"chunked", "gzip, chunked"}) {
  21511. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21512. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21513. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21514. "5\r\nhello\r\n0\r\n\r\n";
  21515. with_single_response(response, [&](Client &cli) {
  21516. auto res = cli.Get("/");
  21517. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21518. EXPECT_EQ(Error::Read, res.error()) << te;
  21519. });
  21520. with_single_response(response, [&](Client &cli) {
  21521. auto handle = cli.open_stream("GET", "/");
  21522. EXPECT_FALSE(handle.is_valid()) << te;
  21523. EXPECT_EQ(Error::Read, handle.error) << te;
  21524. });
  21525. }
  21526. }
  21527. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21528. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21529. // closing the connection (unlike a request, which must be rejected).
  21530. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21531. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21532. "Transfer-Encoding: chunked\r\n"
  21533. "Connection: close\r\n"
  21534. "\r\n"
  21535. "5\r\nhello\r\n0\r\n\r\n",
  21536. "HTTP/1.1 200 OK\r\n"
  21537. "Transfer-Encoding: gzip\r\n"
  21538. "Connection: close\r\n"
  21539. "\r\n"
  21540. "hello"}) {
  21541. with_single_response(response, [&](Client &cli) {
  21542. auto res = cli.Get("/");
  21543. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21544. EXPECT_EQ("hello", res->body);
  21545. });
  21546. with_single_response(response, [&](Client &cli) {
  21547. auto handle = cli.open_stream("GET", "/");
  21548. ASSERT_TRUE(handle.is_valid()) << response;
  21549. EXPECT_EQ("hello", read_all(handle));
  21550. });
  21551. }
  21552. }
  21553. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21554. // framing headers describe nothing to read and must not be rejected.
  21555. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21556. const std::string framing = "Content-Length: 5\r\n"
  21557. "Transfer-Encoding: chunked\r\n"
  21558. "Connection: close\r\n"
  21559. "\r\n";
  21560. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21561. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21562. });
  21563. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21564. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21565. });
  21566. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21567. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21568. with_single_response(response, [&](Client &cli) {
  21569. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21570. });
  21571. with_single_response(response, [&](Client &cli) {
  21572. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21573. });
  21574. }
  21575. }
  21576. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21577. // header section, so a stream opened on one has nothing to read, whatever
  21578. // framing or coding headers it carries.
  21579. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21580. struct Case {
  21581. const char *method;
  21582. const char *status;
  21583. };
  21584. // A reader of the declared body reports an early close when nothing
  21585. // follows, and hands back what does.
  21586. struct Framing {
  21587. const char *headers;
  21588. const char *after;
  21589. };
  21590. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21591. Case{"GET", "304 Not Modified"}}) {
  21592. for (const auto &f :
  21593. {Framing{"Content-Length: 5\r\n", ""},
  21594. Framing{"Content-Length: 5\r\n", "hello"},
  21595. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21596. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21597. // Not decoded, so a build without Brotli opens it too
  21598. Framing{"Content-Encoding: br\r\n", ""}}) {
  21599. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21600. "Connection: close\r\n"
  21601. "\r\n" +
  21602. f.after;
  21603. with_single_response(response, [&](Client &cli) {
  21604. auto handle = cli.open_stream(c.method, "/");
  21605. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21606. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21607. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21608. });
  21609. }
  21610. }
  21611. }
  21612. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21613. // response, is faulty framing, so the connection is not reused after it.
  21614. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21615. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21616. "Content-Length: 0\r\n"
  21617. "Transfer-Encoding: chunked\r\n"
  21618. "\r\n"
  21619. "5\r\nhello\r\n0\r\n\r\n",
  21620. "HTTP/1.0 200 Connection established\r\n"
  21621. "Connection: keep-alive\r\n"
  21622. "Transfer-Encoding: chunked\r\n"
  21623. "\r\n"
  21624. "5\r\nhello\r\n0\r\n\r\n"}) {
  21625. with_single_response(response, [&](Client &cli) {
  21626. cli.set_keep_alive(true);
  21627. auto res = cli.Get("/");
  21628. ASSERT_TRUE(res) << response;
  21629. EXPECT_EQ("hello", res->body);
  21630. EXPECT_FALSE(cli.is_socket_open()) << response;
  21631. });
  21632. }
  21633. }
  21634. // A payload max length of 0 means no limit, however the body is framed.
  21635. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21636. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21637. "Transfer-Encoding: chunked\r\n"
  21638. "\r\n"
  21639. "5\r\nhello\r\n0\r\n\r\n",
  21640. "HTTP/1.1 200 OK\r\n"
  21641. "Connection: close\r\n"
  21642. "\r\n"
  21643. "hello"}) {
  21644. with_single_response(response, [&](Client &cli) {
  21645. cli.set_payload_max_length(0);
  21646. auto res = cli.Get("/");
  21647. ASSERT_TRUE(res) << response;
  21648. EXPECT_EQ("hello", res->body) << response;
  21649. });
  21650. }
  21651. }
  21652. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21653. Server svr;
  21654. svr.set_payload_max_length(0);
  21655. svr.Post("/echo", [](const Request &req, Response &res) {
  21656. res.set_content(req.body, "text/plain");
  21657. });
  21658. auto port = svr.bind_to_any_port(HOST);
  21659. thread t = thread([&] { svr.listen_after_bind(); });
  21660. auto se = detail::scope_exit([&] {
  21661. svr.stop();
  21662. t.join();
  21663. ASSERT_FALSE(svr.is_running());
  21664. });
  21665. svr.wait_until_ready();
  21666. Client cli(HOST, port);
  21667. auto res = cli.Post(
  21668. "/echo",
  21669. [](size_t /*offset*/, DataSink &sink) {
  21670. sink.write("hello", 5);
  21671. sink.done();
  21672. return true;
  21673. },
  21674. "text/plain");
  21675. ASSERT_TRUE(res);
  21676. EXPECT_EQ(StatusCode::OK_200, res->status);
  21677. EXPECT_EQ("hello", res->body);
  21678. }
  21679. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21680. TEST_F(OpenStreamTest, Gzip) {
  21681. Client cli("127.0.0.1", port_);
  21682. auto handle = cli.open_stream("GET", "/compressible", {},
  21683. {{"Accept-Encoding", "gzip"}});
  21684. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21685. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21686. }
  21687. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21688. Client cli("127.0.0.1", port_);
  21689. auto handle =
  21690. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21691. {{"Accept-Encoding", "gzip"}});
  21692. ASSERT_TRUE(handle.is_valid());
  21693. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21694. EXPECT_EQ("123456789", read_all(handle));
  21695. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21696. }
  21697. #endif
  21698. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21699. TEST_F(OpenStreamTest, Brotli) {
  21700. Client cli("127.0.0.1", port_);
  21701. auto handle =
  21702. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21703. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21704. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21705. }
  21706. #endif
  21707. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21708. TEST_F(OpenStreamTest, Zstd) {
  21709. Client cli("127.0.0.1", port_);
  21710. auto handle = cli.open_stream("GET", "/compressible", {},
  21711. {{"Accept-Encoding", "zstd"}});
  21712. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21713. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21714. }
  21715. #endif
  21716. #ifdef CPPHTTPLIB_SSL_ENABLED
  21717. class SSLOpenStreamTest : public ::testing::Test {
  21718. protected:
  21719. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21720. void SetUp() override {
  21721. svr_.Get("/hello", [](const Request &, Response &res) {
  21722. res.set_content("Hello SSL World!", "text/plain");
  21723. });
  21724. svr_.Get("/chunked", [](const Request &, Response &res) {
  21725. res.set_chunked_content_provider("text/plain",
  21726. [](size_t offset, DataSink &sink) {
  21727. if (offset < 15) {
  21728. sink.write("chunk", 5);
  21729. return true;
  21730. }
  21731. sink.done();
  21732. return true;
  21733. });
  21734. });
  21735. svr_.Post("/echo", [](const Request &req, Response &res) {
  21736. res.set_content(req.body, req.get_header_value("Content-Type"));
  21737. });
  21738. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21739. std::string body = req.body;
  21740. res.set_chunked_content_provider(
  21741. "text/plain", [body](size_t offset, DataSink &sink) {
  21742. if (offset < body.size()) {
  21743. sink.write(body.data() + offset, body.size() - offset);
  21744. }
  21745. sink.done();
  21746. return true;
  21747. });
  21748. });
  21749. port_ = svr_.bind_to_any_port("127.0.0.1");
  21750. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21751. svr_.wait_until_ready();
  21752. }
  21753. void TearDown() override {
  21754. svr_.stop();
  21755. if (thread_.joinable()) thread_.join();
  21756. }
  21757. SSLServer svr_;
  21758. std::thread thread_;
  21759. int port_ = 0;
  21760. };
  21761. TEST_F(SSLOpenStreamTest, Basic) {
  21762. SSLClient cli("127.0.0.1", port_);
  21763. cli.enable_server_certificate_verification(false);
  21764. auto handle = cli.open_stream("GET", "/hello");
  21765. ASSERT_TRUE(handle.is_valid());
  21766. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21767. }
  21768. TEST_F(SSLOpenStreamTest, Chunked) {
  21769. SSLClient cli("127.0.0.1", port_);
  21770. cli.enable_server_certificate_verification(false);
  21771. auto handle = cli.open_stream("GET", "/chunked");
  21772. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21773. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21774. "Transfer-Encoding") == "chunked");
  21775. auto body = read_all(handle);
  21776. EXPECT_EQ("chunkchunkchunk", body);
  21777. }
  21778. TEST_F(SSLOpenStreamTest, Post) {
  21779. SSLClient cli("127.0.0.1", port_);
  21780. cli.enable_server_certificate_verification(false);
  21781. auto handle =
  21782. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21783. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21784. EXPECT_EQ(200, handle.response->status);
  21785. auto body = read_all(handle);
  21786. EXPECT_EQ("Hello SSL POST", body);
  21787. }
  21788. TEST_F(SSLOpenStreamTest, PostChunked) {
  21789. SSLClient cli("127.0.0.1", port_);
  21790. cli.enable_server_certificate_verification(false);
  21791. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21792. "Chunked SSL Data", "text/plain");
  21793. ASSERT_TRUE(handle.is_valid());
  21794. EXPECT_EQ(200, handle.response->status);
  21795. auto body = read_all(handle);
  21796. EXPECT_EQ("Chunked SSL Data", body);
  21797. }
  21798. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21799. // Content-Length is terminated by the server closing the connection. When the
  21800. // SSL peer sends a close_notify after the body, the client must treat it as a
  21801. // clean EOF and return a successful response rather than an error.
  21802. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21804. ASSERT_TRUE(svr.is_valid());
  21805. svr.set_keep_alive_max_count(1);
  21806. const std::string expected_body = "Hello from connection-close response!";
  21807. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21808. res.set_content_provider("text/plain",
  21809. [&](size_t offset, DataSink &sink) -> bool {
  21810. if (offset < expected_body.size()) {
  21811. sink.write(expected_body.data() + offset,
  21812. expected_body.size() - offset);
  21813. }
  21814. sink.done();
  21815. return true;
  21816. });
  21817. });
  21818. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21819. auto se = detail::scope_exit([&] {
  21820. svr.stop();
  21821. listen_thread.join();
  21822. ASSERT_FALSE(svr.is_running());
  21823. });
  21824. svr.wait_until_ready();
  21825. SSLClient cli(HOST, PORT);
  21826. cli.enable_server_certificate_verification(false);
  21827. auto res = cli.Get("/no-content-length");
  21828. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21829. EXPECT_EQ(StatusCode::OK_200, res->status);
  21830. EXPECT_EQ(expected_body, res->body);
  21831. }
  21832. // Without Content-Length, the full buffer size reaches tls::read().
  21833. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21834. if (sizeof(size_t) <= sizeof(int)) {
  21835. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21836. }
  21837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21838. ASSERT_TRUE(svr.is_valid());
  21839. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21840. res.set_content_provider("text/plain",
  21841. [&](size_t offset, DataSink &sink) -> bool {
  21842. if (offset == 0) { sink.write("Hello", 5); }
  21843. sink.done();
  21844. return true;
  21845. });
  21846. });
  21847. auto port = svr.bind_to_any_port(HOST);
  21848. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21849. auto se = detail::scope_exit([&] {
  21850. svr.stop();
  21851. listen_thread.join();
  21852. });
  21853. svr.wait_until_ready();
  21854. SSLClient cli(HOST, port);
  21855. cli.enable_server_certificate_verification(false);
  21856. auto handle = cli.open_stream("GET", "/no-content-length");
  21857. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21858. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21859. std::unique_ptr<char[]> buf(new char[len]);
  21860. std::string body;
  21861. ssize_t n;
  21862. while ((n = handle.read(buf.get(), len)) > 0) {
  21863. body.append(buf.get(), static_cast<size_t>(n));
  21864. }
  21865. EXPECT_EQ(0, n);
  21866. EXPECT_EQ("Hello", body);
  21867. }
  21868. #endif // CPPHTTPLIB_SSL_ENABLED
  21869. //==============================================================================
  21870. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21871. // results for various scenarios.
  21872. //==============================================================================
  21873. TEST(ParityTest, GetVsOpenStream) {
  21874. Server svr;
  21875. const std::string path = "/parity";
  21876. const std::string content = "Parity test content: hello world";
  21877. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21878. res.set_content(content, "text/plain");
  21879. });
  21880. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21881. auto se = detail::scope_exit([&] {
  21882. svr.stop();
  21883. t.join();
  21884. ASSERT_FALSE(svr.is_running());
  21885. });
  21886. svr.wait_until_ready();
  21887. Client cli(HOST, PORT);
  21888. // Non-stream path
  21889. auto r1 = cli.Get(path);
  21890. ASSERT_TRUE(r1);
  21891. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21892. // Stream path
  21893. auto h = cli.open_stream("GET", path);
  21894. ASSERT_TRUE(h.is_valid());
  21895. EXPECT_EQ(r1->body, read_all(h));
  21896. }
  21897. // Helper to compress data with provided compressor type T
  21898. template <typename Compressor>
  21899. static std::string compress_payload_for_parity(const std::string &in) {
  21900. std::string out;
  21901. Compressor compressor;
  21902. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21903. [&](const char *data, size_t n) {
  21904. out.append(data, n);
  21905. return true;
  21906. });
  21907. EXPECT_TRUE(ok);
  21908. return out;
  21909. }
  21910. // Helper function for compression parity tests
  21911. template <typename Compressor>
  21912. static void test_compression_parity(const std::string &original,
  21913. const std::string &path,
  21914. const std::string &encoding) {
  21915. const std::string compressed =
  21916. compress_payload_for_parity<Compressor>(original);
  21917. Server svr;
  21918. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21919. res.set_content(compressed, "application/octet-stream");
  21920. res.set_header("Content-Encoding", encoding);
  21921. });
  21922. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21923. auto se = detail::scope_exit([&] {
  21924. svr.stop();
  21925. t.join();
  21926. ASSERT_FALSE(svr.is_running());
  21927. });
  21928. svr.wait_until_ready();
  21929. Client cli(HOST, PORT);
  21930. // Non-streaming
  21931. {
  21932. auto res = cli.Get(path);
  21933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21934. EXPECT_EQ(StatusCode::OK_200, res->status);
  21935. EXPECT_EQ(original, res->body);
  21936. }
  21937. // Streaming
  21938. {
  21939. auto h = cli.open_stream("GET", path);
  21940. ASSERT_TRUE(h.is_valid());
  21941. EXPECT_EQ(original, read_all(h));
  21942. }
  21943. }
  21944. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21945. TEST(ParityTest, Gzip) {
  21946. test_compression_parity<detail::gzip_compressor>(
  21947. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21948. }
  21949. #endif
  21950. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21951. TEST(ParityTest, Brotli) {
  21952. test_compression_parity<detail::brotli_compressor>(
  21953. "Hello, brotli parity test payload", "/parity-br", "br");
  21954. }
  21955. #endif
  21956. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21957. TEST(ParityTest, Zstd) {
  21958. test_compression_parity<detail::zstd_compressor>(
  21959. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21960. }
  21961. #endif
  21962. //==============================================================================
  21963. // New Stream API Tests
  21964. //==============================================================================
  21965. inline std::string read_body(httplib::stream::Result &result) {
  21966. std::string body;
  21967. while (result.next()) {
  21968. body.append(result.data(), result.size());
  21969. }
  21970. return body;
  21971. }
  21972. TEST(ClientConnectionTest, Basic) {
  21973. httplib::ClientConnection conn;
  21974. EXPECT_FALSE(conn.is_open());
  21975. conn.sock = 1;
  21976. EXPECT_TRUE(conn.is_open());
  21977. httplib::ClientConnection conn2(std::move(conn));
  21978. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21979. conn2.sock = INVALID_SOCKET;
  21980. }
  21981. // Unified test server for all stream::* tests
  21982. class StreamApiTest : public ::testing::Test {
  21983. protected:
  21984. void SetUp() override {
  21985. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21986. res.set_content("Hello World!", "text/plain");
  21987. });
  21988. svr_.Get("/echo-params",
  21989. [](const httplib::Request &req, httplib::Response &res) {
  21990. std::string r;
  21991. for (const auto &p : req.params) {
  21992. if (!r.empty()) r += "&";
  21993. r += p.first + "=" + p.second;
  21994. }
  21995. res.set_content(r, "text/plain");
  21996. });
  21997. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21998. res.set_content(req.body, req.get_header_value("Content-Type"));
  21999. });
  22000. svr_.Post("/echo-headers",
  22001. [](const httplib::Request &req, httplib::Response &res) {
  22002. std::string r;
  22003. for (const auto &h : req.headers)
  22004. r += h.first + ": " + h.second + "\n";
  22005. res.set_content(r, "text/plain");
  22006. });
  22007. svr_.Post("/echo-params",
  22008. [](const httplib::Request &req, httplib::Response &res) {
  22009. std::string r = "params:";
  22010. for (const auto &p : req.params)
  22011. r += p.first + "=" + p.second + ";";
  22012. res.set_content(r + " body:" + req.body, "text/plain");
  22013. });
  22014. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22015. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22016. });
  22017. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22018. res.set_content("PUT:" + req.body, "text/plain");
  22019. });
  22020. svr_.Patch("/echo",
  22021. [](const httplib::Request &req, httplib::Response &res) {
  22022. res.set_content("PATCH:" + req.body, "text/plain");
  22023. });
  22024. svr_.Delete(
  22025. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22026. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22027. "text/plain");
  22028. });
  22029. svr_.Get("/head-test",
  22030. [](const httplib::Request &, httplib::Response &res) {
  22031. res.set_content("body for HEAD", "text/plain");
  22032. });
  22033. svr_.Options("/options",
  22034. [](const httplib::Request &, httplib::Response &res) {
  22035. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22036. });
  22037. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22038. svr_.wait_until_ready();
  22039. }
  22040. void TearDown() override {
  22041. svr_.stop();
  22042. if (thread_.joinable()) thread_.join();
  22043. }
  22044. httplib::Server svr_;
  22045. std::thread thread_;
  22046. };
  22047. // stream::Get tests
  22048. TEST_F(StreamApiTest, GetBasic) {
  22049. httplib::Client cli(HOST, PORT);
  22050. auto result = httplib::stream::Get(cli, "/hello");
  22051. ASSERT_TRUE(result.is_valid());
  22052. EXPECT_EQ(200, result.status());
  22053. EXPECT_EQ("Hello World!", read_body(result));
  22054. }
  22055. TEST_F(StreamApiTest, GetWithParams) {
  22056. httplib::Client cli(HOST, PORT);
  22057. httplib::Params params{{"foo", "bar"}};
  22058. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22059. ASSERT_TRUE(result.is_valid());
  22060. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22061. }
  22062. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22063. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22064. httplib::Client cli(HOST, PORT);
  22065. cli.set_payload_max_length(0);
  22066. auto result = httplib::stream::Get(cli, "/hello");
  22067. ASSERT_TRUE(result.is_valid());
  22068. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22069. EXPECT_EQ("Hello World!", read_body(result));
  22070. }
  22071. #endif
  22072. TEST_F(StreamApiTest, GetConnectionError) {
  22073. httplib::Client cli(HOST, 9999);
  22074. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22075. }
  22076. TEST_F(StreamApiTest, Get404) {
  22077. httplib::Client cli(HOST, PORT);
  22078. auto result = httplib::stream::Get(cli, "/nonexistent");
  22079. EXPECT_TRUE(result.is_valid());
  22080. EXPECT_EQ(404, result.status());
  22081. }
  22082. // stream::Post tests
  22083. TEST_F(StreamApiTest, PostBasic) {
  22084. httplib::Client cli(HOST, PORT);
  22085. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22086. "application/json");
  22087. ASSERT_TRUE(result.is_valid());
  22088. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22089. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22090. }
  22091. TEST_F(StreamApiTest, PostWithHeaders) {
  22092. httplib::Client cli(HOST, PORT);
  22093. httplib::Headers headers{{"X-Custom", "value"}};
  22094. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22095. "text/plain");
  22096. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22097. }
  22098. TEST_F(StreamApiTest, PostWithParams) {
  22099. httplib::Client cli(HOST, PORT);
  22100. httplib::Params params{{"k", "v"}};
  22101. auto result =
  22102. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22103. auto body = read_body(result);
  22104. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22105. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22106. }
  22107. TEST_F(StreamApiTest, PostLarge) {
  22108. httplib::Client cli(HOST, PORT);
  22109. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22110. size_t total = 0;
  22111. while (result.next()) {
  22112. total += result.size();
  22113. }
  22114. EXPECT_EQ(100u * 1024u, total);
  22115. }
  22116. // stream::Put/Patch tests
  22117. TEST_F(StreamApiTest, PutAndPatch) {
  22118. httplib::Client cli(HOST, PORT);
  22119. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22120. EXPECT_EQ("PUT:test", read_body(put));
  22121. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22122. EXPECT_EQ("PATCH:test", read_body(patch));
  22123. }
  22124. // stream::Delete tests
  22125. TEST_F(StreamApiTest, Delete) {
  22126. httplib::Client cli(HOST, PORT);
  22127. auto del1 = httplib::stream::Delete(cli, "/resource");
  22128. EXPECT_EQ("Deleted", read_body(del1));
  22129. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22130. EXPECT_EQ("Deleted:data", read_body(del2));
  22131. }
  22132. // stream::Head/Options tests
  22133. TEST_F(StreamApiTest, HeadAndOptions) {
  22134. httplib::Client cli(HOST, PORT);
  22135. auto head = httplib::stream::Head(cli, "/head-test");
  22136. EXPECT_TRUE(head.is_valid());
  22137. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22138. auto opts = httplib::stream::Options(cli, "/options");
  22139. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22140. }
  22141. // SSL stream::* tests
  22142. #ifdef CPPHTTPLIB_SSL_ENABLED
  22143. class SSLStreamApiTest : public ::testing::Test {
  22144. protected:
  22145. void SetUp() override {
  22146. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22147. res.set_content("Hello SSL!", "text/plain");
  22148. });
  22149. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22150. res.set_content(req.body, "text/plain");
  22151. });
  22152. port_ = svr_.bind_to_any_port("127.0.0.1");
  22153. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22154. svr_.wait_until_ready();
  22155. }
  22156. void TearDown() override {
  22157. svr_.stop();
  22158. if (thread_.joinable()) thread_.join();
  22159. }
  22160. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22161. std::thread thread_;
  22162. int port_ = 0;
  22163. };
  22164. TEST_F(SSLStreamApiTest, GetAndPost) {
  22165. httplib::SSLClient cli("127.0.0.1", port_);
  22166. cli.enable_server_certificate_verification(false);
  22167. auto get = httplib::stream::Get(cli, "/hello");
  22168. EXPECT_EQ("Hello SSL!", read_body(get));
  22169. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22170. EXPECT_EQ("test", read_body(post));
  22171. }
  22172. #endif
  22173. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22174. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22175. // BodyReader
  22176. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22177. // Test that read timeout during streaming is detected
  22178. // Use a large content-length response where server delays mid-stream
  22179. Server svr;
  22180. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22181. // Send a large response with delay in the middle
  22182. res.set_content_provider(
  22183. 1000, // content_length
  22184. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22185. if (offset < 100) {
  22186. // Send first 100 bytes immediately
  22187. std::string data(100, 'A');
  22188. sink.write(data.c_str(), data.size());
  22189. return true;
  22190. }
  22191. // Then delay longer than client timeout
  22192. std::this_thread::sleep_for(std::chrono::seconds(3));
  22193. std::string data(900, 'B');
  22194. sink.write(data.c_str(), data.size());
  22195. return true;
  22196. });
  22197. });
  22198. auto port = 8091;
  22199. std::thread t([&]() { svr.listen("localhost", port); });
  22200. svr.wait_until_ready();
  22201. Client cli("localhost", port);
  22202. cli.set_read_timeout(1, 0); // 1 second timeout
  22203. auto handle = cli.open_stream("GET", "/slow-stream");
  22204. ASSERT_TRUE(handle.is_valid());
  22205. char buf[256];
  22206. ssize_t total = 0;
  22207. ssize_t n;
  22208. bool got_error = false;
  22209. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22210. total += n;
  22211. }
  22212. if (n < 0) {
  22213. got_error = true;
  22214. // Should be timeout or read error
  22215. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22216. handle.get_read_error() == Error::Read)
  22217. << "Actual error: " << to_string(handle.get_read_error());
  22218. }
  22219. // Either we got an error, or we got less data than expected
  22220. EXPECT_TRUE(got_error || total < 1000)
  22221. << "Expected timeout but got all " << total << " bytes";
  22222. svr.stop();
  22223. t.join();
  22224. }
  22225. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22226. // Test connection closed detection via BodyReader
  22227. Server svr;
  22228. std::atomic<bool> close_now{false};
  22229. svr.Get("/will-close", [&](const Request &, Response &res) {
  22230. res.set_content_provider(
  22231. 10000, // Large content_length that we won't fully send
  22232. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22233. if (offset < 100) {
  22234. std::string data(100, 'X');
  22235. sink.write(data.c_str(), data.size());
  22236. return true;
  22237. }
  22238. // Wait for signal then abort
  22239. while (!close_now) {
  22240. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22241. }
  22242. return false; // Abort - server will close connection
  22243. });
  22244. });
  22245. auto port = 8092;
  22246. std::thread t([&]() { svr.listen("localhost", port); });
  22247. svr.wait_until_ready();
  22248. Client cli("localhost", port);
  22249. auto handle = cli.open_stream("GET", "/will-close");
  22250. ASSERT_TRUE(handle.is_valid());
  22251. char buf[256];
  22252. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22253. EXPECT_GT(n, 0) << "First read should succeed";
  22254. // Signal server to close
  22255. close_now = true;
  22256. // Keep reading until error or EOF
  22257. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22258. // Keep reading
  22259. }
  22260. // Should get an error since content_length wasn't satisfied
  22261. if (n < 0) {
  22262. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22263. handle.get_read_error() == Error::Read)
  22264. << "Actual error: " << to_string(handle.get_read_error());
  22265. }
  22266. svr.stop();
  22267. t.join();
  22268. }
  22269. #ifdef CPPHTTPLIB_SSL_ENABLED
  22270. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22271. // Test that read timeout during SSL streaming is detected
  22272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22273. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22274. res.set_content_provider(
  22275. 1000, "text/plain",
  22276. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22277. if (offset < 100) {
  22278. std::string data(100, 'A');
  22279. sink.write(data.c_str(), data.size());
  22280. return true;
  22281. }
  22282. std::this_thread::sleep_for(std::chrono::seconds(3));
  22283. std::string data(900, 'B');
  22284. sink.write(data.c_str(), data.size());
  22285. return true;
  22286. });
  22287. });
  22288. auto port = 8093;
  22289. std::thread t([&]() { svr.listen("localhost", port); });
  22290. svr.wait_until_ready();
  22291. SSLClient cli("localhost", port);
  22292. cli.enable_server_certificate_verification(false);
  22293. cli.set_read_timeout(1, 0); // 1 second timeout
  22294. auto handle = cli.open_stream("GET", "/slow-stream");
  22295. ASSERT_TRUE(handle.is_valid());
  22296. char buf[256];
  22297. ssize_t total = 0;
  22298. ssize_t n;
  22299. bool got_error = false;
  22300. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22301. total += n;
  22302. }
  22303. if (n < 0) {
  22304. got_error = true;
  22305. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22306. handle.get_read_error() == Error::Read)
  22307. << "Actual error: " << to_string(handle.get_read_error());
  22308. }
  22309. EXPECT_TRUE(got_error || total < 1000)
  22310. << "Expected timeout but got all " << total << " bytes";
  22311. svr.stop();
  22312. t.join();
  22313. }
  22314. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22315. // Test SSL connection closed detection
  22316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22317. std::atomic<bool> close_now{false};
  22318. svr.Get("/will-close", [&](const Request &, Response &res) {
  22319. res.set_content_provider(
  22320. 10000, "text/plain",
  22321. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22322. if (offset < 100) {
  22323. std::string data(100, 'X');
  22324. sink.write(data.c_str(), data.size());
  22325. return true;
  22326. }
  22327. while (!close_now) {
  22328. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22329. }
  22330. return false;
  22331. });
  22332. });
  22333. auto port = 8094;
  22334. std::thread t([&]() { svr.listen("localhost", port); });
  22335. svr.wait_until_ready();
  22336. SSLClient cli("localhost", port);
  22337. cli.enable_server_certificate_verification(false);
  22338. auto handle = cli.open_stream("GET", "/will-close");
  22339. ASSERT_TRUE(handle.is_valid());
  22340. char buf[256];
  22341. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22342. EXPECT_GT(n, 0);
  22343. // Signal server to close
  22344. close_now = true;
  22345. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22346. // Keep reading
  22347. }
  22348. if (n < 0) {
  22349. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22350. handle.get_read_error() == Error::Read)
  22351. << "Actual error: " << to_string(handle.get_read_error());
  22352. }
  22353. svr.stop();
  22354. t.join();
  22355. }
  22356. #endif
  22357. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22358. using namespace httplib;
  22359. // Create a test file
  22360. const char *fname = "etag_testfile.txt";
  22361. const char *content = "etag-content";
  22362. {
  22363. std::ofstream ofs(fname);
  22364. ofs << content;
  22365. ASSERT_TRUE(ofs.good());
  22366. }
  22367. Server svr;
  22368. svr.set_mount_point("/static", ".");
  22369. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22370. svr.wait_until_ready();
  22371. Client cli(HOST, PORT);
  22372. // First request: should get 200 with ETag header
  22373. auto res1 = cli.Get("/static/etag_testfile.txt");
  22374. ASSERT_TRUE(res1);
  22375. ASSERT_EQ(200, res1->status);
  22376. ASSERT_TRUE(res1->has_header("ETag"));
  22377. std::string etag = res1->get_header_value("ETag");
  22378. EXPECT_FALSE(etag.empty());
  22379. // Verify ETag format: W/"hex-hex"
  22380. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22381. EXPECT_EQ('W', etag[0]);
  22382. EXPECT_EQ('/', etag[1]);
  22383. EXPECT_EQ('"', etag[2]);
  22384. EXPECT_EQ('"', etag.back());
  22385. // Exact match: expect 304 Not Modified
  22386. Headers h2 = {{"If-None-Match", etag}};
  22387. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22388. ASSERT_TRUE(res2);
  22389. EXPECT_EQ(304, res2->status);
  22390. // Wildcard match: expect 304 Not Modified
  22391. Headers h3 = {{"If-None-Match", "*"}};
  22392. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22393. ASSERT_TRUE(res3);
  22394. EXPECT_EQ(304, res3->status);
  22395. // Non-matching ETag: expect 200
  22396. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22397. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22398. ASSERT_TRUE(res4);
  22399. EXPECT_EQ(200, res4->status);
  22400. // Multiple ETags with one matching: expect 304
  22401. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22402. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22403. ASSERT_TRUE(res5);
  22404. EXPECT_EQ(304, res5->status);
  22405. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22406. // that equivalent to the single comma-separated list above, so the match on
  22407. // the second line must still be found.
  22408. Headers h6;
  22409. h6.emplace("If-None-Match", "W/\"other\"");
  22410. h6.emplace("If-None-Match", etag);
  22411. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22412. ASSERT_TRUE(res6);
  22413. EXPECT_EQ(304, res6->status);
  22414. svr.stop();
  22415. t.join();
  22416. std::remove(fname);
  22417. }
  22418. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22419. using namespace httplib;
  22420. Server svr;
  22421. svr.set_mount_point("/static", ".");
  22422. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22423. svr.wait_until_ready();
  22424. Client cli(HOST, PORT);
  22425. // Send If-None-Match: * to a non-existent file
  22426. Headers h = {{"If-None-Match", "*"}};
  22427. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22429. EXPECT_EQ(404, res->status);
  22430. svr.stop();
  22431. t.join();
  22432. }
  22433. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22434. using namespace httplib;
  22435. // Create a test file
  22436. const char *fname = "etag_boundary_testfile.txt";
  22437. const char *content = "boundary-test";
  22438. {
  22439. std::ofstream ofs(fname);
  22440. ofs << content;
  22441. ASSERT_TRUE(ofs.good());
  22442. }
  22443. Server svr;
  22444. svr.set_mount_point("/static", ".");
  22445. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22446. svr.wait_until_ready();
  22447. Client cli(HOST, PORT);
  22448. // Get the actual ETag
  22449. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22450. ASSERT_TRUE(res1);
  22451. ASSERT_EQ(200, res1->status);
  22452. ASSERT_TRUE(res1->has_header("ETag"));
  22453. std::string etag = res1->get_header_value("ETag");
  22454. // Test 1: Very long ETag value (longer than actual ETag)
  22455. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22456. Headers h1 = {{"If-None-Match", "W/"
  22457. "\"very-long-etag-value-that-is-much-longer-"
  22458. "than-the-actual-etag-value\""}};
  22459. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22460. ASSERT_TRUE(res2);
  22461. EXPECT_EQ(200, res2->status); // Should not match
  22462. // Test 2: Long string followed by wildcard
  22463. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22464. // string)
  22465. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22466. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22467. ASSERT_TRUE(res3);
  22468. EXPECT_EQ(304, res3->status); // Should match on "*"
  22469. // Test 3: Wildcard followed by long string
  22470. // Should match on "*" immediately and return 304
  22471. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22472. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22473. ASSERT_TRUE(res4);
  22474. EXPECT_EQ(304, res4->status); // Should match on "*"
  22475. // Test 4: Multiple long non-matching values
  22476. // Should NOT match and return 200 (test that all comparisons are safe)
  22477. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22478. "W/\"second-long-non-matching-value\", "
  22479. "W/\"third-long-non-matching-value\""}};
  22480. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22481. ASSERT_TRUE(res5);
  22482. EXPECT_EQ(200, res5->status); // Should not match
  22483. // Test 5: Single character that is not "*" (edge case)
  22484. Headers h5 = {{"If-None-Match", "X"}};
  22485. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22486. ASSERT_TRUE(res6);
  22487. EXPECT_EQ(200, res6->status); // Should not match
  22488. svr.stop();
  22489. t.join();
  22490. std::remove(fname);
  22491. }
  22492. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22493. using namespace httplib;
  22494. // Create a test file
  22495. const char *fname = "ims_testfile.txt";
  22496. const char *content = "if-modified-since-test";
  22497. {
  22498. std::ofstream ofs(fname);
  22499. ofs << content;
  22500. ASSERT_TRUE(ofs.good());
  22501. }
  22502. Server svr;
  22503. svr.set_mount_point("/static", ".");
  22504. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22505. svr.wait_until_ready();
  22506. Client cli(HOST, PORT);
  22507. // First request: should get 200 with Last-Modified header
  22508. auto res1 = cli.Get("/static/ims_testfile.txt");
  22509. ASSERT_TRUE(res1);
  22510. ASSERT_EQ(200, res1->status);
  22511. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22512. std::string last_modified = res1->get_header_value("Last-Modified");
  22513. EXPECT_FALSE(last_modified.empty());
  22514. // If-Modified-Since with same time: expect 304
  22515. Headers h2 = {{"If-Modified-Since", last_modified}};
  22516. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22517. ASSERT_TRUE(res2);
  22518. EXPECT_EQ(304, res2->status);
  22519. // If-Modified-Since with future time: expect 304
  22520. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22521. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22522. ASSERT_TRUE(res3);
  22523. EXPECT_EQ(304, res3->status);
  22524. // If-Modified-Since with past time: expect 200
  22525. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22526. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22527. ASSERT_TRUE(res4);
  22528. EXPECT_EQ(200, res4->status);
  22529. // If-None-Match takes precedence over If-Modified-Since
  22530. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22531. ASSERT_TRUE(res1->has_header("ETag"));
  22532. std::string etag = res1->get_header_value("ETag");
  22533. Headers h5 = {{"If-None-Match", etag},
  22534. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22535. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22536. ASSERT_TRUE(res5);
  22537. EXPECT_EQ(304, res5->status);
  22538. svr.stop();
  22539. t.join();
  22540. std::remove(fname);
  22541. }
  22542. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22543. using namespace httplib;
  22544. Server svr;
  22545. // Endpoint that returns compressible content
  22546. svr.Get("/compressible", [](const Request &, Response &res) {
  22547. // Return a large enough body to trigger compression
  22548. std::string body(1000, 'a');
  22549. res.set_content(body, "text/plain");
  22550. });
  22551. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22552. svr.wait_until_ready();
  22553. Client cli(HOST, PORT);
  22554. // Request with gzip support: should get Vary header when compressed
  22555. cli.set_compress(true);
  22556. auto res1 = cli.Get("/compressible");
  22557. ASSERT_TRUE(res1);
  22558. EXPECT_EQ(200, res1->status);
  22559. // If Content-Encoding is set, Vary should also be set
  22560. if (res1->has_header("Content-Encoding")) {
  22561. EXPECT_TRUE(res1->has_header("Vary"));
  22562. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22563. }
  22564. // Request without Accept-Encoding header: should not have compression
  22565. Headers h_no_compress;
  22566. auto res2 = cli.Get("/compressible", h_no_compress);
  22567. ASSERT_TRUE(res2);
  22568. EXPECT_EQ(200, res2->status);
  22569. // Verify Vary header is present when compression is applied
  22570. // (the exact behavior depends on server configuration)
  22571. svr.stop();
  22572. t.join();
  22573. }
  22574. TEST(ETagTest, IfRangeWithETag) {
  22575. using namespace httplib;
  22576. // Create a test file with known content
  22577. const char *fname = "if_range_testfile.txt";
  22578. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22579. {
  22580. std::ofstream ofs(fname);
  22581. ofs << content;
  22582. ASSERT_TRUE(ofs.good());
  22583. }
  22584. Server svr;
  22585. svr.set_mount_point("/static", ".");
  22586. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22587. svr.wait_until_ready();
  22588. Client cli(HOST, PORT);
  22589. // First request: get ETag
  22590. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22591. ASSERT_TRUE(res1);
  22592. ASSERT_EQ(200, res1->status);
  22593. ASSERT_TRUE(res1->has_header("ETag"));
  22594. std::string etag = res1->get_header_value("ETag");
  22595. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22596. // Since our server generates weak ETags (W/"..."), If-Range with our
  22597. // ETag should NOT result in partial content - it should return full content.
  22598. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22599. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22600. ASSERT_TRUE(res2);
  22601. // Weak ETag in If-Range -> full content (200), not partial (206)
  22602. EXPECT_EQ(200, res2->status);
  22603. EXPECT_EQ(content, res2->body);
  22604. EXPECT_FALSE(res2->has_header("Content-Range"));
  22605. // Range request with non-matching If-Range (ETag): should get 200 (full
  22606. // content)
  22607. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22608. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22609. ASSERT_TRUE(res3);
  22610. EXPECT_EQ(200, res3->status);
  22611. EXPECT_EQ(content, res3->body);
  22612. EXPECT_FALSE(res3->has_header("Content-Range"));
  22613. // Range request with strong ETag (hypothetical - our server doesn't generate
  22614. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22615. // should return full content)
  22616. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22617. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22618. ASSERT_TRUE(res4);
  22619. EXPECT_EQ(200, res4->status);
  22620. EXPECT_EQ(content, res4->body);
  22621. EXPECT_FALSE(res4->has_header("Content-Range"));
  22622. svr.stop();
  22623. t.join();
  22624. std::remove(fname);
  22625. }
  22626. TEST(ETagTest, IfRangeWithDate) {
  22627. using namespace httplib;
  22628. // Create a test file
  22629. const char *fname = "if_range_date_testfile.txt";
  22630. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22631. {
  22632. std::ofstream ofs(fname);
  22633. ofs << content;
  22634. ASSERT_TRUE(ofs.good());
  22635. }
  22636. Server svr;
  22637. svr.set_mount_point("/static", ".");
  22638. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22639. svr.wait_until_ready();
  22640. Client cli(HOST, PORT);
  22641. // First request: get Last-Modified
  22642. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22643. ASSERT_TRUE(res1);
  22644. ASSERT_EQ(200, res1->status);
  22645. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22646. std::string last_modified = res1->get_header_value("Last-Modified");
  22647. // Range request with matching If-Range (date): should get 206
  22648. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22649. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22650. ASSERT_TRUE(res2);
  22651. EXPECT_EQ(206, res2->status);
  22652. EXPECT_EQ("FGHIJ", res2->body);
  22653. // Range request with old If-Range date: should get 200 (full content)
  22654. Headers h3 = {{"Range", "bytes=5-9"},
  22655. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22656. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22657. ASSERT_TRUE(res3);
  22658. EXPECT_EQ(200, res3->status);
  22659. EXPECT_EQ(content, res3->body);
  22660. // Range request with future If-Range date: should get 206
  22661. Headers h4 = {{"Range", "bytes=0-4"},
  22662. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22663. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22664. ASSERT_TRUE(res4);
  22665. EXPECT_EQ(206, res4->status);
  22666. EXPECT_EQ("ABCDE", res4->body);
  22667. svr.stop();
  22668. t.join();
  22669. std::remove(fname);
  22670. }
  22671. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22672. using namespace httplib;
  22673. const char *fname = "etag_malformed.txt";
  22674. const char *content = "malformed-etag";
  22675. {
  22676. std::ofstream ofs(fname);
  22677. ofs << content;
  22678. ASSERT_TRUE(ofs.good());
  22679. }
  22680. Server svr;
  22681. svr.set_mount_point("/static", ".");
  22682. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22683. svr.wait_until_ready();
  22684. Client cli(HOST, PORT);
  22685. // baseline: should get 200 and an ETag
  22686. auto res1 = cli.Get("/static/etag_malformed.txt");
  22687. ASSERT_TRUE(res1);
  22688. ASSERT_EQ(200, res1->status);
  22689. ASSERT_TRUE(res1->has_header("ETag"));
  22690. // Malformed ETag value (missing quotes) should be treated as non-matching
  22691. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22692. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22693. ASSERT_TRUE(res_bad);
  22694. EXPECT_EQ(200, res_bad->status);
  22695. // Whitespace-only header value should be considered invalid / non-matching
  22696. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22697. "Host: localhost\r\n"
  22698. "If-None-Match: \r\n"
  22699. "Connection: close\r\n"
  22700. "\r\n";
  22701. std::string out;
  22702. ASSERT_TRUE(send_request(5, raw_req, &out));
  22703. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22704. svr.stop();
  22705. t.join();
  22706. std::remove(fname);
  22707. }
  22708. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22709. using namespace httplib;
  22710. const char *fname = "ims_invalid_format.txt";
  22711. const char *content = "ims-bad-format";
  22712. {
  22713. std::ofstream ofs(fname);
  22714. ofs << content;
  22715. ASSERT_TRUE(ofs.good());
  22716. }
  22717. Server svr;
  22718. svr.set_mount_point("/static", ".");
  22719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22720. svr.wait_until_ready();
  22721. Client cli(HOST, PORT);
  22722. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22723. ASSERT_TRUE(res1);
  22724. ASSERT_EQ(200, res1->status);
  22725. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22726. // If-Modified-Since with invalid format should not result in 304
  22727. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22728. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22729. ASSERT_TRUE(res_bad);
  22730. EXPECT_EQ(200, res_bad->status);
  22731. // If-Range with invalid date format should be treated as mismatch -> full
  22732. // content (200)
  22733. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22734. {"If-Range", "invalid-date"}};
  22735. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22736. ASSERT_TRUE(res_ifrange);
  22737. EXPECT_EQ(200, res_ifrange->status);
  22738. svr.stop();
  22739. t.join();
  22740. std::remove(fname);
  22741. }
  22742. TEST(ETagTest, IfRangeWithMalformedETag) {
  22743. using namespace httplib;
  22744. const char *fname = "ifrange_malformed.txt";
  22745. const std::string content = "0123456789";
  22746. {
  22747. std::ofstream ofs(fname);
  22748. ofs << content;
  22749. ASSERT_TRUE(ofs.good());
  22750. }
  22751. Server svr;
  22752. svr.set_mount_point("/static", ".");
  22753. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22754. svr.wait_until_ready();
  22755. Client cli(HOST, PORT);
  22756. // First request: get ETag
  22757. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22758. ASSERT_TRUE(res1);
  22759. ASSERT_EQ(200, res1->status);
  22760. ASSERT_TRUE(res1->has_header("ETag"));
  22761. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22762. // full content (200)
  22763. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22764. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22765. ASSERT_TRUE(res2);
  22766. EXPECT_EQ(200, res2->status);
  22767. EXPECT_EQ(content, res2->body);
  22768. svr.stop();
  22769. t.join();
  22770. std::remove(fname);
  22771. }
  22772. TEST(ETagTest, ExtremeLargeDateValues) {
  22773. using namespace httplib;
  22774. const char *fname = "ims_extreme_date.txt";
  22775. const char *content = "ims-extreme-date";
  22776. {
  22777. std::ofstream ofs(fname);
  22778. ofs << content;
  22779. ASSERT_TRUE(ofs.good());
  22780. }
  22781. Server svr;
  22782. svr.set_mount_point("/static", ".");
  22783. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22784. svr.wait_until_ready();
  22785. Client cli(HOST, PORT);
  22786. auto res1 = cli.Get(std::string("/static/") + fname);
  22787. ASSERT_TRUE(res1);
  22788. ASSERT_EQ(200, res1->status);
  22789. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22790. // Extremely large year that may overflow date parsing routines.
  22791. Headers h_large_date = {
  22792. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22793. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22794. ASSERT_TRUE(res_bad);
  22795. // Expect server to treat this as invalid/mismatch and return full content
  22796. EXPECT_EQ(200, res_bad->status);
  22797. // If-Range with extremely large date should be treated as mismatch -> full
  22798. // content (200)
  22799. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22800. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22801. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22802. ASSERT_TRUE(res_ifrange);
  22803. EXPECT_EQ(200, res_ifrange->status);
  22804. svr.stop();
  22805. t.join();
  22806. std::remove(fname);
  22807. }
  22808. TEST(ETagTest, NegativeFileModificationTime) {
  22809. using namespace httplib;
  22810. const char *fname = "ims_negative_mtime.txt";
  22811. const std::string content = "negative-mtime";
  22812. {
  22813. std::ofstream ofs(fname);
  22814. ofs << content;
  22815. ASSERT_TRUE(ofs.good());
  22816. }
  22817. // Try to set file mtime to a negative value. This may fail on some
  22818. // platforms/filesystems; if it fails, the test will still verify server
  22819. // behaves safely by performing a regular conditional request.
  22820. #if defined(__APPLE__) || defined(__linux__)
  22821. bool set_negative = false;
  22822. do {
  22823. struct timeval times[2];
  22824. // access time: now
  22825. times[0].tv_sec = time(nullptr);
  22826. times[0].tv_usec = 0;
  22827. // modification time: negative (e.g., -1)
  22828. times[1].tv_sec = -1;
  22829. times[1].tv_usec = 0;
  22830. if (utimes(fname, times) == 0) { set_negative = true; }
  22831. } while (0);
  22832. #else
  22833. bool set_negative = false;
  22834. #endif
  22835. Server svr;
  22836. svr.set_mount_point("/static", ".");
  22837. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22838. svr.wait_until_ready();
  22839. Client cli(HOST, PORT);
  22840. auto res1 = cli.Get(std::string("/static/") + fname);
  22841. ASSERT_TRUE(res1);
  22842. ASSERT_EQ(200, res1->status);
  22843. bool has_last_modified = res1->has_header("Last-Modified");
  22844. std::string last_modified;
  22845. if (has_last_modified) {
  22846. last_modified = res1->get_header_value("Last-Modified");
  22847. }
  22848. if (set_negative) {
  22849. // If we successfully set a negative mtime, ensure server returns a
  22850. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22851. // with an old date and ensure server handles it without crash.
  22852. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22853. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22854. ASSERT_TRUE(res2);
  22855. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22856. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22857. } else {
  22858. // Could not set negative mtime on this platform; fall back to verifying
  22859. // that normal invalid/malformed dates are treated safely (non-304).
  22860. Headers h_bad_date = {
  22861. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22862. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22863. ASSERT_TRUE(res_bad);
  22864. EXPECT_EQ(200, res_bad->status);
  22865. }
  22866. svr.stop();
  22867. t.join();
  22868. std::remove(fname);
  22869. }
  22870. //==============================================================================
  22871. // Integration Tests with Server
  22872. //==============================================================================
  22873. class SSEIntegrationTest : public ::testing::Test {
  22874. protected:
  22875. void SetUp() override {
  22876. stop_server_.store(false);
  22877. events_.clear();
  22878. server_ = httplib::detail::make_unique<Server>();
  22879. setup_server();
  22880. start_server();
  22881. }
  22882. void TearDown() override {
  22883. stop_server_.store(true);
  22884. event_cv_.notify_all();
  22885. server_->stop();
  22886. if (server_thread_.joinable()) { server_thread_.join(); }
  22887. }
  22888. void setup_server() {
  22889. // Simple SSE endpoint
  22890. server_->Get("/events", [this](const Request &req, Response &res) {
  22891. auto last_id = req.get_header_value("Last-Event-ID");
  22892. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22893. res.set_chunked_content_provider(
  22894. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22895. std::unique_lock<std::mutex> lock(event_mutex_);
  22896. if (event_cv_.wait_for(
  22897. lock, std::chrono::milliseconds(200), [this] {
  22898. return !events_.empty() || stop_server_.load();
  22899. })) {
  22900. if (stop_server_.load()) { return false; }
  22901. if (!events_.empty()) {
  22902. std::string event = events_.front();
  22903. events_.erase(events_.begin());
  22904. sink.write(event.data(), event.size());
  22905. return true;
  22906. }
  22907. }
  22908. return !stop_server_.load();
  22909. });
  22910. });
  22911. // Endpoint that returns error
  22912. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22913. res.status = 500;
  22914. res.set_content("Internal Server Error", "text/plain");
  22915. });
  22916. // Endpoint for custom event types
  22917. server_->Get("/custom-events", [](const Request &, Response &res) {
  22918. res.set_chunked_content_provider(
  22919. "text/event-stream", [](size_t offset, DataSink &sink) {
  22920. if (offset == 0) {
  22921. std::string event = "event: update\ndata: updated\n\n"
  22922. "event: delete\ndata: deleted\n\n";
  22923. sink.write(event.data(), event.size());
  22924. }
  22925. return false; // End stream after sending
  22926. });
  22927. });
  22928. }
  22929. void start_server() {
  22930. port_ = server_->bind_to_any_port(HOST);
  22931. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22932. // Wait for server to start
  22933. while (!server_->is_running()) {
  22934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22935. }
  22936. }
  22937. int get_port() const { return port_; }
  22938. void send_event(const std::string &event) {
  22939. std::lock_guard<std::mutex> lock(event_mutex_);
  22940. events_.push_back(event);
  22941. event_cv_.notify_all();
  22942. }
  22943. std::unique_ptr<Server> server_;
  22944. std::thread server_thread_;
  22945. std::mutex event_mutex_;
  22946. std::condition_variable event_cv_;
  22947. std::vector<std::string> events_;
  22948. std::atomic<bool> stop_server_{false};
  22949. std::string last_received_event_id_;
  22950. int port_ = 0;
  22951. };
  22952. //==============================================================================
  22953. // SSE Parser Tests
  22954. //==============================================================================
  22955. struct SSEParseResult {
  22956. std::vector<sse::SSEMessage> events;
  22957. std::vector<std::string> ids;
  22958. std::vector<int> retries;
  22959. bool ok = true;
  22960. std::string trace; // Every handler call in order
  22961. };
  22962. static SSEParseResult
  22963. sse_parse(const std::vector<std::string> &chunks,
  22964. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  22965. SSEParseResult r;
  22966. detail::SSEParser parser(
  22967. [&](const sse::SSEMessage &msg) {
  22968. r.events.push_back(msg);
  22969. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  22970. },
  22971. [&](const std::string &id) {
  22972. r.ids.push_back(id);
  22973. r.trace += "id[" + id + "]";
  22974. },
  22975. [&](int retry_ms) {
  22976. r.retries.push_back(retry_ms);
  22977. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  22978. },
  22979. max_event_length);
  22980. for (const auto &chunk : chunks) {
  22981. if (!parser.parse(chunk.data(), chunk.size())) {
  22982. r.ok = false;
  22983. break;
  22984. }
  22985. }
  22986. return r;
  22987. }
  22988. static SSEParseResult sse_parse(const std::string &stream) {
  22989. return sse_parse(std::vector<std::string>{stream});
  22990. }
  22991. TEST(SSEParserTest, SingleLineData) {
  22992. auto r = sse_parse("data: hello\n\n");
  22993. ASSERT_EQ(r.events.size(), 1u);
  22994. EXPECT_EQ(r.events[0].data, "hello");
  22995. EXPECT_EQ(r.events[0].event, "message");
  22996. }
  22997. TEST(SSEParserTest, MultiLineData) {
  22998. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  22999. ASSERT_EQ(r.events.size(), 1u);
  23000. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23001. }
  23002. TEST(SSEParserTest, CustomEventType) {
  23003. auto r = sse_parse("event: update\ndata: payload\n\n");
  23004. ASSERT_EQ(r.events.size(), 1u);
  23005. EXPECT_EQ(r.events[0].event, "update");
  23006. EXPECT_EQ(r.events[0].data, "payload");
  23007. }
  23008. TEST(SSEParserTest, EventIdHandling) {
  23009. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23010. ASSERT_EQ(r.events.size(), 1u);
  23011. EXPECT_EQ(r.events[0].id, "12345");
  23012. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23013. }
  23014. TEST(SSEParserTest, EmptyEventId) {
  23015. auto r = sse_parse("id:\ndata: test\n\n");
  23016. ASSERT_EQ(r.events.size(), 1u);
  23017. EXPECT_EQ(r.events[0].id, "");
  23018. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23019. }
  23020. TEST(SSEParserTest, CommentsIgnored) {
  23021. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23022. ASSERT_EQ(r.events.size(), 1u);
  23023. EXPECT_EQ(r.events[0].data, "hello");
  23024. EXPECT_EQ(r.events[0].event, "message");
  23025. }
  23026. TEST(SSEParserTest, ColonInValue) {
  23027. auto r = sse_parse("data: hello:world:test\n\n");
  23028. ASSERT_EQ(r.events.size(), 1u);
  23029. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23030. }
  23031. TEST(SSEParserTest, FieldNameOnly) {
  23032. // A line without a colon is a field name with an empty value
  23033. auto r = sse_parse("data\n\n");
  23034. ASSERT_EQ(r.events.size(), 1u);
  23035. EXPECT_EQ(r.events[0].data, "");
  23036. }
  23037. TEST(SSEParserTest, TrailingCarriageReturn) {
  23038. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23039. ASSERT_EQ(r.events.size(), 1u);
  23040. EXPECT_EQ(r.events[0].event, "update");
  23041. EXPECT_EQ(r.events[0].data, "hello");
  23042. }
  23043. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23044. auto r = sse_parse("data\r\n\r\n");
  23045. ASSERT_EQ(r.events.size(), 1u);
  23046. EXPECT_EQ(r.events[0].data, "");
  23047. }
  23048. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23049. auto r = sse_parse("event: update\rdata: hello\r\r");
  23050. ASSERT_EQ(r.events.size(), 1u);
  23051. EXPECT_EQ(r.events[0].event, "update");
  23052. EXPECT_EQ(r.events[0].data, "hello");
  23053. }
  23054. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23055. // Chunk boundaries fall inside every \r\n and right before the first one
  23056. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23057. "\ndata: hello\r", "\n\r", "\n"});
  23058. ASSERT_EQ(r.events.size(), 1u);
  23059. EXPECT_EQ(r.events[0].event, "update");
  23060. EXPECT_EQ(r.events[0].data, "hello");
  23061. }
  23062. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23063. // Only a BOM at the start of the stream is ignored
  23064. auto r = sse_parse("\xEF\xBB\xBF"
  23065. "data: first\n\n"
  23066. "\xEF\xBB\xBF"
  23067. "data: second\n\n");
  23068. ASSERT_EQ(r.events.size(), 1u);
  23069. EXPECT_EQ(r.events[0].data, "first");
  23070. }
  23071. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23072. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23073. ASSERT_EQ(r.events.size(), 1u);
  23074. EXPECT_EQ(r.events[0].data, "hello");
  23075. EXPECT_EQ(r.events[0].event, "message");
  23076. }
  23077. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23078. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23079. ASSERT_EQ(r.events.size(), 2u);
  23080. EXPECT_EQ(r.events[0].data, "hello");
  23081. EXPECT_EQ(r.events[1].data, "hello");
  23082. }
  23083. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23084. // An event without data is not dispatched, and its type must not leak
  23085. // into the next event
  23086. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23087. ASSERT_EQ(r.events.size(), 1u);
  23088. EXPECT_EQ(r.events[0].event, "message");
  23089. EXPECT_EQ(r.events[0].data, "hello");
  23090. }
  23091. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23092. // Also when the empty field replaces an earlier type
  23093. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23094. ASSERT_EQ(r.events.size(), 2u);
  23095. EXPECT_EQ(r.events[0].event, "message");
  23096. EXPECT_EQ(r.events[1].event, "message");
  23097. }
  23098. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23099. auto r = sse_parse("id: 42\n\n");
  23100. EXPECT_TRUE(r.events.empty());
  23101. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23102. }
  23103. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23104. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23105. ASSERT_EQ(r.events.size(), 2u);
  23106. EXPECT_EQ(r.events[0].id, "1");
  23107. EXPECT_EQ(r.events[1].id, "");
  23108. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23109. }
  23110. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23111. // Ids that cannot be carried in a Last-Event-ID header
  23112. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23113. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23114. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23115. }
  23116. TEST(SSEParserTest, RetryDigitsOnly) {
  23117. auto r = sse_parse("retry: 1000\n");
  23118. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23119. // A value that is not all ASCII digits, or does not fit, is ignored
  23120. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23121. EXPECT_TRUE(r.retries.empty());
  23122. }
  23123. TEST(SSEParserTest, CompleteEventParsing) {
  23124. auto r = sse_parse("event: notification\nid: evt-42\n"
  23125. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23126. ASSERT_EQ(r.events.size(), 1u);
  23127. EXPECT_EQ(r.events[0].event, "notification");
  23128. EXPECT_EQ(r.events[0].id, "evt-42");
  23129. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23130. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23131. }
  23132. TEST(SSEParserTest, IncompleteEventNotReported) {
  23133. // An event still waiting for its blank line when the stream ends is
  23134. // discarded per the SSE spec
  23135. auto r = sse_parse("id: 1\ndata: x\n");
  23136. EXPECT_TRUE(r.events.empty());
  23137. EXPECT_TRUE(r.ids.empty());
  23138. }
  23139. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23140. const std::vector<std::string> streams = {
  23141. "\xEF\xBB\xBF"
  23142. "data: bom\r\n\r\n",
  23143. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23144. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23145. };
  23146. for (const auto &stream : streams) {
  23147. auto expected = sse_parse(stream).trace;
  23148. ASSERT_FALSE(expected.empty());
  23149. for (size_t i = 0; i <= stream.size(); i++) {
  23150. auto r = sse_parse(
  23151. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23152. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23153. }
  23154. std::vector<std::string> bytes;
  23155. for (auto c : stream) {
  23156. bytes.emplace_back(1, c);
  23157. }
  23158. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23159. }
  23160. }
  23161. TEST(SSEParserTest, MaxEventLength) {
  23162. // A line still waiting for its end
  23163. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23164. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23165. // Data accumulated over the lines of one event
  23166. EXPECT_TRUE(
  23167. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23168. EXPECT_FALSE(
  23169. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23170. // 0 means no limit
  23171. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23172. // Events completed in the same chunk are still reported
  23173. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23174. EXPECT_FALSE(r.ok);
  23175. ASSERT_EQ(r.events.size(), 1u);
  23176. EXPECT_EQ(r.events[0].data, "a");
  23177. }
  23178. TEST(SSEMessageTest, Clear) {
  23179. sse::SSEMessage msg;
  23180. msg.event = "custom";
  23181. msg.data = "some data";
  23182. msg.id = "123";
  23183. msg.clear();
  23184. EXPECT_EQ(msg.event, "message");
  23185. EXPECT_EQ(msg.data, "");
  23186. EXPECT_EQ(msg.id, "");
  23187. }
  23188. //==============================================================================
  23189. // SSE Integration Tests
  23190. //==============================================================================
  23191. // Test: Successful connection and on_open callback
  23192. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23193. // Add a simple endpoint that sends one event and closes
  23194. server_->Get("/simple-event", [](const Request &, Response &res) {
  23195. res.set_chunked_content_provider(
  23196. "text/event-stream", [](size_t offset, DataSink &sink) {
  23197. if (offset == 0) {
  23198. std::string event = "data: hello\n\n";
  23199. sink.write(event.data(), event.size());
  23200. }
  23201. return false; // Close stream after sending
  23202. });
  23203. });
  23204. Client client("localhost", get_port());
  23205. sse::SSEClient sse(client, "/simple-event");
  23206. std::atomic<bool> open_called{false};
  23207. std::atomic<bool> message_received{false};
  23208. sse.on_open([&open_called]() { open_called.store(true); });
  23209. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23210. if (msg.data == "hello") { message_received.store(true); }
  23211. });
  23212. sse.set_reconnect_interval(100);
  23213. sse.set_max_reconnect_attempts(1);
  23214. // Start async
  23215. sse.start_async();
  23216. // Wait for message to be processed
  23217. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23218. sse.stop();
  23219. EXPECT_TRUE(open_called.load());
  23220. EXPECT_TRUE(message_received.load());
  23221. }
  23222. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23223. // A data line that never ends.
  23224. server_->Get("/endless-line", [](const Request &, Response &res) {
  23225. res.set_chunked_content_provider(
  23226. "text/event-stream", [](size_t offset, DataSink &sink) {
  23227. if (offset == 0) { sink.write("data: ", 6); }
  23228. std::string chunk(64 * 1024, 'A');
  23229. return sink.write(chunk.data(), chunk.size());
  23230. });
  23231. });
  23232. Client client("localhost", get_port());
  23233. sse::SSEClient sse(client, "/endless-line");
  23234. std::atomic<bool> too_long{false};
  23235. sse.on_error([&](Error err) {
  23236. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23237. });
  23238. sse.set_max_reconnect_attempts(1);
  23239. sse.start_async();
  23240. for (int i = 0; i < 500 && !too_long; i++) {
  23241. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23242. }
  23243. sse.stop();
  23244. EXPECT_TRUE(too_long);
  23245. }
  23246. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23247. // Far more in all than the client's payload limit below.
  23248. server_->Get("/many-events", [](const Request &, Response &res) {
  23249. res.set_chunked_content_provider(
  23250. "text/event-stream", [](size_t offset, DataSink &sink) {
  23251. if (offset == 0) {
  23252. std::string events;
  23253. for (int i = 0; i < 1000; i++) {
  23254. events += "data: message\n\n";
  23255. }
  23256. sink.write(events.data(), events.size());
  23257. }
  23258. return false;
  23259. });
  23260. });
  23261. Client client("localhost", get_port());
  23262. client.set_payload_max_length(1024);
  23263. sse::SSEClient sse(client, "/many-events");
  23264. std::atomic<int> messages{0};
  23265. std::atomic<bool> too_large{false};
  23266. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23267. sse.on_error([&](Error err) {
  23268. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23269. });
  23270. sse.set_max_reconnect_attempts(1);
  23271. sse.start_async();
  23272. for (int i = 0; i < 500 && messages < 1000; i++) {
  23273. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23274. }
  23275. sse.stop();
  23276. EXPECT_GE(messages.load(), 1000);
  23277. EXPECT_FALSE(too_large);
  23278. }
  23279. // Test: on_message callback
  23280. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23281. // Endpoint that sends multiple events then closes
  23282. server_->Get("/multi-event", [](const Request &, Response &res) {
  23283. res.set_chunked_content_provider(
  23284. "text/event-stream", [](size_t offset, DataSink &sink) {
  23285. if (offset == 0) {
  23286. std::string events = "data: message1\n\ndata: message2\n\n";
  23287. sink.write(events.data(), events.size());
  23288. }
  23289. return false;
  23290. });
  23291. });
  23292. Client client("localhost", get_port());
  23293. sse::SSEClient sse(client, "/multi-event");
  23294. std::vector<std::string> received_messages;
  23295. std::mutex messages_mutex;
  23296. sse.on_message([&](const sse::SSEMessage &msg) {
  23297. std::lock_guard<std::mutex> lock(messages_mutex);
  23298. received_messages.push_back(msg.data);
  23299. });
  23300. sse.set_reconnect_interval(100);
  23301. sse.set_max_reconnect_attempts(1);
  23302. sse.start_async();
  23303. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23304. sse.stop();
  23305. std::lock_guard<std::mutex> lock(messages_mutex);
  23306. EXPECT_GE(received_messages.size(), 2u);
  23307. if (received_messages.size() >= 2) {
  23308. EXPECT_EQ(received_messages[0], "message1");
  23309. EXPECT_EQ(received_messages[1], "message2");
  23310. }
  23311. }
  23312. // Test: on_event for specific types
  23313. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23314. Client client("localhost", get_port());
  23315. sse::SSEClient sse(client, "/custom-events");
  23316. std::atomic<bool> update_received{false};
  23317. std::atomic<bool> delete_received{false};
  23318. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23319. if (msg.data == "updated") { update_received.store(true); }
  23320. });
  23321. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23322. if (msg.data == "deleted") { delete_received.store(true); }
  23323. });
  23324. sse.set_max_reconnect_attempts(1);
  23325. sse.start_async();
  23326. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23327. sse.stop();
  23328. EXPECT_TRUE(update_received.load());
  23329. EXPECT_TRUE(delete_received.load());
  23330. }
  23331. // Test: on_error callback on connection failure
  23332. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23333. // Connect to a non-existent port
  23334. Client client("localhost", 59999);
  23335. sse::SSEClient sse(client, "/events");
  23336. std::atomic<bool> error_called{false};
  23337. Error received_error = Error::Success;
  23338. sse.on_error([&](Error err) {
  23339. error_called.store(true);
  23340. received_error = err;
  23341. });
  23342. sse.set_reconnect_interval(50);
  23343. sse.set_max_reconnect_attempts(1);
  23344. sse.start_async();
  23345. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23346. sse.stop();
  23347. EXPECT_TRUE(error_called.load());
  23348. EXPECT_NE(received_error, Error::Success);
  23349. }
  23350. // Test: Last-Event-ID header sent on reconnect
  23351. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23352. // Endpoint that sends event with ID
  23353. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23354. res.set_chunked_content_provider(
  23355. "text/event-stream", [](size_t offset, DataSink &sink) {
  23356. if (offset == 0) {
  23357. std::string event = "id: evt-123\ndata: test\n\n";
  23358. sink.write(event.data(), event.size());
  23359. }
  23360. return false;
  23361. });
  23362. });
  23363. Client client("localhost", get_port());
  23364. sse::SSEClient sse(client, "/event-with-id");
  23365. std::atomic<bool> id_received{false};
  23366. sse.on_message([&](const sse::SSEMessage &msg) {
  23367. if (!msg.id.empty()) { id_received.store(true); }
  23368. });
  23369. sse.set_reconnect_interval(100);
  23370. sse.set_max_reconnect_attempts(1);
  23371. sse.start_async();
  23372. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23373. sse.stop();
  23374. EXPECT_TRUE(id_received.load());
  23375. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23376. }
  23377. // Test: last_event_id() read from another thread while start_async() runs
  23378. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23379. // Ids of every length up to 200, so the stored id keeps changing size
  23380. server_->Get("/many-ids", [](const Request &, Response &res) {
  23381. res.set_chunked_content_provider(
  23382. "text/event-stream", [](size_t offset, DataSink &sink) {
  23383. if (offset == 0) {
  23384. std::string events;
  23385. for (size_t i = 0; i < 2000; i++) {
  23386. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23387. events += "data: x\n\n";
  23388. }
  23389. events += "id: end\ndata: x\n\n";
  23390. sink.write(events.data(), events.size());
  23391. }
  23392. return false;
  23393. });
  23394. });
  23395. Client client("localhost", get_port());
  23396. sse::SSEClient sse(client, "/many-ids");
  23397. // Wait out the rest of the test rather than replay the stream
  23398. sse.set_reconnect_interval(10000);
  23399. sse.set_max_reconnect_attempts(1);
  23400. sse.start_async();
  23401. auto well_formed = true;
  23402. std::string id;
  23403. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23404. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23405. id = sse.last_event_id();
  23406. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23407. well_formed = false;
  23408. }
  23409. }
  23410. sse.stop();
  23411. EXPECT_TRUE(well_formed);
  23412. EXPECT_EQ(sse.last_event_id(), "end");
  23413. }
  23414. // Test: Manual stop
  23415. TEST_F(SSEIntegrationTest, ManualStop) {
  23416. // Endpoint that sends one event and stays open briefly. The server outlives
  23417. // this test body, so the provider uses the fixture's flag, not a local.
  23418. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23419. res.set_chunked_content_provider(
  23420. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23421. if (offset == 0) {
  23422. std::string event = "data: connected\n\n";
  23423. sink.write(event.data(), event.size());
  23424. }
  23425. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23426. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23427. }
  23428. return false;
  23429. });
  23430. });
  23431. Client client("localhost", get_port());
  23432. sse::SSEClient sse(client, "/stay-open");
  23433. std::atomic<bool> connected{false};
  23434. sse.on_open([&connected]() { connected.store(true); });
  23435. sse.set_reconnect_interval(100);
  23436. sse.set_max_reconnect_attempts(1);
  23437. sse.start_async();
  23438. // Wait for connection to establish
  23439. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23440. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23441. }
  23442. EXPECT_TRUE(connected.load());
  23443. EXPECT_TRUE(sse.is_connected());
  23444. // Signal handler to stop
  23445. stop_server_.store(true);
  23446. // Stop SSE client
  23447. sse.stop();
  23448. EXPECT_FALSE(sse.is_connected());
  23449. }
  23450. // Sends one event, then nothing until stop is set
  23451. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23452. return [&stop](const Request &, Response &res) {
  23453. res.set_chunked_content_provider(
  23454. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23455. if (offset == 0) {
  23456. std::string event = "data: hello\n\n";
  23457. sink.write(event.data(), event.size());
  23458. }
  23459. while (!stop.load()) {
  23460. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23461. }
  23462. return false;
  23463. });
  23464. };
  23465. }
  23466. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23467. static void check_stop_interrupts_blocked_read(Client &client) {
  23468. client.set_read_timeout(30, 0);
  23469. for (auto by_destructor : {false, true}) {
  23470. std::atomic<bool> received{false};
  23471. std::chrono::steady_clock::time_point start;
  23472. {
  23473. sse::SSEClient sse(client, "/idle-stream");
  23474. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23475. sse.start_async();
  23476. for (int i = 0; i < 500 && !received.load(); ++i) {
  23477. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23478. }
  23479. ASSERT_TRUE(received.load());
  23480. // Let the client block in the next read
  23481. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23482. start = std::chrono::steady_clock::now();
  23483. if (!by_destructor) { sse.stop(); }
  23484. }
  23485. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23486. std::chrono::seconds(2));
  23487. }
  23488. }
  23489. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23490. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23491. Client client("localhost", get_port());
  23492. check_stop_interrupts_blocked_read(client);
  23493. }
  23494. #ifdef CPPHTTPLIB_SSL_ENABLED
  23495. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23497. std::atomic<bool> done{false};
  23498. svr.Get("/idle-stream", idle_event_stream(done));
  23499. auto port = svr.bind_to_any_port(HOST);
  23500. std::thread t([&] { svr.listen_after_bind(); });
  23501. auto se = detail::scope_exit([&] {
  23502. done.store(true);
  23503. svr.stop();
  23504. t.join();
  23505. });
  23506. svr.wait_until_ready();
  23507. Client client("https://localhost:" + std::to_string(port));
  23508. client.enable_server_certificate_verification(false);
  23509. check_stop_interrupts_blocked_read(client);
  23510. }
  23511. #endif
  23512. // Test: SSEClient with custom headers
  23513. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23514. // Setup a server endpoint that checks for custom header
  23515. std::atomic<bool> header_received{false};
  23516. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23517. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23518. header_received.store(true);
  23519. }
  23520. res.set_chunked_content_provider("text/event-stream",
  23521. [](size_t, DataSink &) { return false; });
  23522. });
  23523. Client client("localhost", get_port());
  23524. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23525. sse::SSEClient sse(client, "/header-check", headers);
  23526. sse.set_max_reconnect_attempts(1);
  23527. sse.start_async();
  23528. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23529. sse.stop();
  23530. EXPECT_TRUE(header_received.load());
  23531. }
  23532. // Test: Reconnect interval configuration
  23533. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23534. Client client("localhost", get_port());
  23535. sse::SSEClient sse(client, "/events");
  23536. auto &result = sse.set_reconnect_interval(500);
  23537. // Builder pattern should return reference to self
  23538. EXPECT_EQ(&result, &sse);
  23539. }
  23540. // Test: Max reconnect attempts
  23541. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23542. // Connect to non-existent port to force reconnects
  23543. Client client("localhost", 59998);
  23544. sse::SSEClient sse(client, "/events");
  23545. std::atomic<int> error_count{0};
  23546. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23547. sse.set_reconnect_interval(50);
  23548. sse.set_max_reconnect_attempts(2);
  23549. auto start = std::chrono::steady_clock::now();
  23550. sse.start(); // Blocking call
  23551. auto end = std::chrono::steady_clock::now();
  23552. // Should have stopped after 2 failed attempts
  23553. EXPECT_GE(error_count.load(), 2);
  23554. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23555. auto duration =
  23556. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23557. #ifdef _WIN32
  23558. // Windows is much slower for socket connection failures
  23559. EXPECT_LT(duration.count(), 7000);
  23560. #else
  23561. EXPECT_LT(duration.count(), 1000);
  23562. #endif
  23563. }
  23564. // Test: Multi-line data in integration
  23565. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23566. // Endpoint with multi-line data
  23567. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23568. res.set_chunked_content_provider(
  23569. "text/event-stream", [](size_t offset, DataSink &sink) {
  23570. if (offset == 0) {
  23571. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23572. sink.write(event.data(), event.size());
  23573. }
  23574. return false;
  23575. });
  23576. });
  23577. Client client("localhost", get_port());
  23578. sse::SSEClient sse(client, "/multiline-data");
  23579. std::string received_data;
  23580. std::mutex data_mutex;
  23581. sse.on_message([&](const sse::SSEMessage &msg) {
  23582. std::lock_guard<std::mutex> lock(data_mutex);
  23583. received_data = msg.data;
  23584. });
  23585. sse.set_reconnect_interval(100);
  23586. sse.set_max_reconnect_attempts(1);
  23587. sse.start_async();
  23588. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23589. sse.stop();
  23590. std::lock_guard<std::mutex> lock(data_mutex);
  23591. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23592. }
  23593. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23594. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23595. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23596. DataSink &sink) {
  23597. if (offset == 0) {
  23598. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23599. sink.write(events.data(), events.size());
  23600. }
  23601. return false;
  23602. });
  23603. });
  23604. Client client("localhost", get_port());
  23605. sse::SSEClient sse(client, "/empty-data-lines");
  23606. std::mutex mutex;
  23607. std::condition_variable cv;
  23608. std::vector<std::string> received;
  23609. sse.on_message([&](const sse::SSEMessage &msg) {
  23610. std::lock_guard<std::mutex> lock(mutex);
  23611. received.push_back(msg.data);
  23612. cv.notify_all();
  23613. });
  23614. sse.set_max_reconnect_attempts(1);
  23615. sse.start_async();
  23616. {
  23617. std::unique_lock<std::mutex> lock(mutex);
  23618. cv.wait_for(lock, std::chrono::seconds(2),
  23619. [&] { return received.size() >= 3; });
  23620. }
  23621. sse.stop();
  23622. ASSERT_GE(received.size(), 3u);
  23623. EXPECT_EQ(received[0], "");
  23624. EXPECT_EQ(received[1], "\nhello");
  23625. EXPECT_EQ(received[2], "");
  23626. }
  23627. // Test: Auto-reconnect after server disconnection
  23628. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23629. std::atomic<int> connection_count{0};
  23630. std::atomic<int> message_count{0};
  23631. // Endpoint that sends one event and closes, forcing reconnect
  23632. server_->Get("/reconnect-test",
  23633. [&connection_count](const Request &, Response &res) {
  23634. connection_count.fetch_add(1);
  23635. res.set_chunked_content_provider(
  23636. "text/event-stream", [](size_t offset, DataSink &sink) {
  23637. if (offset == 0) {
  23638. std::string event = "data: hello\n\n";
  23639. sink.write(event.data(), event.size());
  23640. }
  23641. return false; // Close connection after sending
  23642. });
  23643. });
  23644. Client client("localhost", get_port());
  23645. sse::SSEClient sse(client, "/reconnect-test");
  23646. sse.on_message([&message_count](const sse::SSEMessage &) {
  23647. message_count.fetch_add(1);
  23648. });
  23649. sse.set_reconnect_interval(100);
  23650. sse.set_max_reconnect_attempts(3);
  23651. sse.start_async();
  23652. // Wait long enough for multiple reconnects
  23653. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23654. sse.stop();
  23655. // Should have connected multiple times (initial + reconnects)
  23656. EXPECT_GE(connection_count.load(), 2);
  23657. // Should have received messages from multiple connections
  23658. EXPECT_GE(message_count.load(), 2);
  23659. }
  23660. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23661. std::atomic<int> connection_count{0};
  23662. // Neither Content-Length nor chunked: the close ends the stream
  23663. server_->Get("/close-delimited",
  23664. [&connection_count](const Request &, Response &res) {
  23665. connection_count.fetch_add(1);
  23666. res.set_content_provider(
  23667. "text/event-stream", [](size_t offset, DataSink &sink) {
  23668. if (offset == 0) {
  23669. std::string event = "data: hello\n\n";
  23670. sink.write(event.data(), event.size());
  23671. } else {
  23672. sink.done();
  23673. }
  23674. return true;
  23675. });
  23676. });
  23677. Client client("localhost", get_port());
  23678. sse::SSEClient sse(client, "/close-delimited");
  23679. std::atomic<int> error_count{0};
  23680. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23681. sse.set_reconnect_interval(100);
  23682. sse.start_async();
  23683. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23684. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23685. }
  23686. sse.stop();
  23687. // Reconnects as after any end of the stream, but reports no error
  23688. EXPECT_GE(connection_count.load(), 2);
  23689. EXPECT_EQ(0, error_count.load());
  23690. }
  23691. // Test: A retry field of all ASCII digits sets the reconnection time
  23692. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23693. std::mutex mutex;
  23694. std::condition_variable cv;
  23695. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23696. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23697. {
  23698. std::lock_guard<std::mutex> lock(mutex);
  23699. connected_at.push_back(std::chrono::steady_clock::now());
  23700. cv.notify_all();
  23701. }
  23702. res.set_chunked_content_provider(
  23703. "text/event-stream", [](size_t offset, DataSink &sink) {
  23704. if (offset == 0) {
  23705. std::string event = "retry: 0\ndata: hello\n\n";
  23706. sink.write(event.data(), event.size());
  23707. }
  23708. return false;
  23709. });
  23710. });
  23711. Client client("localhost", get_port());
  23712. sse::SSEClient sse(client, "/zero-retry");
  23713. sse.set_reconnect_interval(10000);
  23714. sse.start_async();
  23715. {
  23716. std::unique_lock<std::mutex> lock(mutex);
  23717. cv.wait_for(lock, std::chrono::seconds(5),
  23718. [&] { return connected_at.size() >= 2; });
  23719. }
  23720. sse.stop();
  23721. // The server-supplied interval is applied, but never below 100ms, so
  23722. // "retry: 0" does not cause a busy reconnect loop
  23723. std::lock_guard<std::mutex> lock(mutex);
  23724. ASSERT_GE(connected_at.size(), 2u);
  23725. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23726. connected_at[1] - connected_at[0])
  23727. .count();
  23728. EXPECT_GE(interval_ms, 100);
  23729. }
  23730. // Test: Last-Event-ID sent on reconnect
  23731. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23732. std::atomic<int> connection_count{0};
  23733. std::vector<std::string> received_last_event_ids;
  23734. std::mutex id_mutex;
  23735. // Endpoint that checks Last-Event-ID header and sends event with ID
  23736. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23737. int conn = connection_count.fetch_add(1);
  23738. // Capture the Last-Event-ID header from each connection
  23739. {
  23740. std::lock_guard<std::mutex> lock(id_mutex);
  23741. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23742. }
  23743. res.set_chunked_content_provider(
  23744. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23745. if (offset == 0) {
  23746. std::string event =
  23747. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23748. sink.write(event.data(), event.size());
  23749. }
  23750. return false;
  23751. });
  23752. });
  23753. Client client("localhost", get_port());
  23754. sse::SSEClient sse(client, "/reconnect-with-id");
  23755. sse.set_reconnect_interval(100);
  23756. sse.set_max_reconnect_attempts(3);
  23757. sse.start_async();
  23758. // Wait for at least 2 connections
  23759. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23760. sse.stop();
  23761. // Verify behavior
  23762. std::lock_guard<std::mutex> lock(id_mutex);
  23763. EXPECT_GE(received_last_event_ids.size(), 2u);
  23764. // First connection should have no Last-Event-ID
  23765. if (!received_last_event_ids.empty()) {
  23766. EXPECT_EQ(received_last_event_ids[0], "");
  23767. }
  23768. // Second connection should have Last-Event-ID from first connection
  23769. if (received_last_event_ids.size() >= 2) {
  23770. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23771. }
  23772. }
  23773. // Test: set_headers updates headers used on reconnect
  23774. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23775. std::vector<std::string> received_tokens;
  23776. std::mutex token_mutex;
  23777. // Endpoint that captures Authorization header
  23778. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23779. {
  23780. std::lock_guard<std::mutex> lock(token_mutex);
  23781. received_tokens.push_back(req.get_header_value("Authorization"));
  23782. }
  23783. res.set_chunked_content_provider(
  23784. "text/event-stream", [](size_t offset, DataSink &sink) {
  23785. if (offset == 0) {
  23786. std::string event = "data: hello\n\n";
  23787. sink.write(event.data(), event.size());
  23788. }
  23789. return false; // Close connection to trigger reconnect
  23790. });
  23791. });
  23792. Client client("localhost", get_port());
  23793. Headers headers = {{"Authorization", "Bearer old-token"}};
  23794. sse::SSEClient sse(client, "/auth-check", headers);
  23795. // Update headers on each successful connection
  23796. sse.on_open(
  23797. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23798. sse.set_reconnect_interval(100);
  23799. sse.set_max_reconnect_attempts(3);
  23800. sse.start_async();
  23801. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23802. sse.stop();
  23803. std::lock_guard<std::mutex> lock(token_mutex);
  23804. ASSERT_GE(received_tokens.size(), 2u);
  23805. // First connection uses original header
  23806. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23807. // Second connection uses updated header from set_headers
  23808. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23809. }
  23810. // Test: 401 allows reconnection (so on_error can refresh headers)
  23811. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23812. std::atomic<int> connection_count{0};
  23813. // Endpoint: returns 401 on first attempt, 200 on second
  23814. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23815. int conn = connection_count.fetch_add(1);
  23816. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23817. res.status = StatusCode::Unauthorized_401;
  23818. res.set_content("Unauthorized", "text/plain");
  23819. return;
  23820. }
  23821. res.set_chunked_content_provider(
  23822. "text/event-stream", [](size_t offset, DataSink &sink) {
  23823. if (offset == 0) {
  23824. std::string event = "data: authenticated\n\n";
  23825. sink.write(event.data(), event.size());
  23826. }
  23827. return false;
  23828. });
  23829. });
  23830. Client client("localhost", get_port());
  23831. Headers headers = {{"Authorization", "Bearer expired"}};
  23832. sse::SSEClient sse(client, "/auth-retry", headers);
  23833. std::atomic<bool> message_received{false};
  23834. // Refresh token on error
  23835. sse.on_error(
  23836. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23837. sse.on_message([&](const sse::SSEMessage &msg) {
  23838. if (msg.data == "authenticated") { message_received.store(true); }
  23839. });
  23840. sse.set_reconnect_interval(100);
  23841. sse.set_max_reconnect_attempts(3);
  23842. sse.start_async();
  23843. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23844. sse.stop();
  23845. // Should have reconnected after 401 and succeeded with new token
  23846. EXPECT_GE(connection_count.load(), 2);
  23847. EXPECT_TRUE(message_received.load());
  23848. }
  23849. TEST(Issue2318Test, EmptyHostString) {
  23850. {
  23851. httplib::Client cli_empty("", PORT);
  23852. auto res = cli_empty.Get("/");
  23853. ASSERT_FALSE(res);
  23854. EXPECT_EQ(httplib::Error::Connection, res.error());
  23855. }
  23856. {
  23857. httplib::Client cli(" ", PORT);
  23858. auto res = cli.Get("/");
  23859. ASSERT_FALSE(res);
  23860. EXPECT_EQ(httplib::Error::Connection, res.error());
  23861. }
  23862. }
  23863. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23864. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23865. Server svr;
  23866. // Set a small payload limit (1KB)
  23867. svr.set_payload_max_length(1024);
  23868. svr.Post("/test", [&](const Request &req, Response &res) {
  23869. res.set_content("Body size: " + std::to_string(req.body.size()),
  23870. "text/plain");
  23871. });
  23872. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23873. auto se = detail::scope_exit([&] {
  23874. svr.stop();
  23875. listen_thread.join();
  23876. });
  23877. svr.wait_until_ready();
  23878. // Create data that compresses well but exceeds limit when decompressed
  23879. // 8KB of repeated null bytes compresses to a very small size
  23880. std::string original_data(8 * 1024, '\0');
  23881. // Compress the data using gzip
  23882. std::string compressed_data;
  23883. detail::gzip_compressor compressor;
  23884. compressor.compress(original_data.data(), original_data.size(), true,
  23885. [&](const char *data, size_t size) {
  23886. compressed_data.append(data, size);
  23887. return true;
  23888. });
  23889. // Verify compression worked (compressed should be much smaller)
  23890. ASSERT_LT(compressed_data.size(), original_data.size());
  23891. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23892. // Send compressed data with Content-Encoding: gzip
  23893. Client cli(HOST, PORT);
  23894. Headers headers = {{"Content-Encoding", "gzip"}};
  23895. auto res =
  23896. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23897. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23899. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23900. }
  23901. #endif
  23902. // ============================================================================
  23903. // OpenSSL-Specific Tests
  23904. // ============================================================================
  23905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23906. X509 *readCertificate(const std::string &strFileName) {
  23907. std::ifstream inStream(strFileName);
  23908. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23909. std::istreambuf_iterator<char>());
  23910. if (strCertPEM.empty()) return (nullptr);
  23911. BIO *pbCert = BIO_new(BIO_s_mem());
  23912. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23913. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23914. BIO_free(pbCert);
  23915. return (pCert);
  23916. }
  23917. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23918. std::ifstream inStream(strFileName);
  23919. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23920. std::istreambuf_iterator<char>());
  23921. if (strPrivateKeyPEM.empty()) return (nullptr);
  23922. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23923. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23924. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23925. BIO_free(pbPrivKey);
  23926. return (pPrivateKey);
  23927. }
  23928. TEST(BindServerTest, UpdateCerts) {
  23929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23930. int port = svr.bind_to_any_port("0.0.0.0");
  23931. ASSERT_TRUE(svr.is_valid());
  23932. ASSERT_TRUE(port > 0);
  23933. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23934. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23935. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23936. ASSERT_TRUE(cert != nullptr);
  23937. ASSERT_TRUE(ca_cert != nullptr);
  23938. ASSERT_TRUE(key != nullptr);
  23939. X509_STORE *cert_store = X509_STORE_new();
  23940. X509_STORE_add_cert(cert_store, ca_cert);
  23941. // svr.update_certs(cert, key, cert_store); // deprecated
  23942. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23943. CLIENT_CA_CERT_FILE);
  23944. ASSERT_TRUE(svr.is_valid());
  23945. svr.stop();
  23946. X509_STORE_free(cert_store);
  23947. X509_free(cert);
  23948. X509_free(ca_cert);
  23949. EVP_PKEY_free(key);
  23950. }
  23951. // Test that update_certs() updates client CA list correctly
  23952. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23953. // Start with file-based constructor
  23954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23955. ASSERT_TRUE(svr.is_valid());
  23956. // Initially no client CA list should be set
  23957. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23958. ASSERT_TRUE(ssl_ctx != nullptr);
  23959. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23960. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23961. // Now update with client CA (PEM string)
  23962. std::string cert_pem, key_pem, ca_pem;
  23963. read_file(SERVER_CERT_FILE, cert_pem);
  23964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23966. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23967. ASSERT_TRUE(svr.is_valid());
  23968. // Now client CA list should be set
  23969. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23970. ASSERT_TRUE(ca_list_after != nullptr);
  23971. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23972. }
  23973. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23974. // Test that the file-path SSLServer constructor properly sets the client CA
  23975. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23977. ASSERT_TRUE(svr.is_valid());
  23978. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23979. ASSERT_TRUE(ssl_ctx != nullptr);
  23980. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23981. ASSERT_TRUE(ca_list != nullptr);
  23982. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23983. }
  23984. #endif
  23985. // ============================================================================
  23986. // MbedTLS-Specific Tests
  23987. // ============================================================================
  23988. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23989. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23990. using namespace httplib::tls;
  23991. // Track if callback was invoked
  23992. bool callback_invoked = false;
  23993. // The callback receives void* ctx which is actually MbedTlsContext*
  23994. // We can access the mbedtls_ssl_config via the context
  23995. auto setup_callback = [&callback_invoked](void *ctx) {
  23996. callback_invoked = true;
  23997. // Cast to MbedTlsContext* to access the ssl config
  23998. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23999. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24000. // Use static variables to hold certificate data (simplified for test)
  24001. static mbedtls_x509_crt own_cert;
  24002. static mbedtls_pk_context own_key;
  24003. static mbedtls_x509_crt ca_chain;
  24004. static bool initialized = false;
  24005. if (!initialized) {
  24006. mbedtls_x509_crt_init(&own_cert);
  24007. mbedtls_pk_init(&own_key);
  24008. mbedtls_x509_crt_init(&ca_chain);
  24009. // Load server certificate
  24010. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24011. return false;
  24012. }
  24013. // Load server private key.
  24014. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24015. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24016. #if MBEDTLS_VERSION_MAJOR == 3
  24017. ,
  24018. mbedtls_ctr_drbg_random, nullptr
  24019. #endif
  24020. ) != 0) {
  24021. return false;
  24022. }
  24023. // Load CA chain for client verification
  24024. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24025. return false;
  24026. }
  24027. initialized = true;
  24028. }
  24029. // Configure the SSL config
  24030. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24031. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24032. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24033. // Set minimum TLS version using mbedTLS native API
  24034. #if MBEDTLS_VERSION_MAJOR >= 3
  24035. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24036. #else
  24037. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24038. MBEDTLS_SSL_MINOR_VERSION_3);
  24039. #endif
  24040. return true;
  24041. };
  24042. SSLServer svr(setup_callback);
  24043. ASSERT_TRUE(svr.is_valid());
  24044. ASSERT_TRUE(callback_invoked);
  24045. svr.Get("/test", [&](const Request &req, Response &res) {
  24046. res.set_content("test", "text/plain");
  24047. auto cert = req.peer_cert();
  24048. ASSERT_TRUE(static_cast<bool>(cert));
  24049. auto common_name = cert.subject_cn();
  24050. EXPECT_EQ("Common Name", common_name);
  24051. });
  24052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24053. auto se = detail::scope_exit([&] {
  24054. svr.stop();
  24055. t.join();
  24056. ASSERT_FALSE(svr.is_running());
  24057. });
  24058. svr.wait_until_ready();
  24059. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24060. cli.enable_server_certificate_verification(false);
  24061. cli.set_connection_timeout(30);
  24062. auto res = cli.Get("/test");
  24063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24064. ASSERT_EQ(StatusCode::OK_200, res->status);
  24065. }
  24066. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24067. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24068. // keep-alive SSL session, which reads through that config in
  24069. // mbedtls_ssl_close_notify.
  24070. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24072. ASSERT_TRUE(svr.is_valid());
  24073. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24074. res.set_content("test", "text/plain");
  24075. });
  24076. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24077. auto se = detail::scope_exit([&] {
  24078. svr.stop();
  24079. t.join();
  24080. ASSERT_FALSE(svr.is_running());
  24081. });
  24082. svr.wait_until_ready();
  24083. {
  24084. SSLClient cli(HOST, PORT);
  24085. cli.enable_server_certificate_verification(false);
  24086. cli.set_keep_alive(true);
  24087. auto res = cli.Get("/test");
  24088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24089. ASSERT_EQ(StatusCode::OK_200, res->status);
  24090. // cli is destructed here with the keep-alive SSL session still open.
  24091. }
  24092. }
  24093. #endif
  24094. // WebSocket Tests
  24095. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24096. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24097. // defining the meaning of these bits has been negotiated.
  24098. auto make_frame = [](uint8_t first_byte) {
  24099. std::string frame;
  24100. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24101. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24102. frame += "Hello";
  24103. return frame;
  24104. };
  24105. // RSV1 set (0x40)
  24106. {
  24107. detail::BufferStream strm;
  24108. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24109. ws::Opcode opcode;
  24110. std::string payload;
  24111. bool fin;
  24112. EXPECT_EQ(
  24113. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24114. ws::impl::FrameRead::Fail);
  24115. }
  24116. // RSV2 set (0x20)
  24117. {
  24118. detail::BufferStream strm;
  24119. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24120. ws::Opcode opcode;
  24121. std::string payload;
  24122. bool fin;
  24123. EXPECT_EQ(
  24124. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24125. ws::impl::FrameRead::Fail);
  24126. }
  24127. // RSV3 set (0x10)
  24128. {
  24129. detail::BufferStream strm;
  24130. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24131. ws::Opcode opcode;
  24132. std::string payload;
  24133. bool fin;
  24134. EXPECT_EQ(
  24135. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24136. ws::impl::FrameRead::Fail);
  24137. }
  24138. // No RSV bits set - should succeed
  24139. {
  24140. detail::BufferStream strm;
  24141. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24142. ws::Opcode opcode;
  24143. std::string payload;
  24144. bool fin;
  24145. EXPECT_EQ(
  24146. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24147. ws::impl::FrameRead::Ok);
  24148. EXPECT_EQ(ws::Opcode::Text, opcode);
  24149. EXPECT_EQ("Hello", payload);
  24150. EXPECT_TRUE(fin);
  24151. }
  24152. }
  24153. TEST(WebSocketTest, ControlFrameValidation) {
  24154. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24155. // payload length <= 125.
  24156. // Ping with FIN=0 - must be rejected
  24157. {
  24158. detail::BufferStream strm;
  24159. std::string frame;
  24160. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24161. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24162. strm.write(frame.data(), frame.size());
  24163. ws::Opcode opcode;
  24164. std::string payload;
  24165. bool fin;
  24166. EXPECT_EQ(
  24167. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24168. ws::impl::FrameRead::Fail);
  24169. }
  24170. // Close with FIN=0 - must be rejected
  24171. {
  24172. detail::BufferStream strm;
  24173. std::string frame;
  24174. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24175. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24176. strm.write(frame.data(), frame.size());
  24177. ws::Opcode opcode;
  24178. std::string payload;
  24179. bool fin;
  24180. EXPECT_EQ(
  24181. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24182. ws::impl::FrameRead::Fail);
  24183. }
  24184. // Ping with payload_len=126 (extended length) - must be rejected
  24185. {
  24186. detail::BufferStream strm;
  24187. std::string frame;
  24188. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24189. frame += static_cast<char>(126); // payload_len=126 (>125)
  24190. frame += static_cast<char>(0x00); // extended length high byte
  24191. frame += static_cast<char>(126); // extended length low byte
  24192. frame += std::string(126, 'x');
  24193. strm.write(frame.data(), frame.size());
  24194. ws::Opcode opcode;
  24195. std::string payload;
  24196. bool fin;
  24197. EXPECT_EQ(
  24198. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24199. ws::impl::FrameRead::Fail);
  24200. }
  24201. // Ping with FIN=1 and payload_len=125 - should succeed
  24202. {
  24203. detail::BufferStream strm;
  24204. std::string frame;
  24205. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24206. frame += static_cast<char>(125); // payload_len=125
  24207. frame += std::string(125, 'x');
  24208. strm.write(frame.data(), frame.size());
  24209. ws::Opcode opcode;
  24210. std::string payload;
  24211. bool fin;
  24212. EXPECT_EQ(
  24213. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24214. ws::impl::FrameRead::Ok);
  24215. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24216. EXPECT_EQ(125u, payload.size());
  24217. EXPECT_TRUE(fin);
  24218. }
  24219. }
  24220. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24221. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24222. // length MUST be 0.
  24223. // MSB set - must be rejected
  24224. {
  24225. detail::BufferStream strm;
  24226. std::string frame;
  24227. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24228. frame += static_cast<char>(127); // 64-bit extended length
  24229. frame += static_cast<char>(0x80); // MSB set (invalid)
  24230. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24231. strm.write(frame.data(), frame.size());
  24232. ws::Opcode opcode;
  24233. std::string payload;
  24234. bool fin;
  24235. EXPECT_EQ(
  24236. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24237. ws::impl::FrameRead::Fail);
  24238. }
  24239. // MSB clear - should pass length parsing (will be rejected by max_len,
  24240. // but that's a different check; use a small length to verify)
  24241. {
  24242. detail::BufferStream strm;
  24243. std::string frame;
  24244. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24245. frame += static_cast<char>(127); // 64-bit extended length
  24246. frame += std::string(7, '\0'); // high bytes = 0
  24247. frame += static_cast<char>(0x03); // length = 3
  24248. frame += "abc";
  24249. strm.write(frame.data(), frame.size());
  24250. ws::Opcode opcode;
  24251. std::string payload;
  24252. bool fin;
  24253. EXPECT_EQ(
  24254. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24255. ws::impl::FrameRead::Ok);
  24256. EXPECT_EQ(ws::Opcode::Text, opcode);
  24257. EXPECT_EQ("abc", payload);
  24258. }
  24259. }
  24260. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24261. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24262. // Valid UTF-8
  24263. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24264. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24265. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24266. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24267. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24268. // Invalid UTF-8
  24269. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24270. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24271. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24272. EXPECT_FALSE(
  24273. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24274. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24275. }
  24276. TEST(WebSocketTest, ConnectAndDisconnect) {
  24277. Server svr;
  24278. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24279. std::string msg;
  24280. while (ws.read(msg)) {}
  24281. });
  24282. auto port = svr.bind_to_any_port(HOST);
  24283. std::thread t([&]() { svr.listen_after_bind(); });
  24284. svr.wait_until_ready();
  24285. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24286. auto res = client.connect();
  24287. ASSERT_TRUE(res);
  24288. EXPECT_EQ(Error::Success, res.error());
  24289. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24290. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24291. EXPECT_TRUE(client.is_open());
  24292. client.close();
  24293. EXPECT_FALSE(client.is_open());
  24294. svr.stop();
  24295. t.join();
  24296. }
  24297. TEST(WebSocketTest, ValidURL) {
  24298. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24299. EXPECT_TRUE(ws1.is_valid());
  24300. ws::WebSocketClient ws2("ws://example.com/path");
  24301. EXPECT_TRUE(ws2.is_valid());
  24302. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24303. EXPECT_TRUE(ws3.is_valid());
  24304. #ifdef CPPHTTPLIB_SSL_ENABLED
  24305. ws::WebSocketClient wss1("wss://example.com/path");
  24306. EXPECT_TRUE(wss1.is_valid());
  24307. ws::WebSocketClient wss2("wss://example.com:443/path");
  24308. EXPECT_TRUE(wss2.is_valid());
  24309. #endif
  24310. }
  24311. TEST(WebSocketTest, InvalidURL) {
  24312. // No scheme
  24313. ws::WebSocketClient ws1("localhost:8080/path");
  24314. EXPECT_FALSE(ws1.is_valid());
  24315. // No path
  24316. ws::WebSocketClient ws2("ws://localhost:8080");
  24317. EXPECT_FALSE(ws2.is_valid());
  24318. // Empty string
  24319. ws::WebSocketClient ws3("");
  24320. EXPECT_FALSE(ws3.is_valid());
  24321. // Missing host
  24322. ws::WebSocketClient ws4("ws://:8080/path");
  24323. EXPECT_FALSE(ws4.is_valid());
  24324. // Port number overflow — should not crash
  24325. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24326. EXPECT_FALSE(ws5.is_valid());
  24327. // Port out of range
  24328. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24329. EXPECT_FALSE(ws6.is_valid());
  24330. }
  24331. TEST(WebSocketTest, UnsupportedScheme) {
  24332. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24333. ws::WebSocketClient ws1("http://localhost:8080/path");
  24334. EXPECT_FALSE(ws1.is_valid());
  24335. ws::WebSocketClient ws2("https://localhost:8080/path");
  24336. EXPECT_FALSE(ws2.is_valid());
  24337. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24338. EXPECT_FALSE(ws3.is_valid());
  24339. #else
  24340. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24341. std::invalid_argument);
  24342. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24343. std::invalid_argument);
  24344. #endif
  24345. }
  24346. TEST(WebSocketTest, ConnectWhenInvalid) {
  24347. ws::WebSocketClient ws("not a valid url");
  24348. EXPECT_FALSE(ws.is_valid());
  24349. auto res = ws.connect();
  24350. EXPECT_FALSE(res);
  24351. EXPECT_EQ(Error::Connection, res.error());
  24352. EXPECT_EQ(-1, res.status());
  24353. }
  24354. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24355. // Grab a port that is free, then close it again so nothing listens there
  24356. Server svr;
  24357. auto port = svr.bind_to_any_port(HOST);
  24358. svr.stop();
  24359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24360. auto res = client.connect();
  24361. ASSERT_FALSE(res);
  24362. EXPECT_EQ(Error::Connection, res.error());
  24363. EXPECT_EQ(-1, res.status());
  24364. }
  24365. TEST(WebSocketTest, DefaultPort) {
  24366. ws::WebSocketClient ws1("ws://example.com/path");
  24367. EXPECT_TRUE(ws1.is_valid());
  24368. // ws:// defaults to port 80 (verified by successful parse)
  24369. #ifdef CPPHTTPLIB_SSL_ENABLED
  24370. ws::WebSocketClient ws2("wss://example.com/path");
  24371. EXPECT_TRUE(ws2.is_valid());
  24372. // wss:// defaults to port 443 (verified by successful parse)
  24373. #endif
  24374. }
  24375. TEST(WebSocketTest, IPv6LiteralAddress) {
  24376. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24377. EXPECT_TRUE(ws1.is_valid());
  24378. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24379. EXPECT_TRUE(ws2.is_valid());
  24380. }
  24381. TEST(WebSocketTest, ComplexPath) {
  24382. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24383. EXPECT_TRUE(ws1.is_valid());
  24384. ws::WebSocketClient ws2("ws://localhost:8080/");
  24385. EXPECT_TRUE(ws2.is_valid());
  24386. }
  24387. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24388. Server svr;
  24389. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24390. std::string msg;
  24391. while (ws.read(msg)) {}
  24392. });
  24393. auto port = svr.bind_to_any_port(HOST);
  24394. std::thread t([&]() { svr.listen_after_bind(); });
  24395. svr.wait_until_ready();
  24396. auto another_host = "example.com";
  24397. auto wrong_ip = "192.0.2.1";
  24398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24399. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24400. ASSERT_TRUE(client.connect());
  24401. EXPECT_TRUE(client.is_open());
  24402. client.close();
  24403. svr.stop();
  24404. t.join();
  24405. }
  24406. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24407. Server svr;
  24408. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24409. std::string msg;
  24410. while (ws.read(msg)) {}
  24411. });
  24412. auto port = svr.bind_to_any_port(HOST);
  24413. std::thread t([&]() { svr.listen_after_bind(); });
  24414. svr.wait_until_ready();
  24415. auto wrong_ip = "192.0.2.1";
  24416. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24417. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24418. client.set_connection_timeout(1);
  24419. client.set_read_timeout(1);
  24420. client.set_write_timeout(1);
  24421. EXPECT_FALSE(client.connect());
  24422. EXPECT_FALSE(client.is_open());
  24423. svr.stop();
  24424. t.join();
  24425. }
  24426. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24427. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24428. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24429. // (RFC 6761) is only a map key and the Host header value.
  24430. auto host = "target.invalid";
  24431. Server svr;
  24432. std::string received_host;
  24433. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24434. received_host = req.get_header_value("Host");
  24435. std::string msg;
  24436. while (ws.read(msg)) {}
  24437. });
  24438. auto port = svr.bind_to_any_port(HOST);
  24439. std::thread t([&]() { svr.listen_after_bind(); });
  24440. // ASSERT_* below returns from the test body, which would leave t joinable
  24441. // and make ~thread call std::terminate.
  24442. auto se = detail::scope_exit([&] {
  24443. svr.stop();
  24444. if (t.joinable()) { t.join(); }
  24445. });
  24446. svr.wait_until_ready();
  24447. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24448. std::to_string(port) + "/ws");
  24449. client.set_direct_hostname_addr_map({{host, HOST}});
  24450. ASSERT_TRUE(client.connect());
  24451. EXPECT_TRUE(client.is_open());
  24452. client.close();
  24453. svr.stop();
  24454. t.join();
  24455. // The mapping only redirects the connection; the identity stays host_.
  24456. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24457. }
  24458. class WebSocketIntegrationTest : public ::testing::Test {
  24459. protected:
  24460. void SetUp() override {
  24461. server_ = httplib::detail::make_unique<Server>();
  24462. setup_server();
  24463. start_server();
  24464. }
  24465. void TearDown() override {
  24466. server_->stop();
  24467. if (server_thread_.joinable()) { server_thread_.join(); }
  24468. }
  24469. void setup_server() {
  24470. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24471. std::string msg;
  24472. ws::ReadResult ret;
  24473. while ((ret = ws.read(msg))) {
  24474. if (ret == ws::Binary) {
  24475. ws.send(msg.data(), msg.size());
  24476. } else {
  24477. ws.send(msg);
  24478. }
  24479. }
  24480. });
  24481. server_->WebSocket("/ws-echo-string",
  24482. [](const Request &, ws::WebSocket &ws) {
  24483. std::string msg;
  24484. while (ws.read(msg)) {
  24485. ws.send("echo: " + msg);
  24486. }
  24487. });
  24488. server_->WebSocket(
  24489. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24490. // Echo back request metadata
  24491. ws.send("path:" + req.path);
  24492. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24493. std::string msg;
  24494. while (ws.read(msg)) {}
  24495. });
  24496. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24497. std::string msg;
  24498. ws.read(msg); // wait for a message
  24499. ws.close();
  24500. });
  24501. server_->WebSocket("/ws-close-status",
  24502. [](const Request &, ws::WebSocket &ws) {
  24503. std::string msg;
  24504. ws.read(msg); // wait for a message
  24505. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24506. });
  24507. server_->WebSocket(
  24508. "/ws-subprotocol",
  24509. [](const Request &, ws::WebSocket &ws) {
  24510. std::string msg;
  24511. while (ws.read(msg)) {
  24512. ws.send(msg);
  24513. }
  24514. },
  24515. [](const std::vector<std::string> &protocols) -> std::string {
  24516. for (const auto &p : protocols) {
  24517. if (p == "graphql-ws") { return p; }
  24518. }
  24519. return "";
  24520. });
  24521. server_->WebSocket(
  24522. "/ws-subprotocol-unoffered",
  24523. [](const Request &, ws::WebSocket &ws) {
  24524. std::string msg;
  24525. while (ws.read(msg)) {
  24526. ws.send(msg);
  24527. }
  24528. },
  24529. [](const std::vector<std::string> &) -> std::string {
  24530. return "admin";
  24531. });
  24532. }
  24533. void start_server() {
  24534. port_ = server_->bind_to_any_port(HOST);
  24535. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24536. server_->wait_until_ready();
  24537. }
  24538. std::unique_ptr<Server> server_;
  24539. std::thread server_thread_;
  24540. int port_ = 0;
  24541. };
  24542. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24544. "/ws-echo");
  24545. ASSERT_TRUE(client.connect());
  24546. ASSERT_TRUE(client.is_open());
  24547. ASSERT_TRUE(client.send("Hello WebSocket"));
  24548. std::string msg;
  24549. EXPECT_EQ(ws::Text, client.read(msg));
  24550. EXPECT_EQ("Hello WebSocket", msg);
  24551. client.close();
  24552. }
  24553. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24555. "/ws-echo");
  24556. ASSERT_TRUE(client.connect());
  24557. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24558. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24559. std::string msg;
  24560. EXPECT_EQ(ws::Binary, client.read(msg));
  24561. EXPECT_EQ(binary_data, msg);
  24562. client.close();
  24563. }
  24564. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24566. "/ws-echo");
  24567. ASSERT_TRUE(client.connect());
  24568. for (int i = 0; i < 10; i++) {
  24569. auto text = "message " + std::to_string(i);
  24570. ASSERT_TRUE(client.send(text));
  24571. std::string msg;
  24572. ASSERT_TRUE(client.read(msg));
  24573. EXPECT_EQ(text, msg);
  24574. }
  24575. client.close();
  24576. }
  24577. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24579. "/ws-close");
  24580. ASSERT_TRUE(client.connect());
  24581. // Send a message to trigger the server to close
  24582. ASSERT_TRUE(client.send("trigger close"));
  24583. // The server will close, so read should return false
  24584. std::string msg;
  24585. EXPECT_FALSE(client.read(msg));
  24586. EXPECT_FALSE(client.is_open());
  24587. }
  24588. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24589. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24590. "/ws-echo");
  24591. ASSERT_TRUE(client.connect());
  24592. // 128KB message
  24593. std::string large_data(128 * 1024, 'X');
  24594. ASSERT_TRUE(client.send(large_data));
  24595. std::string msg;
  24596. ASSERT_TRUE(client.read(msg));
  24597. EXPECT_EQ(large_data, msg);
  24598. client.close();
  24599. }
  24600. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24602. "/ws-echo");
  24603. ASSERT_TRUE(client.connect());
  24604. const int num_threads = 4;
  24605. std::vector<std::thread> threads;
  24606. std::atomic<int> send_count{0};
  24607. for (int t = 0; t < num_threads; t++) {
  24608. threads.emplace_back([&client, &send_count, t]() {
  24609. for (int i = 0; i < 5; i++) {
  24610. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24611. if (client.send(text)) { send_count++; }
  24612. }
  24613. });
  24614. }
  24615. for (auto &th : threads) {
  24616. th.join();
  24617. }
  24618. int received = 0;
  24619. std::string msg;
  24620. while (received < send_count.load()) {
  24621. if (!client.read(msg)) { break; }
  24622. received++;
  24623. }
  24624. EXPECT_EQ(send_count.load(), received);
  24625. client.close();
  24626. }
  24627. TEST_F(WebSocketIntegrationTest, ReadString) {
  24628. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24629. "/ws-echo-string");
  24630. ASSERT_TRUE(client.connect());
  24631. ASSERT_TRUE(client.send("hello"));
  24632. std::string msg;
  24633. ASSERT_TRUE(client.read(msg));
  24634. EXPECT_EQ("echo: hello", msg);
  24635. ASSERT_TRUE(client.send("world"));
  24636. ASSERT_TRUE(client.read(msg));
  24637. EXPECT_EQ("echo: world", msg);
  24638. client.close();
  24639. }
  24640. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24641. Headers headers = {{"X-Test-Header", "test-value"}};
  24642. ws::WebSocketClient client(
  24643. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24644. ASSERT_TRUE(client.connect());
  24645. std::string msg;
  24646. ASSERT_TRUE(client.read(msg));
  24647. EXPECT_EQ("path:/ws-request-info", msg);
  24648. ASSERT_TRUE(client.read(msg));
  24649. EXPECT_EQ("header:test-value", msg);
  24650. client.close();
  24651. }
  24652. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24653. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24654. "/ws-echo");
  24655. client.set_read_timeout(1, 0); // 1 second
  24656. ASSERT_TRUE(client.connect());
  24657. // Don't send anything — server echo handler waits for a message, so read()
  24658. // should time out. The connection survives it: nothing was consumed.
  24659. std::string msg;
  24660. EXPECT_EQ(client.read(msg), ws::Timeout);
  24661. EXPECT_TRUE(client.is_open());
  24662. // And it is still usable afterwards.
  24663. EXPECT_TRUE(client.send("after timeout"));
  24664. EXPECT_EQ(client.read(msg), ws::Text);
  24665. EXPECT_EQ(msg, "after timeout");
  24666. }
  24667. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24668. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24669. "/ws-echo");
  24670. client.set_read_timeout(1, 0);
  24671. ASSERT_TRUE(client.connect());
  24672. ASSERT_TRUE(client.send("first"));
  24673. std::string msg;
  24674. ASSERT_EQ(client.read(msg), ws::Text);
  24675. ASSERT_EQ(msg, "first");
  24676. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24677. // not be used with a read timeout: it would reprocess the previous message.
  24678. EXPECT_EQ(client.read(msg), ws::Timeout);
  24679. EXPECT_EQ(msg, "first");
  24680. }
  24681. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24683. "/ws-echo");
  24684. ASSERT_TRUE(client.connect());
  24685. // Setting it once the connection is open reaches the live stream, not just
  24686. // the seed for the next connect().
  24687. client.set_read_timeout(1, 0);
  24688. std::string msg;
  24689. EXPECT_EQ(client.read(msg), ws::Timeout);
  24690. EXPECT_TRUE(client.is_open());
  24691. }
  24692. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24694. "/ws-echo");
  24695. client.set_read_timeout(5, 0);
  24696. ASSERT_TRUE(client.connect());
  24697. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24698. // The server should reject it and close the connection.
  24699. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24700. client.send(oversized);
  24701. // The server's read() should have failed due to payload limit,
  24702. // so our read() should return false (connection closed).
  24703. std::string msg;
  24704. EXPECT_FALSE(client.read(msg));
  24705. }
  24706. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24708. "/ws-echo");
  24709. client.set_read_timeout(10, 0);
  24710. ASSERT_TRUE(client.connect());
  24711. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24712. // This should succeed.
  24713. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24714. ASSERT_TRUE(client.send(at_limit));
  24715. std::string msg;
  24716. ASSERT_TRUE(client.read(msg));
  24717. EXPECT_EQ(at_limit.size(), msg.size());
  24718. client.close();
  24719. }
  24720. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24722. "/nonexistent");
  24723. auto res = client.connect();
  24724. EXPECT_FALSE(res);
  24725. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24726. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24727. EXPECT_FALSE(client.is_open());
  24728. }
  24729. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24730. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24731. "/ws-echo");
  24732. ASSERT_TRUE(client.connect());
  24733. ASSERT_TRUE(client.send(""));
  24734. std::string msg;
  24735. EXPECT_EQ(ws::Text, client.read(msg));
  24736. EXPECT_EQ("", msg);
  24737. client.close();
  24738. }
  24739. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24741. "/ws-echo");
  24742. // First connection
  24743. ASSERT_TRUE(client.connect());
  24744. ASSERT_TRUE(client.send("first"));
  24745. std::string msg;
  24746. ASSERT_TRUE(client.read(msg));
  24747. EXPECT_EQ("first", msg);
  24748. client.close();
  24749. EXPECT_FALSE(client.is_open());
  24750. // Reconnect using the same client object
  24751. ASSERT_TRUE(client.connect());
  24752. ASSERT_TRUE(client.is_open());
  24753. ASSERT_TRUE(client.send("second"));
  24754. ASSERT_TRUE(client.read(msg));
  24755. EXPECT_EQ("second", msg);
  24756. client.close();
  24757. }
  24758. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24760. "/ws-close-status");
  24761. ASSERT_TRUE(client.connect());
  24762. // Trigger the server to close with GoingAway status
  24763. ASSERT_TRUE(client.send("trigger"));
  24764. // read() should return false after receiving the close frame
  24765. std::string msg;
  24766. EXPECT_FALSE(client.read(msg));
  24767. EXPECT_FALSE(client.is_open());
  24768. }
  24769. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24771. "/ws-echo");
  24772. ASSERT_TRUE(client.connect());
  24773. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24774. EXPECT_FALSE(client.is_open());
  24775. }
  24776. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24777. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24778. ws::WebSocketClient client(
  24779. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24780. ASSERT_TRUE(client.connect());
  24781. // Server should have selected graphql-ws
  24782. EXPECT_EQ("graphql-ws", client.subprotocol());
  24783. client.close();
  24784. }
  24785. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24786. Headers headers;
  24787. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24788. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24789. ws::WebSocketClient client(
  24790. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24791. ASSERT_TRUE(client.connect());
  24792. // The offer on the second field line counts too, so graphql-ws is selected
  24793. EXPECT_EQ("graphql-ws", client.subprotocol());
  24794. client.close();
  24795. }
  24796. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24797. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24798. ws::WebSocketClient client(
  24799. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24800. ASSERT_TRUE(client.connect());
  24801. // Server should not have selected any subprotocol
  24802. EXPECT_TRUE(client.subprotocol().empty());
  24803. client.close();
  24804. }
  24805. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24806. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24807. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24808. "/ws-subprotocol-unoffered",
  24809. headers);
  24810. ASSERT_TRUE(client.connect());
  24811. EXPECT_TRUE(client.subprotocol().empty());
  24812. client.close();
  24813. }
  24814. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24815. // Connect without requesting any subprotocol
  24816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24817. "/ws-subprotocol");
  24818. ASSERT_TRUE(client.connect());
  24819. EXPECT_TRUE(client.subprotocol().empty());
  24820. client.close();
  24821. }
  24822. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24823. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24824. "/ws-echo");
  24825. client.set_tcp_nodelay(true);
  24826. client.set_connection_timeout(3, 0);
  24827. bool socket_options_called = false;
  24828. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24829. ASSERT_TRUE(client.connect());
  24830. ASSERT_TRUE(client.is_open());
  24831. EXPECT_TRUE(socket_options_called);
  24832. ASSERT_TRUE(client.send("hello"));
  24833. std::string msg;
  24834. auto result = client.read(msg);
  24835. EXPECT_EQ(result, ws::ReadResult::Text);
  24836. EXPECT_EQ(msg, "hello");
  24837. client.close();
  24838. }
  24839. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24841. "/ws-echo");
  24842. client.set_connection_timeout(std::chrono::seconds(3));
  24843. client.set_write_timeout(std::chrono::seconds(3));
  24844. // A sub-second remainder exercises the seconds/microseconds split.
  24845. client.set_read_timeout(std::chrono::milliseconds(1500));
  24846. ASSERT_TRUE(client.connect());
  24847. auto start = std::chrono::steady_clock::now();
  24848. std::string msg;
  24849. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24850. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24851. std::chrono::steady_clock::now() - start)
  24852. .count();
  24853. // Above 1s so that dropping the microseconds half of the split fails here.
  24854. // Ignoring the setter altogether would not reach this line at all: a client
  24855. // waits forever by default.
  24856. EXPECT_GE(elapsed, 1400);
  24857. EXPECT_LT(elapsed, 30000);
  24858. }
  24859. #ifndef _WIN32
  24860. // A send() that times out after part of the data went out returns the count
  24861. // written so far. Every byte of the frame must still be sent, or the peer reads
  24862. // the next frame's header and payload as the rest of this one.
  24863. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24864. signal(SIGPIPE, SIG_IGN);
  24865. const std::string large(4 * 1024 * 1024, 'A');
  24866. std::atomic<bool> large_sent{false};
  24867. std::atomic<bool> small_sent{false};
  24868. Server svr;
  24869. svr.set_write_timeout(0, 500000);
  24870. svr.set_socket_options([](socket_t sock) {
  24871. int size = 8192;
  24872. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24873. reinterpret_cast<const char *>(&size), sizeof(size));
  24874. });
  24875. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24876. large_sent = ws.send(large.data(), large.size());
  24877. small_sent = ws.send("after");
  24878. std::string msg;
  24879. while (ws.read(msg)) {}
  24880. });
  24881. auto port = svr.bind_to_any_port(HOST);
  24882. std::thread t([&]() { svr.listen_after_bind(); });
  24883. auto se = detail::scope_exit([&] {
  24884. svr.stop();
  24885. t.join();
  24886. });
  24887. svr.wait_until_ready();
  24888. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24889. std::to_string(port) + "/ws");
  24890. client.set_read_timeout(5);
  24891. client.set_socket_options([](socket_t sock) {
  24892. int size = 8192;
  24893. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24894. reinterpret_cast<const char *>(&size), sizeof(size));
  24895. });
  24896. ASSERT_TRUE(client.connect());
  24897. // Outlast the server's write timeout, then drain.
  24898. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24899. std::string msg;
  24900. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24901. EXPECT_TRUE(msg == large);
  24902. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24903. EXPECT_EQ("after", msg);
  24904. EXPECT_TRUE(large_sent);
  24905. EXPECT_TRUE(small_sent);
  24906. client.close();
  24907. }
  24908. #endif
  24909. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24910. Server svr;
  24911. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24912. if (!req.has_header("Authorization")) {
  24913. res.status = StatusCode::Unauthorized_401;
  24914. res.set_content("Unauthorized", "text/plain");
  24915. return Server::HandlerResponse::Handled;
  24916. }
  24917. return Server::HandlerResponse::Unhandled;
  24918. });
  24919. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24920. std::string msg;
  24921. while (ws.read(msg)) {
  24922. ws.send(msg);
  24923. }
  24924. });
  24925. auto port = svr.bind_to_any_port("localhost");
  24926. std::thread t([&]() { svr.listen_after_bind(); });
  24927. svr.wait_until_ready();
  24928. // Without Authorization header - should be rejected before upgrade
  24929. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24930. EXPECT_FALSE(client1.connect());
  24931. // The rejection is framed like any other HTTP response
  24932. {
  24933. Client cli("localhost", port);
  24934. Headers headers = {{"Upgrade", "websocket"},
  24935. {"Connection", "Upgrade"},
  24936. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24937. {"Sec-WebSocket-Version", "13"}};
  24938. auto res = cli.Get("/ws", headers);
  24939. ASSERT_TRUE(res);
  24940. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24941. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24942. EXPECT_EQ("Unauthorized", res->body);
  24943. }
  24944. // With Authorization header - should succeed
  24945. Headers headers = {{"Authorization", "Bearer token123"}};
  24946. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24947. headers);
  24948. ASSERT_TRUE(client2.connect());
  24949. ASSERT_TRUE(client2.send("hello"));
  24950. std::string msg;
  24951. ASSERT_TRUE(client2.read(msg));
  24952. EXPECT_EQ("hello", msg);
  24953. client2.close();
  24954. svr.stop();
  24955. t.join();
  24956. }
  24957. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24958. Server svr;
  24959. std::atomic<int> pre_routing_calls{0};
  24960. std::atomic<int> pre_request_calls{0};
  24961. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24962. pre_routing_calls++;
  24963. if (req.path == "/handled") {
  24964. res.set_content("handled", "text/plain");
  24965. return Server::HandlerResponse::Handled;
  24966. }
  24967. return Server::HandlerResponse::Unhandled;
  24968. });
  24969. svr.set_pre_request_handler([&](const Request &, Response &) {
  24970. pre_request_calls++;
  24971. return Server::HandlerResponse::Unhandled;
  24972. });
  24973. svr.Get("/http", [](const Request &, Response &res) {
  24974. res.set_content("http", "text/plain");
  24975. });
  24976. svr.WebSocket("/ws",
  24977. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24978. auto port = svr.bind_to_any_port("localhost");
  24979. std::thread t([&]() { svr.listen_after_bind(); });
  24980. auto se = detail::scope_exit([&] {
  24981. svr.stop();
  24982. t.join();
  24983. });
  24984. svr.wait_until_ready();
  24985. Headers upgrade = {{"Upgrade", "websocket"},
  24986. {"Connection", "Upgrade"},
  24987. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24988. {"Sec-WebSocket-Version", "13"}};
  24989. auto get = [&](const char *path) {
  24990. pre_routing_calls = 0;
  24991. return Client("localhost", port).Get(path, upgrade);
  24992. };
  24993. // No WebSocket route, but an HTTP one
  24994. auto res = get("/http");
  24995. ASSERT_TRUE(res);
  24996. EXPECT_EQ(StatusCode::OK_200, res->status);
  24997. EXPECT_EQ("http", res->body);
  24998. EXPECT_EQ(1, pre_routing_calls);
  24999. EXPECT_EQ(1, pre_request_calls);
  25000. // No route at all
  25001. res = get("/none");
  25002. ASSERT_TRUE(res);
  25003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25004. EXPECT_EQ(1, pre_routing_calls);
  25005. // Answered by the pre-routing handler
  25006. res = get("/handled");
  25007. ASSERT_TRUE(res);
  25008. EXPECT_EQ(StatusCode::OK_200, res->status);
  25009. EXPECT_EQ("handled", res->body);
  25010. EXPECT_EQ(1, pre_routing_calls);
  25011. // A WebSocket route
  25012. pre_routing_calls = 0;
  25013. pre_request_calls = 0;
  25014. {
  25015. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25016. "/ws");
  25017. ASSERT_TRUE(client.connect());
  25018. std::string msg;
  25019. ASSERT_TRUE(client.read(msg));
  25020. EXPECT_EQ("ws", msg);
  25021. client.close();
  25022. }
  25023. EXPECT_EQ(1, pre_routing_calls);
  25024. EXPECT_EQ(1, pre_request_calls);
  25025. }
  25026. // An upgrade request answered by a hook leaves its body unread, so that body
  25027. // must not be served as the next request on the connection.
  25028. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25029. Server svr;
  25030. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25031. if (req.path == "/pre-routing") {
  25032. res.set_content("pre-routing", "text/plain");
  25033. return Server::HandlerResponse::Handled;
  25034. }
  25035. return Server::HandlerResponse::Unhandled;
  25036. });
  25037. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25038. if (req.matched_route == "/pre-request") {
  25039. res.set_content("pre-request", "text/plain");
  25040. return Server::HandlerResponse::Handled;
  25041. }
  25042. return Server::HandlerResponse::Unhandled;
  25043. });
  25044. svr.Get("/smuggled", [](const Request &, Response &res) {
  25045. res.set_content("smuggled", "text/plain");
  25046. });
  25047. svr.WebSocket("/pre-request",
  25048. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25049. auto port = svr.bind_to_any_port(HOST);
  25050. std::thread t([&]() { svr.listen_after_bind(); });
  25051. auto se = detail::scope_exit([&] {
  25052. svr.stop();
  25053. t.join();
  25054. });
  25055. svr.wait_until_ready();
  25056. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25057. for (auto path : {"/pre-routing", "/pre-request"}) {
  25058. std::string req = std::string("GET ") + path +
  25059. " HTTP/1.1\r\n"
  25060. "Host: localhost\r\n"
  25061. "Upgrade: websocket\r\n"
  25062. "Connection: Upgrade\r\n"
  25063. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25064. "Sec-WebSocket-Version: 13\r\n"
  25065. "Content-Length: " +
  25066. std::to_string(body.size()) + "\r\n\r\n" + body;
  25067. std::string res;
  25068. ASSERT_TRUE(send_request(5, req, &res, port));
  25069. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25070. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25071. // Only one response, and the body was not served as a request
  25072. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25073. }
  25074. }
  25075. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25076. Server svr;
  25077. std::atomic<int> pre_request_calls{0};
  25078. std::atomic<bool> route_matched{false};
  25079. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25080. pre_request_calls++;
  25081. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25082. if (req.get_header_value("Authorization") != "Bearer token123") {
  25083. res.status = StatusCode::Unauthorized_401;
  25084. res.set_content("Unauthorized", "text/plain");
  25085. return Server::HandlerResponse::Handled;
  25086. }
  25087. return Server::HandlerResponse::Unhandled;
  25088. });
  25089. std::atomic<bool> handler_called{false};
  25090. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25091. handler_called = true;
  25092. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25093. });
  25094. auto port = svr.bind_to_any_port("localhost");
  25095. std::thread t([&]() { svr.listen_after_bind(); });
  25096. svr.wait_until_ready();
  25097. // Without Authorization header - should be rejected before upgrade
  25098. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25099. "/ws/1");
  25100. EXPECT_FALSE(client1.connect());
  25101. EXPECT_FALSE(handler_called);
  25102. EXPECT_EQ(1, pre_request_calls);
  25103. EXPECT_TRUE(route_matched);
  25104. // The rejection is an ordinary HTTP response, not a protocol switch
  25105. {
  25106. Client cli("localhost", port);
  25107. Headers headers = {{"Upgrade", "websocket"},
  25108. {"Connection", "Upgrade"},
  25109. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25110. {"Sec-WebSocket-Version", "13"}};
  25111. auto res = cli.Get("/ws/1", headers);
  25112. ASSERT_TRUE(res);
  25113. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25114. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25115. EXPECT_EQ("Unauthorized", res->body);
  25116. }
  25117. EXPECT_FALSE(handler_called);
  25118. // With Authorization header - should succeed
  25119. Headers headers = {{"Authorization", "Bearer token123"}};
  25120. ws::WebSocketClient client2(
  25121. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25122. ASSERT_TRUE(client2.connect());
  25123. std::string msg;
  25124. ASSERT_TRUE(client2.read(msg));
  25125. EXPECT_EQ("/ws/:id 2", msg);
  25126. EXPECT_TRUE(handler_called);
  25127. client2.close();
  25128. svr.stop();
  25129. t.join();
  25130. }
  25131. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25132. static Headers websocket_upgrade_headers() {
  25133. return {{"Upgrade", "websocket"},
  25134. {"Connection", "Upgrade"},
  25135. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25136. {"Sec-WebSocket-Version", "13"},
  25137. {"Sec-WebSocket-Protocol", "chat"}};
  25138. }
  25139. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25140. Server svr;
  25141. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25142. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25143. return Server::HandlerResponse::Unhandled;
  25144. });
  25145. svr.set_pre_request_handler([](const Request &req, Response &) {
  25146. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25147. return Server::HandlerResponse::Unhandled;
  25148. });
  25149. svr.set_exception_handler(
  25150. [](const Request &, Response &res, std::exception_ptr ep) {
  25151. try {
  25152. std::rethrow_exception(ep);
  25153. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25154. });
  25155. auto handler = [](const Request &, ws::WebSocket &) {};
  25156. svr.WebSocket("/pre-routing", handler);
  25157. svr.WebSocket("/pre-request", handler);
  25158. svr.WebSocket("/sub-protocol", handler,
  25159. [](const std::vector<std::string> &) -> std::string {
  25160. throw std::runtime_error("/sub-protocol");
  25161. });
  25162. auto port = svr.bind_to_any_port(HOST);
  25163. ASSERT_GT(port, 0);
  25164. thread t = thread([&] { svr.listen_after_bind(); });
  25165. auto se = detail::scope_exit([&] {
  25166. svr.stop();
  25167. t.join();
  25168. ASSERT_FALSE(svr.is_running());
  25169. });
  25170. svr.wait_until_ready();
  25171. Client cli(HOST, port);
  25172. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25173. auto res = cli.Get(path, websocket_upgrade_headers());
  25174. if (!res) {
  25175. ADD_FAILURE() << path << ": " << to_string(res.error());
  25176. continue;
  25177. }
  25178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25179. EXPECT_EQ(path, res->body);
  25180. }
  25181. }
  25182. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25183. Server svr;
  25184. svr.set_pre_routing_handler(
  25185. [](const Request &, Response &) -> Server::HandlerResponse {
  25186. throw std::runtime_error("pre-routing");
  25187. });
  25188. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25189. auto port = svr.bind_to_any_port(HOST);
  25190. ASSERT_GT(port, 0);
  25191. thread t = thread([&] { svr.listen_after_bind(); });
  25192. auto se = detail::scope_exit([&] {
  25193. svr.stop();
  25194. t.join();
  25195. ASSERT_FALSE(svr.is_running());
  25196. });
  25197. svr.wait_until_ready();
  25198. Client cli(HOST, port);
  25199. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25200. ASSERT_TRUE(res) << to_string(res.error());
  25201. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25202. }
  25203. #endif
  25204. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25205. Server svr;
  25206. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25207. // A read timeout is how a handler gets control back. Without it, a handler
  25208. // parked in read() can never write on the connection it is reading.
  25209. ws.set_read_timeout(std::chrono::milliseconds(100));
  25210. std::string msg;
  25211. while (ws.is_open()) {
  25212. auto r = ws.read(msg);
  25213. if (r == httplib::ws::Timeout) {
  25214. ws.send("tick");
  25215. continue;
  25216. }
  25217. if (r == httplib::ws::Fail) { break; }
  25218. ws.send(msg);
  25219. }
  25220. });
  25221. auto port = svr.bind_to_any_port("localhost");
  25222. std::thread t([&]() { svr.listen_after_bind(); });
  25223. svr.wait_until_ready();
  25224. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25225. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25226. ASSERT_TRUE(client.connect());
  25227. // The client sends nothing, so anything it receives came out of the
  25228. // handler's timeout path.
  25229. std::string msg;
  25230. ASSERT_EQ(client.read(msg), ws::Text);
  25231. EXPECT_EQ("tick", msg);
  25232. client.close();
  25233. svr.stop();
  25234. t.join();
  25235. }
  25236. // Stream::read may return fewer bytes than asked for. This is that contract at
  25237. // its worst -- one byte per call -- which is what a frame header straddling a
  25238. // read buffer's boundary looks like to the frame parser.
  25239. class WsByteAtATimeStream : public Stream {
  25240. public:
  25241. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25242. bool is_readable() const override { return true; }
  25243. bool wait_readable() const override { return true; }
  25244. bool wait_writable() const override { return true; }
  25245. ssize_t read(char *ptr, size_t size) override {
  25246. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25247. *ptr = data_[pos_++];
  25248. return 1;
  25249. }
  25250. ssize_t write(const char *, size_t size) override {
  25251. return static_cast<ssize_t>(size);
  25252. }
  25253. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25254. ip = "127.0.0.1";
  25255. port = 0;
  25256. }
  25257. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25258. ip = "127.0.0.1";
  25259. port = 0;
  25260. }
  25261. socket_t socket() const override { return INVALID_SOCKET; }
  25262. time_t duration() const override { return 0; }
  25263. private:
  25264. std::string data_;
  25265. size_t pos_ = 0;
  25266. };
  25267. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25268. // The payload uses the 16-bit extended length, so the header, the length
  25269. // and the mask key are all multi-byte fields here. Each used to be read
  25270. // with a single read() call, which fails as soon as one is split. The
  25271. // payload is also a little over one read chunk, so it is read in two.
  25272. std::string body;
  25273. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25274. body += static_cast<char>(i % 251);
  25275. }
  25276. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25277. std::string frame;
  25278. frame += static_cast<char>(0x81); // FIN + Text
  25279. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25280. frame += static_cast<char>(body.size() >> 8);
  25281. frame += static_cast<char>(body.size() & 0xff);
  25282. for (size_t i = 0; i < 4; i++) {
  25283. frame += static_cast<char>(mask[i]);
  25284. }
  25285. for (size_t i = 0; i < body.size(); i++) {
  25286. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25287. }
  25288. WsByteAtATimeStream strm(frame);
  25289. ws::Opcode opcode;
  25290. std::string payload;
  25291. bool fin = false;
  25292. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25293. /*expect_masked=*/true, body.size()),
  25294. ws::impl::FrameRead::Ok);
  25295. EXPECT_TRUE(fin);
  25296. EXPECT_EQ(opcode, ws::Opcode::Text);
  25297. EXPECT_EQ(payload, body);
  25298. }
  25299. // Keeps what is written, counting the writes, and reads it back.
  25300. class WsWriteCountingStream : public Stream {
  25301. public:
  25302. bool is_readable() const override { return true; }
  25303. bool wait_readable() const override { return true; }
  25304. bool wait_writable() const override { return true; }
  25305. ssize_t read(char *ptr, size_t size) override {
  25306. auto n = (std::min)(size, data_.size() - pos_);
  25307. if (n == 0) { return 0; }
  25308. memcpy(ptr, data_.data() + pos_, n);
  25309. pos_ += n;
  25310. return static_cast<ssize_t>(n);
  25311. }
  25312. ssize_t write(const char *ptr, size_t size) override {
  25313. writes++;
  25314. data_.append(ptr, size);
  25315. return static_cast<ssize_t>(size);
  25316. }
  25317. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25318. ip = "127.0.0.1";
  25319. port = 0;
  25320. }
  25321. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25322. ip = "127.0.0.1";
  25323. port = 0;
  25324. }
  25325. socket_t socket() const override { return INVALID_SOCKET; }
  25326. time_t duration() const override { return 0; }
  25327. int writes = 0;
  25328. private:
  25329. std::string data_;
  25330. size_t pos_ = 0;
  25331. };
  25332. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25333. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25334. // masked and not, reads back as written; a payload over one chunk follows
  25335. // its first in more writes.
  25336. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25337. for (auto mask : {false, true}) {
  25338. std::string body(len, '\0');
  25339. for (size_t i = 0; i < len; i++) {
  25340. body[i] = static_cast<char>(i % 251);
  25341. }
  25342. WsWriteCountingStream strm;
  25343. ASSERT_TRUE(detail::write_websocket_frame(
  25344. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25345. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25346. ws::Opcode opcode;
  25347. std::string payload;
  25348. bool fin = false;
  25349. ASSERT_EQ(
  25350. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25351. ws::impl::FrameRead::Ok)
  25352. << len << " " << mask;
  25353. EXPECT_TRUE(fin);
  25354. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25355. EXPECT_EQ(body, payload) << len << " " << mask;
  25356. }
  25357. }
  25358. }
  25359. // Hands out its pieces one read at a time, timing out between each two.
  25360. class WsTimeoutBetweenPiecesStream : public Stream {
  25361. public:
  25362. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25363. : pieces_(std::move(pieces)) {}
  25364. bool is_readable() const override { return true; }
  25365. bool wait_readable() const override { return true; }
  25366. bool wait_writable() const override { return true; }
  25367. ssize_t read(char *ptr, size_t size) override {
  25368. if (time_out_) {
  25369. time_out_ = false;
  25370. error_ = Error::Timeout;
  25371. return -1;
  25372. }
  25373. if (i_ >= pieces_.size()) {
  25374. error_ = Error::ConnectionClosed;
  25375. return 0;
  25376. }
  25377. auto &piece = pieces_[i_];
  25378. auto n = (std::min)(size, piece.size() - at_);
  25379. memcpy(ptr, piece.data() + at_, n);
  25380. at_ += n;
  25381. if (at_ == piece.size()) {
  25382. i_++;
  25383. at_ = 0;
  25384. time_out_ = true;
  25385. }
  25386. return static_cast<ssize_t>(n);
  25387. }
  25388. ssize_t write(const char *, size_t size) override {
  25389. return static_cast<ssize_t>(size);
  25390. }
  25391. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25392. ip = "127.0.0.1";
  25393. port = 0;
  25394. }
  25395. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25396. ip = "127.0.0.1";
  25397. port = 0;
  25398. }
  25399. socket_t socket() const override { return INVALID_SOCKET; }
  25400. time_t duration() const override { return 0; }
  25401. private:
  25402. std::vector<std::string> pieces_;
  25403. size_t i_ = 0;
  25404. size_t at_ = 0;
  25405. bool time_out_ = false;
  25406. };
  25407. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25408. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25409. std::string frame = "\x81\x85";
  25410. frame.append(4, '\0');
  25411. frame += "Hello";
  25412. // The header's first byte, then its second with half the mask key, then
  25413. // the rest
  25414. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25415. frame.substr(4)};
  25416. WsTimeoutBetweenPiecesStream strm(pieces);
  25417. ws::impl::FrameReader reader;
  25418. ws::Opcode opcode;
  25419. std::string payload;
  25420. bool fin = false;
  25421. for (int i = 0; i < 2; i++) {
  25422. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25423. reader.read(strm, opcode, payload, fin, true, 0));
  25424. EXPECT_TRUE(reader.begun());
  25425. }
  25426. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25427. reader.read(strm, opcode, payload, fin, true, 0));
  25428. EXPECT_FALSE(reader.begun());
  25429. EXPECT_TRUE(fin);
  25430. EXPECT_EQ(ws::Opcode::Text, opcode);
  25431. EXPECT_EQ("Hello", payload);
  25432. // Read in one go, the frame cannot be gone on with after a timeout
  25433. WsTimeoutBetweenPiecesStream again(pieces);
  25434. EXPECT_EQ(
  25435. ws::impl::FrameRead::Fail,
  25436. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25437. }
  25438. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25439. std::string body(2000, 'x');
  25440. std::string frame;
  25441. frame += static_cast<char>(0x82); // FIN + Binary
  25442. frame += static_cast<char>(126); // 16-bit length follows
  25443. frame += static_cast<char>(body.size() >> 8);
  25444. frame += static_cast<char>(body.size() & 0xff);
  25445. frame += body;
  25446. detail::BufferStream strm;
  25447. strm.write(frame.data(), frame.size());
  25448. ws::Opcode opcode;
  25449. std::string payload;
  25450. bool fin;
  25451. EXPECT_EQ(
  25452. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25453. ws::impl::FrameRead::Ok);
  25454. EXPECT_EQ(body, payload);
  25455. }
  25456. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25457. // The header announces the largest payload allowed, and only 3 bytes of it
  25458. // ever arrive.
  25459. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25460. std::string frame;
  25461. frame += static_cast<char>(0x82); // FIN + Binary
  25462. frame += static_cast<char>(127); // 64-bit length follows
  25463. for (int shift = 56; shift >= 0; shift -= 8) {
  25464. frame += static_cast<char>((len >> shift) & 0xff);
  25465. }
  25466. frame += "abc";
  25467. detail::BufferStream strm;
  25468. strm.write(frame.data(), frame.size());
  25469. ws::Opcode opcode;
  25470. std::string payload;
  25471. bool fin;
  25472. EXPECT_EQ(
  25473. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25474. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25475. ws::impl::FrameRead::Fail);
  25476. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25477. }
  25478. TEST(WebSocketTest, QueryStringInHandshake) {
  25479. Server svr;
  25480. std::mutex mtx;
  25481. std::string received_target;
  25482. std::string received_token;
  25483. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25484. {
  25485. std::lock_guard<std::mutex> lock(mtx);
  25486. received_target = req.target;
  25487. if (req.has_param("token")) {
  25488. received_token = req.get_param_value("token");
  25489. }
  25490. }
  25491. std::string msg;
  25492. while (ws.read(msg)) {
  25493. ws.send(msg);
  25494. }
  25495. });
  25496. auto port = svr.bind_to_any_port("localhost");
  25497. std::thread t([&]() { svr.listen_after_bind(); });
  25498. svr.wait_until_ready();
  25499. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25500. "/ws?token=ABC&session=123");
  25501. ASSERT_TRUE(client.connect());
  25502. // Round-trip ensures the handler has run and captured the request.
  25503. ASSERT_TRUE(client.send("hello"));
  25504. std::string msg;
  25505. ASSERT_TRUE(client.read(msg));
  25506. EXPECT_EQ("hello", msg);
  25507. client.close();
  25508. {
  25509. std::lock_guard<std::mutex> lock(mtx);
  25510. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25511. EXPECT_EQ("ABC", received_token);
  25512. }
  25513. svr.stop();
  25514. t.join();
  25515. }
  25516. // Run a handshake against a throwaway server and hand the request the server
  25517. // received back to the caller, so tests can assert on the headers the client
  25518. // actually put on the wire.
  25519. static void capture_websocket_handshake_request(
  25520. const Headers &client_headers,
  25521. std::function<void(const Request &, int port)> verify) {
  25522. Server svr;
  25523. std::mutex mtx;
  25524. Request received;
  25525. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25526. {
  25527. std::lock_guard<std::mutex> lock(mtx);
  25528. received = req;
  25529. }
  25530. std::string msg;
  25531. while (ws.read(msg)) {
  25532. ws.send(msg);
  25533. }
  25534. });
  25535. auto port = svr.bind_to_any_port("localhost");
  25536. std::thread t([&]() { svr.listen_after_bind(); });
  25537. auto se = detail::scope_exit([&] {
  25538. svr.stop();
  25539. t.join();
  25540. });
  25541. svr.wait_until_ready();
  25542. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25543. client_headers);
  25544. ASSERT_TRUE(client.connect());
  25545. ASSERT_TRUE(client.send("hello"));
  25546. std::string msg;
  25547. ASSERT_TRUE(client.read(msg));
  25548. client.close();
  25549. {
  25550. std::lock_guard<std::mutex> lock(mtx);
  25551. verify(received, port);
  25552. }
  25553. }
  25554. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25555. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25556. // Non-default port must be present in the Host header. Default ports
  25557. // (80/443) are omitted; that logic is covered by
  25558. // MakeHostAndPortStringTest.
  25559. EXPECT_EQ("localhost:" + std::to_string(port),
  25560. req.get_header_value("Host"));
  25561. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25562. req.get_header_value("User-Agent"));
  25563. EXPECT_FALSE(req.has_header("Accept"));
  25564. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25565. EXPECT_FALSE(req.has_header("Content-Length"));
  25566. });
  25567. }
  25568. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25569. capture_websocket_handshake_request(
  25570. {{"Host", "example.com"},
  25571. {"User-Agent", "custom-agent"},
  25572. {"X-Custom", "value"}},
  25573. [](const Request &req, int) {
  25574. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25575. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25576. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25577. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25578. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25579. });
  25580. }
  25581. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25582. capture_websocket_handshake_request(
  25583. {{"Upgrade", "bogus"},
  25584. {"Connection", "close"},
  25585. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25586. {"Sec-WebSocket-Version", "8"}},
  25587. [](const Request &req, int) {
  25588. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25589. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25590. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25591. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25592. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25593. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25594. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25595. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25596. req.get_header_value("Sec-WebSocket-Key"));
  25597. });
  25598. }
  25599. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25600. // A header the client refuses to send must abort the handshake before any
  25601. // part of it reaches the wire; a lone request line would otherwise sit in
  25602. // the peer's buffer as a truncated request.
  25603. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25604. ASSERT_NE(INVALID_SOCKET, srv);
  25605. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25606. sockaddr_in addr{};
  25607. addr.sin_family = AF_INET;
  25608. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25609. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25610. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25611. ASSERT_EQ(0, ::listen(srv, 1));
  25612. sockaddr_in bound{};
  25613. socklen_t bound_len = sizeof(bound);
  25614. ASSERT_EQ(
  25615. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25616. auto port = ntohs(bound.sin_port);
  25617. ssize_t received = -1;
  25618. std::thread t([&] {
  25619. // Bound every blocking call so a regression fails the test with a bad
  25620. // value instead of hanging the suite.
  25621. fd_set rfds;
  25622. FD_ZERO(&rfds);
  25623. FD_SET(srv, &rfds);
  25624. timeval tv{5, 0};
  25625. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25626. 0) {
  25627. return;
  25628. }
  25629. sockaddr_in cli_addr{};
  25630. socklen_t cli_len = sizeof(cli_addr);
  25631. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25632. if (cli == INVALID_SOCKET) { return; }
  25633. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25634. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25635. char buf[4096];
  25636. received = ::recv(cli, buf, sizeof(buf), 0);
  25637. });
  25638. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25639. // connect() has already shut the socket down by the time it returns false,
  25640. // so the peer sees EOF without waiting for the client to be destroyed.
  25641. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25642. {{"X-Bad", "a\r\nInjected: 1"}});
  25643. EXPECT_FALSE(client.connect());
  25644. t.join();
  25645. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25646. EXPECT_EQ(0, received);
  25647. }
  25648. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25649. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25650. // contains "upgrade" as a substring is a different token and must not
  25651. // start a WebSocket handshake.
  25652. auto make_request = [](const std::vector<std::string> &connection_values) {
  25653. Request req;
  25654. req.method = "GET";
  25655. req.headers.emplace("Upgrade", "websocket");
  25656. for (const auto &value : connection_values) {
  25657. req.headers.emplace("Connection", value);
  25658. }
  25659. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25660. req.headers.emplace("Sec-WebSocket-Version", "13");
  25661. return req;
  25662. };
  25663. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25664. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25665. EXPECT_TRUE(
  25666. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25667. EXPECT_TRUE(
  25668. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25669. EXPECT_TRUE(
  25670. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25671. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25672. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25673. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25674. EXPECT_FALSE(
  25675. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25676. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25677. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25678. }
  25679. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25680. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25681. // asks recipients to match each protocol-name case-insensitively, and RFC
  25682. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25683. // client naming websocket alongside another protocol, or on a second field
  25684. // line, is offering websocket; a value that merely contains "websocket" as a
  25685. // substring is a different protocol name and is not.
  25686. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25687. Request req;
  25688. req.method = "GET";
  25689. for (const auto &value : upgrade_values) {
  25690. req.headers.emplace("Upgrade", value);
  25691. }
  25692. req.headers.emplace("Connection", "Upgrade");
  25693. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25694. req.headers.emplace("Sec-WebSocket-Version", "13");
  25695. return req;
  25696. };
  25697. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25698. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25699. EXPECT_TRUE(
  25700. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25701. EXPECT_TRUE(
  25702. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25703. EXPECT_TRUE(
  25704. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25705. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25706. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25707. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25708. EXPECT_FALSE(
  25709. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25710. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25711. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25712. }
  25713. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25714. Server svr;
  25715. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25716. auto port = svr.bind_to_any_port("localhost");
  25717. std::thread t([&]() { svr.listen_after_bind(); });
  25718. auto se = detail::scope_exit([&] {
  25719. svr.stop();
  25720. t.join();
  25721. });
  25722. svr.wait_until_ready();
  25723. Headers headers = {{"Upgrade", "websocket"},
  25724. {"Connection", "notupgrade"},
  25725. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25726. {"Sec-WebSocket-Version", "13"}};
  25727. Client cli("localhost", port);
  25728. auto res = cli.Get("/ws", headers);
  25729. // The route exists only as a WebSocket route, so a request that fails the
  25730. // handshake check falls through to ordinary routing.
  25731. ASSERT_TRUE(res);
  25732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25733. }
  25734. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25735. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25736. // Connection value is the only thing left for the client to reject.
  25737. Server svr;
  25738. svr.Get("/ws", [](const Request &req, Response &res) {
  25739. res.status = StatusCode::SwitchingProtocol_101;
  25740. res.set_header("Upgrade", "websocket");
  25741. res.set_header("Connection", "notupgrade");
  25742. res.set_header("Sec-WebSocket-Accept",
  25743. detail::websocket_accept_key(
  25744. req.get_header_value("Sec-WebSocket-Key")));
  25745. });
  25746. auto port = svr.bind_to_any_port("localhost");
  25747. std::thread t([&]() { svr.listen_after_bind(); });
  25748. auto se = detail::scope_exit([&] {
  25749. svr.stop();
  25750. t.join();
  25751. });
  25752. svr.wait_until_ready();
  25753. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25754. auto res = client.connect();
  25755. EXPECT_FALSE(res);
  25756. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25757. EXPECT_FALSE(client.is_open());
  25758. }
  25759. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25760. Server svr;
  25761. svr.Get("/ws", [](const Request &req, Response &res) {
  25762. res.status = StatusCode::SwitchingProtocol_101;
  25763. res.set_header("Upgrade", "websocket");
  25764. res.set_header("Connection", "Upgrade");
  25765. res.set_header("Sec-WebSocket-Accept",
  25766. detail::websocket_accept_key(
  25767. req.get_header_value("Sec-WebSocket-Key")));
  25768. res.set_header("Sec-WebSocket-Protocol", "admin");
  25769. });
  25770. auto port = svr.bind_to_any_port("localhost");
  25771. std::thread t([&]() { svr.listen_after_bind(); });
  25772. auto se = detail::scope_exit([&] {
  25773. svr.stop();
  25774. t.join();
  25775. });
  25776. svr.wait_until_ready();
  25777. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25778. // Server selects a subprotocol the client never offered
  25779. {
  25780. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25781. ws::WebSocketClient client(url, headers);
  25782. auto res = client.connect();
  25783. EXPECT_FALSE(res);
  25784. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25785. EXPECT_FALSE(client.is_open());
  25786. EXPECT_TRUE(client.subprotocol().empty());
  25787. }
  25788. // Client offered none but the server named one anyway
  25789. {
  25790. ws::WebSocketClient client(url);
  25791. auto res = client.connect();
  25792. EXPECT_FALSE(res);
  25793. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25794. EXPECT_FALSE(client.is_open());
  25795. EXPECT_TRUE(client.subprotocol().empty());
  25796. }
  25797. }
  25798. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25799. // The socket path doubles as the URL host, so it must not contain '/'.
  25800. const char *shard = getenv("GTEST_SHARD_INDEX");
  25801. const std::string sock_path =
  25802. shard ? std::string("httplib-ws-") + shard + ".sock"
  25803. : std::string("httplib-ws.sock");
  25804. std::remove(sock_path.c_str());
  25805. Server svr;
  25806. std::mutex mtx;
  25807. std::string received_host;
  25808. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25809. {
  25810. std::lock_guard<std::mutex> lock(mtx);
  25811. received_host = req.get_header_value("Host");
  25812. }
  25813. std::string msg;
  25814. while (ws.read(msg)) {
  25815. ws.send(msg);
  25816. }
  25817. });
  25818. svr.set_address_family(AF_UNIX);
  25819. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25820. auto se = detail::scope_exit([&] {
  25821. svr.stop();
  25822. t.join();
  25823. std::remove(sock_path.c_str());
  25824. });
  25825. svr.wait_until_ready();
  25826. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25827. client.set_address_family(AF_UNIX);
  25828. ASSERT_TRUE(client.connect());
  25829. ASSERT_TRUE(client.send("hello"));
  25830. std::string msg;
  25831. ASSERT_TRUE(client.read(msg));
  25832. client.close();
  25833. {
  25834. std::lock_guard<std::mutex> lock(mtx);
  25835. // There is no host:port for a Unix socket, so the same "localhost"
  25836. // placeholder the HTTP client uses is expected.
  25837. EXPECT_EQ("localhost", received_host);
  25838. }
  25839. }
  25840. // Two threads must never parse WebSocket frames from the same stream.
  25841. // close() used to read the peer's Close reply with its own frame read, so it
  25842. // raced a reader thread that was in the middle of a payload: the payload loop
  25843. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25844. // so bytes taken by close() were replaced with bytes from further along the
  25845. // stream. The message kept its length and silently changed content.
  25846. //
  25847. // The raw peer below sends a frame header plus part of the payload, waits for
  25848. // the handler to call close(), and only then sends the rest. Whichever thread
  25849. // would win the race for those bytes, the message must arrive intact, because
  25850. // close() must not touch the stream while read() owns it.
  25851. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25852. #ifndef _WIN32
  25853. signal(SIGPIPE, SIG_IGN);
  25854. #endif
  25855. const size_t payload_len = 120; // fits the 7-bit length field
  25856. const size_t prefix_len = 8;
  25857. const int attempts = 8;
  25858. std::string expected(payload_len, '\0');
  25859. for (size_t i = 0; i < payload_len; i++) {
  25860. expected[i] = static_cast<char>('a' + i % 26);
  25861. }
  25862. std::atomic<bool> peer_stalled{false};
  25863. std::atomic<bool> handler_done{false};
  25864. std::mutex received_mutex;
  25865. std::vector<std::string> received;
  25866. // Bound every wait, so a regression fails the test instead of hanging the
  25867. // suite.
  25868. auto wait_for = [](const std::atomic<bool> &flag) {
  25869. for (int i = 0; i < 500 && !flag; i++) {
  25870. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25871. }
  25872. };
  25873. Server svr;
  25874. svr.set_websocket_ping_interval(0);
  25875. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25876. std::thread reader([&]() {
  25877. std::string msg;
  25878. while (ws.read(msg)) {
  25879. std::lock_guard<std::mutex> guard(received_mutex);
  25880. received.push_back(msg);
  25881. }
  25882. });
  25883. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25884. // inside a frame when close() runs.
  25885. wait_for(peer_stalled);
  25886. ws.close();
  25887. reader.join();
  25888. handler_done = true;
  25889. });
  25890. auto port = svr.bind_to_any_port("127.0.0.1");
  25891. std::thread t([&]() { svr.listen_after_bind(); });
  25892. auto se = detail::scope_exit([&] {
  25893. svr.stop();
  25894. t.join();
  25895. });
  25896. svr.wait_until_ready();
  25897. auto send_bytes = [](socket_t s, const std::string &data) {
  25898. #ifdef _WIN32
  25899. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25900. #else
  25901. auto n = ::send(s, data.data(), data.size(), 0);
  25902. #endif
  25903. return n == static_cast<decltype(n)>(data.size());
  25904. };
  25905. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25906. // Every length used here fits the 7-bit length field.
  25907. auto masked_header = [](uint8_t first_byte, size_t len) {
  25908. std::string h;
  25909. h += static_cast<char>(first_byte);
  25910. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25911. h.append(4, '\0'); // mask key
  25912. return h;
  25913. };
  25914. for (int attempt = 0; attempt < attempts; attempt++) {
  25915. peer_stalled = false;
  25916. handler_done = false;
  25917. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25918. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25919. auto se_sock = detail::scope_exit([&] {
  25920. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25921. });
  25922. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25923. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25924. sockaddr_in addr{};
  25925. addr.sin_family = AF_INET;
  25926. addr.sin_port = htons(static_cast<uint16_t>(port));
  25927. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25928. ASSERT_EQ(
  25929. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25930. << "attempt " << attempt;
  25931. ASSERT_TRUE(send_bytes(sock,
  25932. "GET /ws HTTP/1.1\r\n"
  25933. "Host: 127.0.0.1\r\n"
  25934. "Upgrade: websocket\r\n"
  25935. "Connection: Upgrade\r\n"
  25936. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25937. "Sec-WebSocket-Version: 13\r\n"
  25938. "\r\n"))
  25939. << "attempt " << attempt;
  25940. std::string response;
  25941. while (response.find("\r\n\r\n") == std::string::npos) {
  25942. char buf[512];
  25943. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25944. if (n <= 0) { break; }
  25945. response.append(buf, static_cast<size_t>(n));
  25946. }
  25947. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25948. << "attempt " << attempt;
  25949. // Send the header of a Binary message but only the first prefix_len bytes
  25950. // of its payload, leaving the reader thread stalled inside the payload.
  25951. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25952. expected.substr(0, prefix_len)))
  25953. << "attempt " << attempt;
  25954. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25955. peer_stalled = true;
  25956. // Let close() send its Close frame and park in its own read before the
  25957. // rest of the payload arrives, so both threads are waiting for it.
  25958. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25959. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25960. close_frame += static_cast<char>(0x03); // status 1000
  25961. close_frame += static_cast<char>(0xE8);
  25962. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25963. << "attempt " << attempt;
  25964. // Closing the peer releases the reader thread even on the buggy path,
  25965. // where it waits for bytes another thread already consumed.
  25966. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25967. detail::close_socket(sock);
  25968. sock = INVALID_SOCKET;
  25969. wait_for(handler_done);
  25970. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25971. }
  25972. std::lock_guard<std::mutex> guard(received_mutex);
  25973. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25974. << "a message in flight when close() ran was dropped";
  25975. for (size_t i = 0; i < received.size(); i++) {
  25976. EXPECT_EQ(expected, received[i]) << "message " << i;
  25977. }
  25978. }
  25979. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25980. // returning the socket, or INVALID_SOCKET.
  25981. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25982. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25983. if (sock == INVALID_SOCKET) { return sock; }
  25984. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25985. sockaddr_in addr{};
  25986. addr.sin_family = AF_INET;
  25987. addr.sin_port = htons(static_cast<uint16_t>(port));
  25988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25989. std::string req = "GET " + path +
  25990. " HTTP/1.1\r\n"
  25991. "Host: 127.0.0.1\r\n"
  25992. "Upgrade: websocket\r\n"
  25993. "Connection: Upgrade\r\n"
  25994. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25995. "Sec-WebSocket-Version: 13\r\n"
  25996. "\r\n";
  25997. std::string res;
  25998. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25999. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26000. static_cast<ssize_t>(req.size())) {
  26001. char c;
  26002. while (res.find("\r\n\r\n") == std::string::npos &&
  26003. ::recv(sock, &c, 1, 0) == 1) {
  26004. res += c;
  26005. }
  26006. }
  26007. if (res.find(" 101 ") == std::string::npos) {
  26008. detail::close_socket(sock);
  26009. return INVALID_SOCKET;
  26010. }
  26011. return sock;
  26012. }
  26013. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26014. // The payload must fit the 7-bit length field.
  26015. static std::string masked_frame(uint8_t first_byte,
  26016. const std::string &payload) {
  26017. std::string f;
  26018. f += static_cast<char>(first_byte);
  26019. f += static_cast<char>(0x80 | payload.size());
  26020. f.append(4, '\0');
  26021. return f + payload;
  26022. }
  26023. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26024. std::atomic<bool> done{false};
  26025. std::string received;
  26026. Server svr;
  26027. svr.set_websocket_ping_interval(0);
  26028. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26029. std::string msg;
  26030. if (ws.read(msg) == ws::Binary) { received = msg; }
  26031. done = true;
  26032. });
  26033. auto port = svr.bind_to_any_port("127.0.0.1");
  26034. std::thread t([&]() { svr.listen_after_bind(); });
  26035. auto se = detail::scope_exit([&] {
  26036. svr.stop();
  26037. t.join();
  26038. });
  26039. svr.wait_until_ready();
  26040. auto sock = connect_raw_websocket(port, "/ws");
  26041. ASSERT_NE(INVALID_SOCKET, sock);
  26042. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26043. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26044. masked_frame(0x89, "p") + // FIN + Ping
  26045. masked_frame(0x80, "lo"); // FIN + Continuation
  26046. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26047. for (int i = 0; i < 500 && !done; i++) {
  26048. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26049. }
  26050. ASSERT_TRUE(done);
  26051. EXPECT_EQ("Hello", received);
  26052. // The Ping between the fragments is answered with a Pong.
  26053. char pong[3];
  26054. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26055. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26056. }
  26057. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26058. #ifndef _WIN32
  26059. signal(SIGPIPE, SIG_IGN);
  26060. #endif
  26061. std::atomic<bool> read_ended{false};
  26062. std::atomic<bool> sending{true};
  26063. Server svr;
  26064. svr.set_websocket_ping_interval(0);
  26065. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26066. std::thread reader([&]() {
  26067. std::string msg;
  26068. while (ws.read(msg)) {}
  26069. read_ended = true;
  26070. });
  26071. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26072. ws.close();
  26073. reader.join();
  26074. });
  26075. auto port = svr.bind_to_any_port("127.0.0.1");
  26076. std::thread t([&]() { svr.listen_after_bind(); });
  26077. auto se = detail::scope_exit([&] {
  26078. svr.stop();
  26079. t.join();
  26080. });
  26081. svr.wait_until_ready();
  26082. auto sock = connect_raw_websocket(port, "/ws");
  26083. ASSERT_NE(INVALID_SOCKET, sock);
  26084. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26085. // A Text message whose empty continuation frames never end
  26086. std::thread sender([&]() {
  26087. auto data = masked_frame(0x01, "");
  26088. while (sending) {
  26089. data += masked_frame(0x00, "");
  26090. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26091. return;
  26092. }
  26093. data.clear();
  26094. }
  26095. });
  26096. for (int i = 0; i < 300 && !read_ended; i++) {
  26097. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26098. }
  26099. sending = false;
  26100. sender.join();
  26101. EXPECT_TRUE(read_ended);
  26102. }
  26103. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26104. Server svr;
  26105. svr.set_websocket_ping_interval(-1);
  26106. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26107. std::string msg;
  26108. while (ws.read(msg)) {}
  26109. });
  26110. auto port = svr.bind_to_any_port("127.0.0.1");
  26111. std::thread t([&]() { svr.listen_after_bind(); });
  26112. auto se = detail::scope_exit([&] {
  26113. svr.stop();
  26114. t.join();
  26115. });
  26116. svr.wait_until_ready();
  26117. auto sock = connect_raw_websocket(port, "/ws");
  26118. ASSERT_NE(INVALID_SOCKET, sock);
  26119. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26120. // Nothing comes while the client stays quiet.
  26121. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26122. char c;
  26123. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26124. }
  26125. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26126. // and that has to end a read() already waiting on the peer, on every platform.
  26127. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26128. // The peer sends no pings, and its handler never calls read(), which is
  26129. // where pongs are written.
  26130. std::mutex mutex;
  26131. std::condition_variable cv;
  26132. auto release = false;
  26133. svr.set_websocket_ping_interval(0);
  26134. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26135. std::unique_lock<std::mutex> lock(mutex);
  26136. cv.wait(lock, [&] { return release; });
  26137. });
  26138. auto port = svr.bind_to_any_port(HOST);
  26139. std::thread t([&]() { svr.listen_after_bind(); });
  26140. auto se = detail::scope_exit([&] {
  26141. {
  26142. std::lock_guard<std::mutex> lock(mutex);
  26143. release = true;
  26144. }
  26145. cv.notify_all();
  26146. svr.stop();
  26147. t.join();
  26148. });
  26149. svr.wait_until_ready();
  26150. ws::WebSocketClient client(std::string(scheme) +
  26151. "://localhost:" + std::to_string(port) + "/ws");
  26152. #ifdef CPPHTTPLIB_SSL_ENABLED
  26153. client.enable_server_certificate_verification(false);
  26154. #endif
  26155. // A ping a second, given up on after two go unanswered: about 3s
  26156. client.set_websocket_ping_interval(1);
  26157. client.set_websocket_max_missed_pongs(2);
  26158. // Well past that, so that a read the timeout ends instead stands out
  26159. client.set_read_timeout(10);
  26160. ASSERT_TRUE(client.connect());
  26161. auto start = std::chrono::steady_clock::now();
  26162. std::string msg;
  26163. EXPECT_EQ(ws::Fail, client.read(msg));
  26164. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26165. std::chrono::steady_clock::now() - start)
  26166. .count(),
  26167. 6000);
  26168. EXPECT_FALSE(client.is_open());
  26169. }
  26170. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26171. Server svr;
  26172. check_pong_timeout_ends_read(svr, "ws");
  26173. }
  26174. #ifdef CPPHTTPLIB_SSL_ENABLED
  26175. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26177. ASSERT_TRUE(svr.is_valid());
  26178. check_pong_timeout_ends_read(svr, "wss");
  26179. }
  26180. #endif
  26181. // listen() returns only after every handler has, so Server::stop() has to end
  26182. // a WebSocket handler's read() waiting on a client that stays connected and
  26183. // quiet, whether or not the handler bounded its reads, and the client's
  26184. // connection ends with it.
  26185. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26186. bool bounded) {
  26187. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26188. if (bounded) { ws.set_read_timeout(0, 50000); }
  26189. std::string msg;
  26190. while (ws.read(msg) != ws::Fail) {}
  26191. });
  26192. auto port = svr.bind_to_any_port(HOST);
  26193. std::thread t([&]() { svr.listen_after_bind(); });
  26194. auto se = detail::scope_exit([&] {
  26195. if (t.joinable()) {
  26196. svr.stop();
  26197. t.join();
  26198. }
  26199. });
  26200. svr.wait_until_ready();
  26201. ws::WebSocketClient client(std::string(scheme) +
  26202. "://localhost:" + std::to_string(port) + "/ws");
  26203. #ifdef CPPHTTPLIB_SSL_ENABLED
  26204. client.enable_server_certificate_verification(false);
  26205. #endif
  26206. client.set_read_timeout(2);
  26207. ASSERT_TRUE(client.connect());
  26208. auto stopped = std::async(std::launch::async, [&] {
  26209. svr.stop();
  26210. t.join();
  26211. });
  26212. std::string msg;
  26213. EXPECT_EQ(ws::Fail, client.read(msg));
  26214. EXPECT_FALSE(client.is_open());
  26215. auto in_time =
  26216. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26217. // A handler the stop did not reach ends when the client leaves
  26218. if (!in_time) { client.close(); }
  26219. stopped.wait();
  26220. EXPECT_TRUE(in_time);
  26221. }
  26222. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26223. Server svr;
  26224. check_stop_ends_websocket_read(svr, "ws", false);
  26225. }
  26226. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26227. Server svr;
  26228. check_stop_ends_websocket_read(svr, "ws", true);
  26229. }
  26230. #ifdef CPPHTTPLIB_SSL_ENABLED
  26231. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26233. ASSERT_TRUE(svr.is_valid());
  26234. check_stop_ends_websocket_read(svr, "wss", false);
  26235. }
  26236. #endif
  26237. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26238. // dropped connection, whether the handler waits for a message or for the rest
  26239. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26240. // time out inside the message as well, and the stop ends them too.
  26241. static void check_stop_closes_with_going_away(const std::string &sent,
  26242. bool bounded = false) {
  26243. Server svr;
  26244. svr.set_websocket_ping_interval(0);
  26245. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26246. if (bounded) { ws.set_read_timeout(0, 10000); }
  26247. std::string msg;
  26248. while (ws.read(msg) != ws::Fail) {}
  26249. });
  26250. auto port = svr.bind_to_any_port("127.0.0.1");
  26251. std::thread t([&]() { svr.listen_after_bind(); });
  26252. auto se = detail::scope_exit([&] {
  26253. svr.stop();
  26254. t.join();
  26255. });
  26256. svr.wait_until_ready();
  26257. // Closed before the join above, which a handler the stop did not reach
  26258. // would otherwise hold up.
  26259. auto sock = connect_raw_websocket(port, "/ws");
  26260. ASSERT_NE(INVALID_SOCKET, sock);
  26261. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26262. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26263. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26264. // Let the handler take what was sent and wait for more
  26265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26266. svr.stop();
  26267. // FIN + Close, its length, then the code: unmasked, from a server
  26268. std::string head;
  26269. char c;
  26270. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26271. head += c;
  26272. }
  26273. const std::string reason = "server stopping";
  26274. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26275. "\x03\xe9",
  26276. head);
  26277. }
  26278. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26279. check_stop_closes_with_going_away("");
  26280. }
  26281. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26282. // A Text frame without FIN: the first fragment of a message
  26283. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26284. }
  26285. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26286. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26287. /*bounded=*/true);
  26288. }
  26289. // A handler that bounds its reads gets control back within its timeout even
  26290. // while a message arrives in pieces, and the message whole once the last has
  26291. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26292. // sent a while after the one before, much longer than the handler's timeout.
  26293. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26294. const std::string &expected) {
  26295. std::atomic<bool> done{false};
  26296. std::string received;
  26297. std::chrono::steady_clock::duration longest{};
  26298. Server svr;
  26299. svr.set_websocket_ping_interval(0);
  26300. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26301. ws.set_read_timeout(0, 10000);
  26302. std::string msg;
  26303. ws::ReadResult r;
  26304. do {
  26305. auto began = std::chrono::steady_clock::now();
  26306. r = ws.read(msg);
  26307. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26308. } while (r == ws::Timeout);
  26309. if (r == ws::Text) { received = msg; }
  26310. done = true;
  26311. });
  26312. auto port = svr.bind_to_any_port("127.0.0.1");
  26313. std::thread t([&]() { svr.listen_after_bind(); });
  26314. auto se = detail::scope_exit([&] {
  26315. svr.stop();
  26316. t.join();
  26317. });
  26318. svr.wait_until_ready();
  26319. auto sock = connect_raw_websocket(port, "/ws");
  26320. ASSERT_NE(INVALID_SOCKET, sock);
  26321. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26322. for (const auto &piece : pieces) {
  26323. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26324. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26325. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26326. }
  26327. for (int i = 0; i < 500 && !done; i++) {
  26328. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26329. }
  26330. ASSERT_TRUE(done);
  26331. EXPECT_EQ(expected, received);
  26332. // Far under the 200 ms between the pieces, however loaded the machine
  26333. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26334. }
  26335. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26336. // The header's first byte, then its second with half the mask key, then
  26337. // the rest: what a frame written in several writes may look like when
  26338. // Nagle's algorithm holds the later ones back for an ACK.
  26339. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26340. check_bounded_read_resumes(
  26341. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26342. }
  26343. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26344. check_bounded_read_resumes(
  26345. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26346. }
  26347. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26348. Server svr;
  26349. svr.set_websocket_ping_interval(0);
  26350. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26351. std::string msg;
  26352. while (ws.read(msg)) {}
  26353. });
  26354. auto port = svr.bind_to_any_port("127.0.0.1");
  26355. std::thread t([&]() { svr.listen_after_bind(); });
  26356. auto se = detail::scope_exit([&] {
  26357. svr.stop();
  26358. t.join();
  26359. });
  26360. svr.wait_until_ready();
  26361. // Each Close payload and the reply it should get: an echo when valid, 1002
  26362. // otherwise.
  26363. std::vector<std::pair<std::string, std::string>> cases = {
  26364. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26365. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26366. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26367. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26368. };
  26369. // Also between the fragments of a message.
  26370. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26371. for (const auto &c : cases) {
  26372. auto sock = connect_raw_websocket(port, "/ws");
  26373. ASSERT_NE(INVALID_SOCKET, sock);
  26374. auto frames = prefix + masked_frame(0x88, c.first);
  26375. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26376. std::string reply;
  26377. char buf[256];
  26378. while (reply.size() < 2 + c.second.size()) {
  26379. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26380. if (n <= 0) { break; }
  26381. reply.append(buf, static_cast<size_t>(n));
  26382. }
  26383. detail::close_socket(sock);
  26384. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26385. c.second,
  26386. reply);
  26387. }
  26388. }
  26389. }
  26390. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26391. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26392. protected:
  26393. void SetUp() override {
  26394. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26395. SERVER_PRIVATE_KEY_FILE);
  26396. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26397. std::string msg;
  26398. ws::ReadResult ret;
  26399. while ((ret = ws.read(msg))) {
  26400. if (ret == ws::Binary) {
  26401. ws.send(msg.data(), msg.size());
  26402. } else {
  26403. ws.send(msg);
  26404. }
  26405. }
  26406. });
  26407. port_ = server_->bind_to_any_port(HOST);
  26408. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26409. server_->wait_until_ready();
  26410. }
  26411. void TearDown() override {
  26412. server_->stop();
  26413. if (server_thread_.joinable()) { server_thread_.join(); }
  26414. }
  26415. std::unique_ptr<SSLServer> server_;
  26416. std::thread server_thread_;
  26417. int port_ = 0;
  26418. };
  26419. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26420. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26421. {
  26422. ws::WebSocketClient client(url);
  26423. client.enable_server_certificate_verification(false);
  26424. auto calls = 0;
  26425. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26426. calls++;
  26427. return false;
  26428. });
  26429. EXPECT_FALSE(client.connect());
  26430. EXPECT_GT(calls, 0);
  26431. }
  26432. {
  26433. ws::WebSocketClient client(url);
  26434. client.enable_server_certificate_verification(false);
  26435. client.set_session_verifier([](tls::session_t) {
  26436. return SSLVerifierResponse::CertificateRejected;
  26437. });
  26438. EXPECT_FALSE(client.connect());
  26439. }
  26440. {
  26441. ws::WebSocketClient client(url);
  26442. client.enable_server_certificate_verification(false);
  26443. client.set_session_verifier([](tls::session_t) {
  26444. return SSLVerifierResponse::CertificateAccepted;
  26445. });
  26446. EXPECT_TRUE(client.connect());
  26447. }
  26448. }
  26449. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26450. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26451. "/ws-echo");
  26452. client.enable_server_certificate_verification(false);
  26453. ASSERT_TRUE(client.connect());
  26454. ASSERT_TRUE(client.is_open());
  26455. ASSERT_TRUE(client.send("Hello WSS"));
  26456. std::string msg;
  26457. EXPECT_EQ(ws::Text, client.read(msg));
  26458. EXPECT_EQ("Hello WSS", msg);
  26459. client.close();
  26460. }
  26461. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26462. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26463. "/ws-echo");
  26464. client.enable_server_certificate_verification(false);
  26465. EXPECT_TRUE(client.connect());
  26466. }
  26467. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26468. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26469. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26470. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26471. // client (without calling close() first) is the only path that runs
  26472. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26473. // bug exactly.
  26474. //
  26475. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26476. // when linked against an instrumented libssl; run under Valgrind to catch it
  26477. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26478. // suite (the freed session otherwise stalls on the close handshake) — this test
  26479. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26480. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26481. {
  26482. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26483. "/ws-echo");
  26484. client.enable_server_certificate_verification(false);
  26485. client.set_read_timeout(2, 0);
  26486. client.set_write_timeout(2, 0);
  26487. ASSERT_TRUE(client.connect());
  26488. ASSERT_TRUE(client.is_open());
  26489. ASSERT_TRUE(client.send("still open"));
  26490. // Intentionally do NOT call client.close(): leaving scope runs
  26491. // shutdown_and_close() with the WebSocket still open, which must send the
  26492. // close frame while the TLS session is still alive.
  26493. }
  26494. }
  26495. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26496. // shutdown_and_close() at the start of connect(), reproducing the same
  26497. // use-after-free within the test body rather than at scope exit. The second
  26498. // connect must succeed and echo, proving the close handshake ran over a live
  26499. // session. See the note above about memory-tool requirements.
  26500. TEST_F(WebSocketSSLIntegrationTest,
  26501. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26502. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26503. "/ws-echo");
  26504. client.enable_server_certificate_verification(false);
  26505. client.set_read_timeout(2, 0);
  26506. client.set_write_timeout(2, 0);
  26507. ASSERT_TRUE(client.connect());
  26508. ASSERT_TRUE(client.is_open());
  26509. ASSERT_TRUE(client.send("still open"));
  26510. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26511. // the still-open connection, which must not touch a freed TLS session.
  26512. ASSERT_TRUE(client.connect());
  26513. ASSERT_TRUE(client.is_open());
  26514. ASSERT_TRUE(client.send("after reconnect"));
  26515. std::string msg;
  26516. EXPECT_EQ(ws::Text, client.read(msg));
  26517. EXPECT_EQ("after reconnect", msg);
  26518. client.close();
  26519. }
  26520. #endif
  26521. #ifdef CPPHTTPLIB_SSL_ENABLED
  26522. class WebSocketSSLCATest : public ::testing::Test {
  26523. protected:
  26524. void SetUp() override {
  26525. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26526. SERVER_PRIVATE_KEY_FILE);
  26527. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26528. std::string msg;
  26529. while (ws.read(msg)) {
  26530. ws.send(msg);
  26531. }
  26532. });
  26533. port_ = server_->bind_to_any_port("127.0.0.1");
  26534. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26535. server_->wait_until_ready();
  26536. }
  26537. void TearDown() override {
  26538. server_->stop();
  26539. if (server_thread_.joinable()) { server_thread_.join(); }
  26540. }
  26541. std::string url() const {
  26542. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26543. }
  26544. std::unique_ptr<SSLServer> server_;
  26545. std::thread server_thread_;
  26546. int port_ = 0;
  26547. };
  26548. // A custom CA loaded as PEM verifies the server with full certificate
  26549. // verification enabled
  26550. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26551. ws::WebSocketClient client(url());
  26552. std::string cert;
  26553. read_file(SERVER_CERT2_FILE, cert);
  26554. client.load_ca_cert_store(cert.c_str(), cert.size());
  26555. ASSERT_TRUE(client.connect());
  26556. ASSERT_TRUE(client.send("hello"));
  26557. std::string msg;
  26558. EXPECT_EQ(ws::Text, client.read(msg));
  26559. EXPECT_EQ("hello", msg);
  26560. client.close();
  26561. }
  26562. // A custom CA that does not cover the server must fail verification (the
  26563. // custom CA is exclusive; system certs are not loaded alongside it)
  26564. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26565. ws::WebSocketClient client(url());
  26566. std::string cert;
  26567. read_file(CLIENT_CA_CERT_FILE, cert);
  26568. client.load_ca_cert_store(cert.c_str(), cert.size());
  26569. auto res = client.connect();
  26570. ASSERT_FALSE(res);
  26571. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26572. EXPECT_EQ(-1, res.status());
  26573. EXPECT_NE(0u, res.ssl_backend_error());
  26574. }
  26575. // The same CA as a file path rather than PEM in memory
  26576. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26577. ws::WebSocketClient client(url());
  26578. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26579. ASSERT_TRUE(client.connect());
  26580. ASSERT_TRUE(client.send("hello"));
  26581. std::string msg;
  26582. EXPECT_EQ(ws::Text, client.read(msg));
  26583. EXPECT_EQ("hello", msg);
  26584. client.close();
  26585. }
  26586. // ...and a CA file that does not cover the server still fails, so it is the
  26587. // path above that decides the outcome
  26588. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26589. ws::WebSocketClient client(url());
  26590. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26591. ASSERT_FALSE(client.connect());
  26592. }
  26593. // Regression test: reconnecting with a native custom CA store used to reuse
  26594. // a store handle the previous TLS context had already freed (use-after-free
  26595. // under the OpenSSL backend). The context now lives as long as the client.
  26596. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26597. ws::WebSocketClient client(url());
  26598. std::string cert;
  26599. read_file(SERVER_CERT2_FILE, cert);
  26600. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26601. ASSERT_TRUE(client.connect());
  26602. client.close();
  26603. ASSERT_TRUE(client.connect());
  26604. ASSERT_TRUE(client.send("again"));
  26605. std::string msg;
  26606. EXPECT_EQ(ws::Text, client.read(msg));
  26607. EXPECT_EQ("again", msg);
  26608. client.close();
  26609. }
  26610. // Regression test: a certificate with a trusted chain but no identity match
  26611. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26612. // verification entirely for IP hosts, so this connection succeeded there.
  26613. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26614. // chain verification while the identity check must still fail.
  26615. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26617. ASSERT_TRUE(svr.is_valid());
  26618. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26619. std::string msg;
  26620. while (ws.read(msg)) {
  26621. ws.send(msg);
  26622. }
  26623. });
  26624. auto port = svr.bind_to_any_port("127.0.0.1");
  26625. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26626. auto se = detail::scope_exit([&] {
  26627. svr.stop();
  26628. t.join();
  26629. });
  26630. svr.wait_until_ready();
  26631. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26632. "/echo");
  26633. std::string cert;
  26634. read_file(SERVER_CERT_FILE, cert);
  26635. client.load_ca_cert_store(cert.c_str(), cert.size());
  26636. ASSERT_FALSE(client.connect());
  26637. }
  26638. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26639. // SNI, so nothing binds the host name to the TLS session. These bind the
  26640. // server to "localhost" instead, the only shape that exercises the SNI and
  26641. // hostname-verification path with certificate verification left enabled.
  26642. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26643. protected:
  26644. void Start(const char *cert_file) {
  26645. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26646. SERVER_PRIVATE_KEY_FILE);
  26647. ASSERT_TRUE(server_->is_valid());
  26648. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26649. std::string msg;
  26650. while (ws.read(msg)) {
  26651. ws.send(msg);
  26652. }
  26653. });
  26654. port_ = server_->bind_to_any_port("localhost");
  26655. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26656. server_->wait_until_ready();
  26657. }
  26658. void TearDown() override {
  26659. if (server_) { server_->stop(); }
  26660. if (server_thread_.joinable()) { server_thread_.join(); }
  26661. }
  26662. std::string url() const {
  26663. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26664. }
  26665. std::unique_ptr<SSLServer> server_;
  26666. std::thread server_thread_;
  26667. int port_ = 0;
  26668. };
  26669. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26670. // out and the connection is usable
  26671. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26672. Start(SERVER_CERT2_FILE);
  26673. ws::WebSocketClient client(url());
  26674. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26675. ASSERT_TRUE(client.connect());
  26676. ASSERT_TRUE(client.send("hello"));
  26677. std::string msg;
  26678. EXPECT_EQ(ws::Text, client.read(msg));
  26679. EXPECT_EQ("hello", msg);
  26680. client.close();
  26681. }
  26682. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26683. // while the identity check must still reject "localhost"
  26684. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26685. Start(SERVER_CERT_FILE);
  26686. ws::WebSocketClient client(url());
  26687. client.set_ca_cert_path(SERVER_CERT_FILE);
  26688. auto res = client.connect();
  26689. ASSERT_FALSE(res);
  26690. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26691. EXPECT_EQ(-1, res.status());
  26692. }
  26693. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26694. // disabled: the chain is still checked, only the identity check is skipped
  26695. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26696. Start(SERVER_CERT_FILE);
  26697. ws::WebSocketClient client(url());
  26698. client.set_ca_cert_path(SERVER_CERT_FILE);
  26699. client.enable_server_hostname_verification(false);
  26700. ASSERT_TRUE(client.connect());
  26701. ASSERT_TRUE(client.send("hello"));
  26702. std::string msg;
  26703. EXPECT_EQ(ws::Text, client.read(msg));
  26704. EXPECT_EQ("hello", msg);
  26705. client.close();
  26706. }
  26707. // A CA that did not sign the server certificate fails the chain, even though
  26708. // the name would match
  26709. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26710. Start(SERVER_CERT2_FILE);
  26711. ws::WebSocketClient client(url());
  26712. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26713. ASSERT_FALSE(client.connect());
  26714. }
  26715. // With verification disabled, neither the chain nor the name is checked
  26716. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26717. Start(SERVER_CERT_FILE);
  26718. ws::WebSocketClient client(url());
  26719. client.enable_server_certificate_verification(false);
  26720. ASSERT_TRUE(client.connect());
  26721. ASSERT_TRUE(client.send("hello"));
  26722. std::string msg;
  26723. EXPECT_EQ(ws::Text, client.read(msg));
  26724. EXPECT_EQ("hello", msg);
  26725. client.close();
  26726. }
  26727. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26728. protected:
  26729. void SetUp() override {
  26730. server_ = httplib::detail::make_unique<SSLServer>(
  26731. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26732. ASSERT_TRUE(server_->is_valid());
  26733. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26734. std::string msg;
  26735. while (ws.read(msg)) {
  26736. ws.send(msg);
  26737. }
  26738. });
  26739. port_ = server_->bind_to_any_port("localhost");
  26740. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26741. server_->wait_until_ready();
  26742. }
  26743. void TearDown() override {
  26744. server_->stop();
  26745. if (server_thread_.joinable()) { server_thread_.join(); }
  26746. }
  26747. std::string url() const {
  26748. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26749. }
  26750. void ConnectWithClientCert(const std::string &client_cert_file,
  26751. const std::string &client_private_key_file,
  26752. const char *private_key_password) {
  26753. std::string cert_pem, key_pem;
  26754. read_file(client_cert_file, cert_pem);
  26755. read_file(client_private_key_file, key_pem);
  26756. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26757. key_pem.c_str(), key_pem.size(),
  26758. private_key_password};
  26759. ConnectWithPem(pem);
  26760. }
  26761. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26762. ws::WebSocketClient client(url(), pem);
  26763. ASSERT_TRUE(client.is_valid());
  26764. client.enable_server_certificate_verification(false);
  26765. ASSERT_TRUE(client.connect());
  26766. ASSERT_TRUE(client.send("hello"));
  26767. std::string msg;
  26768. EXPECT_EQ(ws::Text, client.read(msg));
  26769. EXPECT_EQ("hello", msg);
  26770. client.close();
  26771. }
  26772. std::unique_ptr<SSLServer> server_;
  26773. std::thread server_thread_;
  26774. int port_ = 0;
  26775. };
  26776. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26777. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26778. }
  26779. // Control for the tests above: the fixture's server really does require a
  26780. // client certificate, so it is the PEM the constructor installed that decides
  26781. // the outcome.
  26782. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26783. ws::WebSocketClient client(url());
  26784. ASSERT_TRUE(client.is_valid());
  26785. client.enable_server_certificate_verification(false);
  26786. EXPECT_FALSE(client.connect());
  26787. }
  26788. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26789. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26790. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26791. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26792. }
  26793. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26794. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26795. std::string cert_pem, key_pem;
  26796. read_file(CLIENT_CERT_FILE, cert_pem);
  26797. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26798. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26799. std::vector<char> key(key_pem.begin(), key_pem.end());
  26800. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26801. key.size(), nullptr};
  26802. ConnectWithPem(pem);
  26803. }
  26804. #endif
  26805. #if !defined(_WIN32)
  26806. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26807. auto secret_dir = std::string("./symlink_test_secret");
  26808. auto served_dir = std::string("./symlink_test_served");
  26809. auto secret_file = secret_dir + "/secret.txt";
  26810. auto symlink_path = served_dir + "/escape";
  26811. // Setup: create directories and files
  26812. mkdir(secret_dir.c_str(), 0755);
  26813. mkdir(served_dir.c_str(), 0755);
  26814. {
  26815. std::ofstream ofs(secret_file);
  26816. ofs << "SECRET_DATA";
  26817. }
  26818. // Create symlink using absolute path so it resolves correctly
  26819. #ifdef PATH_MAX
  26820. char abs_secret[PATH_MAX];
  26821. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26822. #else
  26823. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26824. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26825. ASSERT_NE(nullptr, abs_secret);
  26826. #endif
  26827. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26828. auto se = detail::scope_exit([&] {
  26829. unlink(symlink_path.c_str());
  26830. unlink(secret_file.c_str());
  26831. rmdir(served_dir.c_str());
  26832. rmdir(secret_dir.c_str());
  26833. });
  26834. Server svr;
  26835. svr.set_mount_point("/", served_dir);
  26836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26837. auto se2 = detail::scope_exit([&] {
  26838. svr.stop();
  26839. listen_thread.join();
  26840. });
  26841. svr.wait_until_ready();
  26842. Client cli("localhost", PORT);
  26843. // Symlink pointing outside base dir should be blocked
  26844. auto res = cli.Get("/escape/secret.txt");
  26845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26846. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26847. }
  26848. #else
  26849. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26850. auto secret_dir = std::string("junction_test_secret");
  26851. auto served_dir = std::string("junction_test_served");
  26852. auto secret_file = secret_dir + "\\secret.txt";
  26853. auto junction_path = served_dir + "\\escape";
  26854. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26855. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26856. {
  26857. std::ofstream ofs(secret_file);
  26858. ofs << "SECRET_DATA";
  26859. }
  26860. // A junction needs no privilege to create, unlike a symlink
  26861. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26862. ASSERT_EQ(0, std::system(cmd.c_str()));
  26863. auto se = detail::scope_exit([&] {
  26864. ::RemoveDirectoryA(junction_path.c_str());
  26865. std::remove(secret_file.c_str());
  26866. ::RemoveDirectoryA(served_dir.c_str());
  26867. ::RemoveDirectoryA(secret_dir.c_str());
  26868. });
  26869. Server svr;
  26870. svr.set_mount_point("/", served_dir);
  26871. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26872. auto se2 = detail::scope_exit([&] {
  26873. svr.stop();
  26874. listen_thread.join();
  26875. });
  26876. svr.wait_until_ready();
  26877. Client cli("localhost", PORT);
  26878. // Junction pointing outside base dir should be blocked
  26879. auto res = cli.Get("/escape/secret.txt");
  26880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26881. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26882. }
  26883. #endif
  26884. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26885. // "GET /smuggled" request), reads the first response, and only then sends the
  26886. // embedded request as the body. Returns how many times /smuggled ran.
  26887. //
  26888. // The body is sent AFTER receiving the first response (as in the original
  26889. // PoC) so that the stream_line_reader cannot buffer it together with the
  26890. // headers of the first request.
  26891. static int count_smuggled_requests(const std::string &outer_head,
  26892. std::string &first_response) {
  26893. Server svr;
  26894. svr.set_mount_point("/", "./www");
  26895. std::atomic<int> smuggled_count(0);
  26896. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26897. smuggled_count++;
  26898. res.set_content("oops", "text/plain");
  26899. });
  26900. svr.Post("/post", [&](const Request &req, Response &res) {
  26901. res.set_content(req.body, "text/plain");
  26902. });
  26903. auto port = svr.bind_to_any_port("localhost");
  26904. thread t = thread([&] { svr.listen_after_bind(); });
  26905. auto se = detail::scope_exit([&] {
  26906. svr.stop();
  26907. t.join();
  26908. });
  26909. svr.wait_until_ready();
  26910. auto error = Error::Success;
  26911. auto sock = detail::create_client_socket(
  26912. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26913. /*connection_timeout_sec=*/2, 0,
  26914. /*read_timeout_sec=*/2, 0,
  26915. /*write_timeout_sec=*/2, 0, std::string(), error);
  26916. EXPECT_NE(INVALID_SOCKET, sock);
  26917. if (sock == INVALID_SOCKET) { return -1; }
  26918. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26919. // The "smuggled" request will be sent as the body of the outer request
  26920. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26921. "Host: localhost\r\n"
  26922. "Connection: close\r\n"
  26923. "\r\n";
  26924. auto head = outer_head;
  26925. auto len = std::to_string(smuggled.size());
  26926. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26927. pos = head.find("{len}", pos + len.size())) {
  26928. head.replace(pos, 5, len);
  26929. }
  26930. // Step 1: Send only the outer request headers (no body yet)
  26931. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26932. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26933. // Step 2: Read the first response
  26934. char buf[4096];
  26935. for (;;) {
  26936. auto n = recv(sock, buf, sizeof(buf), 0);
  26937. if (n <= 0) break;
  26938. first_response.append(buf, static_cast<size_t>(n));
  26939. // Stop once we have a complete response (headers + body)
  26940. auto hdr_end = first_response.find("\r\n\r\n");
  26941. if (hdr_end != std::string::npos) {
  26942. // Check for Content-Length to know when the body is complete
  26943. auto cl_pos = first_response.find("Content-Length:");
  26944. if (cl_pos != std::string::npos) {
  26945. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26946. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26947. auto cl = std::stoul(
  26948. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26949. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26950. } else {
  26951. break; // No Content-Length, assume headers-only response
  26952. }
  26953. }
  26954. }
  26955. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26956. // vulnerable server the keep-alive loop reads this as a second request. The
  26957. // server may already have closed the connection, so the result is ignored.
  26958. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26959. // Half-close so that a server which drained the body sees EOF and closes,
  26960. // instead of the read below waiting for the read timeout.
  26961. #ifdef _WIN32
  26962. ::shutdown(sock, SD_SEND);
  26963. #else
  26964. ::shutdown(sock, SHUT_WR);
  26965. #endif
  26966. // Step 4: Read until the server closes the connection
  26967. for (;;) {
  26968. auto n = recv(sock, buf, sizeof(buf), 0);
  26969. if (n <= 0) break;
  26970. }
  26971. return smuggled_count.load();
  26972. }
  26973. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26974. // A GET request with Content-Length to a static file handler must have its
  26975. // body drained before the keep-alive connection is reused. Otherwise the
  26976. // unread body bytes are interpreted as the next HTTP request.
  26977. std::string first_response;
  26978. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26979. "Host: localhost\r\n"
  26980. "Content-Length: {len}\r\n"
  26981. "\r\n",
  26982. first_response));
  26983. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26984. }
  26985. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26986. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26987. // be answered with 400 and the connection closed. Treating it as "no body"
  26988. // leaves the body to be parsed as the next request.
  26989. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26990. const char *targets[] = {
  26991. "GET /file", // handler that never reads the body
  26992. "GET /not-found", // no handler matches (404)
  26993. "POST /post", // handler that reads the body
  26994. };
  26995. for (auto target : targets) {
  26996. for (auto value : values) {
  26997. std::string first_response;
  26998. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26999. " HTTP/1.1\r\n"
  27000. "Host: localhost\r\n"
  27001. "Content-Length: " +
  27002. value + "\r\n\r\n",
  27003. first_response))
  27004. << target << " with Content-Length: " << value;
  27005. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27006. << target << " with Content-Length: " << value;
  27007. }
  27008. }
  27009. }
  27010. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27011. // A 400 for an unparseable request line leaves the rest of the message
  27012. // unread, so the connection must be closed rather than reused.
  27013. std::string first_response;
  27014. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27015. "Host: localhost\r\n"
  27016. "Content-Length: {len}\r\n"
  27017. "\r\n",
  27018. first_response));
  27019. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27020. }
  27021. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27022. // Same as above for a header block that fails to parse.
  27023. std::string first_response;
  27024. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27025. "Host: localhost\r\n"
  27026. "Bad Header\r\n"
  27027. "Content-Length: {len}\r\n"
  27028. "\r\n",
  27029. first_response));
  27030. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27031. }
  27032. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27033. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27034. // server must not read another request on that connection, even when the
  27035. // request had no body to drain.
  27036. std::string first_response;
  27037. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27038. "Host: localhost\r\n"
  27039. "\r\n",
  27040. first_response));
  27041. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27042. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27043. }
  27044. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27045. // A content reader that stops early leaves the stream inside the body.
  27046. // Draining the whole Content-Length from there, or reading the body again,
  27047. // reads into the next request, and whatever follows is parsed as a request
  27048. // of its own.
  27049. Server svr;
  27050. std::atomic<int> smuggled_count(0);
  27051. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27052. svr.Post("/upload", [](const Request &req, Response &res,
  27053. const ContentReader &content_reader) {
  27054. // Stop at the last chunk, so the whole body has been read however it
  27055. // arrives.
  27056. auto length = req.get_header_value_u64("Content-Length");
  27057. size_t total = 0;
  27058. auto consumed = content_reader([&](const char *, size_t n) {
  27059. total += n;
  27060. return total < length;
  27061. });
  27062. EXPECT_FALSE(consumed);
  27063. if (req.has_param("retry")) {
  27064. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27065. }
  27066. // Replace the 400 the aborted read set, which would close the connection.
  27067. res.set_redirect("/done");
  27068. });
  27069. auto port = svr.bind_to_any_port(HOST);
  27070. thread t = thread([&] { svr.listen_after_bind(); });
  27071. auto se = detail::scope_exit([&] {
  27072. svr.stop();
  27073. t.join();
  27074. });
  27075. svr.wait_until_ready();
  27076. // A front end sees the second request as a POST whose body is the GET. The
  27077. // first body is as long as the POST's headers, so draining it again reads
  27078. // exactly those and leaves the GET to be parsed next.
  27079. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27080. "Host: localhost\r\n"
  27081. "\r\n";
  27082. std::string second_head = "POST /post HTTP/1.1\r\n"
  27083. "Host: localhost\r\n"
  27084. "Content-Length: " +
  27085. std::to_string(inner.size()) +
  27086. "\r\n"
  27087. "\r\n";
  27088. for (auto target : {"/upload", "/upload?retry"}) {
  27089. smuggled_count = 0;
  27090. std::string request = "POST " + std::string(target) +
  27091. " HTTP/1.1\r\n"
  27092. "Host: localhost\r\n"
  27093. "Content-Length: " +
  27094. std::to_string(second_head.size()) +
  27095. "\r\n"
  27096. "\r\n" +
  27097. std::string(second_head.size(), 'A') + second_head +
  27098. inner;
  27099. std::string response;
  27100. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27101. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27102. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27103. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27104. EXPECT_EQ(0, smuggled_count.load()) << target;
  27105. }
  27106. }
  27107. // An error response closes the connection anyway, so the body is left unread
  27108. // with a redirect, such as one to a login page.
  27109. static void serve_redirects(Server &svr,
  27110. const std::function<void(int)> &client) {
  27111. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27112. res.set_redirect("/login");
  27113. return Server::HandlerResponse::Handled;
  27114. });
  27115. auto port = svr.bind_to_any_port(HOST);
  27116. ASSERT_GT(port, 0);
  27117. thread t = thread([&] { svr.listen_after_bind(); });
  27118. auto se = detail::scope_exit([&] {
  27119. svr.stop();
  27120. t.join();
  27121. ASSERT_FALSE(svr.is_running());
  27122. });
  27123. svr.wait_until_ready();
  27124. client(port);
  27125. }
  27126. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27127. Server svr;
  27128. serve_redirects(svr, [](int port) {
  27129. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27130. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27131. std::to_string(body.size()) + "\r\n\r\n" + body +
  27132. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27133. std::string resp;
  27134. ASSERT_TRUE(send_request(1, req, &resp, port));
  27135. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27136. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27137. });
  27138. }
  27139. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27140. Server svr;
  27141. svr.set_read_timeout(0, 200000);
  27142. serve_redirects(svr, [](int port) {
  27143. // A byte every 100 ms keeps each read within the read timeout, but not the
  27144. // body as a whole, so the server closes and the bytes sent after that fail.
  27145. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27146. "Content-Length: 10\r\n\r\n"};
  27147. parts.resize(11, "x");
  27148. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27149. });
  27150. }
  27151. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27152. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27153. // must be rejected with 400 Bad Request.
  27154. Server svr;
  27155. svr.Post("/test", [&](const Request &, Response &res) {
  27156. res.set_content("ok", "text/plain");
  27157. });
  27158. thread t = thread([&] { svr.listen(HOST, PORT); });
  27159. auto se = detail::scope_exit([&] {
  27160. svr.stop();
  27161. t.join();
  27162. ASSERT_FALSE(svr.is_running());
  27163. });
  27164. svr.wait_until_ready();
  27165. // Exact "chunked"
  27166. {
  27167. auto req = "POST /test HTTP/1.1\r\n"
  27168. "Host: localhost\r\n"
  27169. "Content-Length: 5\r\n"
  27170. "Transfer-Encoding: chunked\r\n"
  27171. "Connection: close\r\n"
  27172. "\r\n"
  27173. "hello";
  27174. std::string response;
  27175. ASSERT_TRUE(send_request(1, req, &response));
  27176. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27177. response.substr(0, response.find("\r\n")));
  27178. }
  27179. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27180. {
  27181. auto req = "POST /test HTTP/1.1\r\n"
  27182. "Host: localhost\r\n"
  27183. "Content-Length: 5\r\n"
  27184. "Transfer-Encoding: gzip, chunked\r\n"
  27185. "Connection: close\r\n"
  27186. "\r\n"
  27187. "hello";
  27188. std::string response;
  27189. ASSERT_TRUE(send_request(1, req, &response));
  27190. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27191. response.substr(0, response.find("\r\n")));
  27192. }
  27193. }
  27194. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27195. Server svr;
  27196. svr.Post("/test", [&](const Request &, Response &res) {
  27197. res.set_content("ok", "text/plain");
  27198. });
  27199. thread t = thread([&] { svr.listen(HOST, PORT); });
  27200. auto se = detail::scope_exit([&] {
  27201. svr.stop();
  27202. t.join();
  27203. ASSERT_FALSE(svr.is_running());
  27204. });
  27205. svr.wait_until_ready();
  27206. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27207. // length cannot be determined, so the server must answer 400 and close
  27208. // rather than treat the request as bodyless and leave the body in the
  27209. // socket for the next request to pick up.
  27210. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27211. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27212. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27213. std::string response;
  27214. ASSERT_TRUE(send_request(1, req, &response));
  27215. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27216. response.substr(0, response.find("\r\n")))
  27217. << transfer_encoding;
  27218. }
  27219. // RFC 9110 5.3: the codings may also be split across several
  27220. // Transfer-Encoding lines, which combine in the order they were received.
  27221. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27222. // just like the single-line "chunked, gzip" above.
  27223. {
  27224. auto req = "POST /test HTTP/1.1\r\n"
  27225. "Host: localhost\r\n"
  27226. "Transfer-Encoding: chunked\r\n"
  27227. "Transfer-Encoding: gzip\r\n"
  27228. "\r\n"
  27229. "0\r\n\r\n";
  27230. std::string response;
  27231. ASSERT_TRUE(send_request(1, req, &response));
  27232. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27233. response.substr(0, response.find("\r\n")));
  27234. }
  27235. }
  27236. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27237. Server svr;
  27238. svr.Post("/test", [&](const Request &, Response &res) {
  27239. res.set_content("ok", "text/plain");
  27240. });
  27241. auto port = svr.bind_to_any_port(HOST);
  27242. ASSERT_GT(port, 0);
  27243. thread t = thread([&] { svr.listen_after_bind(); });
  27244. auto se = detail::scope_exit([&] {
  27245. svr.stop();
  27246. t.join();
  27247. ASSERT_FALSE(svr.is_running());
  27248. });
  27249. svr.wait_until_ready();
  27250. for (auto transfer_encoding :
  27251. {"Transfer-Encoding: gzip, chunked\r\n",
  27252. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27253. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27254. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27255. transfer_encoding + "\r\n0\r\n\r\n";
  27256. std::string response;
  27257. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27258. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27259. response.substr(0, response.find("\r\n")))
  27260. << transfer_encoding;
  27261. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27262. << transfer_encoding;
  27263. }
  27264. }
  27265. // Regression for issue #2450: a DELETE without Content-Length on a
  27266. // keep-alive connection must not let the post-response drain consume the
  27267. // next request's bytes.
  27268. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27269. Server svr;
  27270. std::atomic<int> delete_count(0);
  27271. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27272. delete_count++;
  27273. res.status = StatusCode::NoContent_204;
  27274. });
  27275. auto port = svr.bind_to_any_port(HOST);
  27276. thread t = thread([&] { svr.listen_after_bind(); });
  27277. auto se = detail::scope_exit([&] {
  27278. svr.stop();
  27279. t.join();
  27280. });
  27281. svr.wait_until_ready();
  27282. auto error = Error::Success;
  27283. auto sock = detail::create_client_socket(
  27284. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27285. /*connection_timeout_sec=*/2, 0,
  27286. /*read_timeout_sec=*/2, 0,
  27287. /*write_timeout_sec=*/2, 0, std::string(), error);
  27288. ASSERT_NE(INVALID_SOCKET, sock);
  27289. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27290. auto send_request_and_read_response = [&](const std::string &req,
  27291. std::string &out) -> bool {
  27292. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27293. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27294. char buf[4096];
  27295. for (;;) {
  27296. auto n = recv(sock, buf, sizeof(buf), 0);
  27297. if (n <= 0) { return !out.empty(); }
  27298. out.append(buf, static_cast<size_t>(n));
  27299. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27300. }
  27301. };
  27302. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27303. "Host: localhost\r\n"
  27304. "\r\n";
  27305. std::string resp1;
  27306. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27307. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27308. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27309. "Host: localhost\r\n"
  27310. "Connection: close\r\n"
  27311. "\r\n";
  27312. std::string resp2;
  27313. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27314. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27315. EXPECT_EQ(2, delete_count.load());
  27316. }
  27317. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27318. Server svr;
  27319. svr.Post("/ingest", [&](const Request &, Response &res,
  27320. const ContentReader &content_reader) {
  27321. auto consumed = content_reader([](const char *, size_t) { return false; });
  27322. EXPECT_FALSE(consumed);
  27323. res.status = StatusCode::Conflict_409;
  27324. res.set_header("Connection", "close");
  27325. });
  27326. auto port = svr.bind_to_any_port(HOST);
  27327. thread t = thread([&] { svr.listen_after_bind(); });
  27328. auto se = detail::scope_exit([&] {
  27329. svr.stop();
  27330. t.join();
  27331. });
  27332. svr.wait_until_ready();
  27333. auto error = Error::Success;
  27334. auto sock = detail::create_client_socket(
  27335. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27336. /*connection_timeout_sec=*/2, 0,
  27337. /*read_timeout_sec=*/1, 0,
  27338. /*write_timeout_sec=*/2, 0, std::string(), error);
  27339. ASSERT_NE(INVALID_SOCKET, sock);
  27340. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27341. std::string request = "POST /ingest HTTP/1.1\r\n"
  27342. "Host: localhost\r\n"
  27343. "Transfer-Encoding: chunked\r\n"
  27344. "\r\n"
  27345. "4\r\n"
  27346. "data\r\n";
  27347. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27348. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27349. std::string response;
  27350. ssize_t received = 0;
  27351. do {
  27352. char buf[4096];
  27353. received = recv(sock, buf, sizeof(buf), 0);
  27354. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27355. } while (received > 0);
  27356. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27357. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27358. EXPECT_EQ(0, received);
  27359. }
  27360. namespace no_proxy_test {
  27361. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27362. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27363. // calling listen().
  27364. class ScopedServer {
  27365. public:
  27366. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27367. ~ScopedServer() {
  27368. svr_.stop();
  27369. if (th_.joinable()) { th_.join(); }
  27370. }
  27371. Server &svr() { return svr_; }
  27372. int port() const { return port_; }
  27373. void listen() {
  27374. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27375. svr_.wait_until_ready();
  27376. }
  27377. private:
  27378. Server svr_;
  27379. std::thread th_;
  27380. int port_ = 0;
  27381. };
  27382. class ProxyAndTargetServers {
  27383. public:
  27384. ProxyAndTargetServers() {
  27385. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27386. proxy_hits_++;
  27387. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27388. res.set_content("via-proxy", "text/plain");
  27389. });
  27390. target_.Get(".*", [this](const Request &req, Response &res) {
  27391. target_hits_++;
  27392. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27393. res.set_content("direct", "text/plain");
  27394. });
  27395. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27396. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27397. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27398. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27399. proxy_mock_.wait_until_ready();
  27400. target_.wait_until_ready();
  27401. }
  27402. ~ProxyAndTargetServers() {
  27403. proxy_mock_.stop();
  27404. target_.stop();
  27405. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27406. if (target_thread_.joinable()) { target_thread_.join(); }
  27407. }
  27408. Server &proxy_mock() { return proxy_mock_; }
  27409. Server &target() { return target_; }
  27410. int proxy_port() const { return proxy_port_; }
  27411. int target_port() const { return target_port_; }
  27412. int proxy_hits() const { return proxy_hits_.load(); }
  27413. int target_hits() const { return target_hits_.load(); }
  27414. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27415. void reset_counters() {
  27416. proxy_hits_ = 0;
  27417. target_hits_ = 0;
  27418. last_had_proxy_authz_ = false;
  27419. }
  27420. private:
  27421. Server proxy_mock_;
  27422. Server target_;
  27423. std::thread proxy_thread_;
  27424. std::thread target_thread_;
  27425. int proxy_port_ = 0;
  27426. int target_port_ = 0;
  27427. std::atomic<int> proxy_hits_{0};
  27428. std::atomic<int> target_hits_{0};
  27429. std::atomic<bool> last_had_proxy_authz_{false};
  27430. };
  27431. inline std::unique_ptr<Client> make_client(const std::string &host,
  27432. ProxyAndTargetServers &s) {
  27433. auto cli = detail::make_unique<Client>(host, s.target_port());
  27434. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27435. cli->set_proxy("127.0.0.1", s.proxy_port());
  27436. return cli;
  27437. }
  27438. } // namespace no_proxy_test
  27439. using no_proxy_test::make_client;
  27440. using no_proxy_test::ProxyAndTargetServers;
  27441. // A stream request carries the credentials a buffered request does
  27442. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27443. no_proxy_test::ScopedServer origin;
  27444. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27445. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27446. });
  27447. origin.listen();
  27448. Client cli("127.0.0.1", origin.port());
  27449. cli.set_basic_auth("user", "pass");
  27450. auto handle = cli.open_stream("GET", "/x");
  27451. ASSERT_TRUE(handle.is_valid());
  27452. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27453. Client bearer("127.0.0.1", origin.port());
  27454. bearer.set_bearer_token_auth("tok");
  27455. auto handle2 = bearer.open_stream("GET", "/x");
  27456. ASSERT_TRUE(handle2.is_valid());
  27457. EXPECT_EQ("Bearer tok", read_all(handle2));
  27458. }
  27459. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27460. // takes its own credentials, as for a buffered request
  27461. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27462. std::string target, authz, proxy_authz;
  27463. no_proxy_test::ScopedServer proxy;
  27464. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27465. target = req.target;
  27466. authz = req.get_header_value("Authorization");
  27467. proxy_authz = req.get_header_value("Proxy-Authorization");
  27468. res.set_content("ok", "text/plain");
  27469. });
  27470. proxy.listen();
  27471. Client cli("origin.example", 8080);
  27472. cli.set_proxy("127.0.0.1", proxy.port());
  27473. cli.set_proxy_basic_auth("puser", "ppass");
  27474. cli.set_basic_auth("user", "pass");
  27475. auto handle = cli.open_stream("GET", "/x");
  27476. ASSERT_TRUE(handle.is_valid());
  27477. EXPECT_EQ("ok", read_all(handle));
  27478. EXPECT_EQ("http://origin.example:8080/x", target);
  27479. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27480. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27481. }
  27482. // In absolute-form the path follows the authority, so a path that does not
  27483. // begin with '/' would make the proxy connect to another host
  27484. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27485. std::vector<std::string> targets;
  27486. no_proxy_test::ScopedServer proxy;
  27487. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27488. targets.push_back(req.target);
  27489. res.set_content("ok", "text/plain");
  27490. });
  27491. proxy.listen();
  27492. Client cli("origin.example", 8080);
  27493. cli.set_proxy("127.0.0.1", proxy.port());
  27494. cli.set_basic_auth("user", "pass");
  27495. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27496. auto res = cli.Get(path);
  27497. EXPECT_FALSE(res) << path;
  27498. auto handle = cli.open_stream("GET", path);
  27499. EXPECT_FALSE(handle.is_valid()) << path;
  27500. }
  27501. EXPECT_TRUE(targets.empty());
  27502. auto res = cli.Get("/x");
  27503. ASSERT_TRUE(res);
  27504. ASSERT_EQ(1u, targets.size());
  27505. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27506. }
  27507. TEST(NoProxyTest, ExactHostnameBypasses) {
  27508. ProxyAndTargetServers s;
  27509. auto cli = make_client("example.com", s);
  27510. cli->set_no_proxy({"example.com"});
  27511. auto res = cli->Get("/");
  27512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27513. EXPECT_EQ(0, s.proxy_hits());
  27514. EXPECT_EQ(1, s.target_hits());
  27515. }
  27516. TEST(NoProxyTest, SubdomainBypasses) {
  27517. ProxyAndTargetServers s;
  27518. auto cli = make_client("foo.example.com", s);
  27519. cli->set_no_proxy({"example.com"});
  27520. auto res = cli->Get("/");
  27521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27522. EXPECT_EQ(0, s.proxy_hits());
  27523. EXPECT_EQ(1, s.target_hits());
  27524. }
  27525. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27526. // Regression guard: "evilexample.com" must not be considered a subdomain
  27527. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27528. // check would let traffic bypass the proxy and leak credentials direct
  27529. // to the attacker host.
  27530. ProxyAndTargetServers s;
  27531. auto cli = make_client("evilexample.com", s);
  27532. cli->set_no_proxy({"example.com"});
  27533. auto res = cli->Get("/");
  27534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27535. EXPECT_GE(s.proxy_hits(), 1);
  27536. EXPECT_EQ(0, s.target_hits());
  27537. }
  27538. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27539. ProxyAndTargetServers s;
  27540. auto cli = make_client("example.com.evil.com", s);
  27541. cli->set_no_proxy({"example.com"});
  27542. auto res = cli->Get("/");
  27543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27544. EXPECT_GE(s.proxy_hits(), 1);
  27545. EXPECT_EQ(0, s.target_hits());
  27546. }
  27547. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27548. ProxyAndTargetServers s;
  27549. auto cli = make_client("example.com", s);
  27550. cli->set_no_proxy({".example.com"});
  27551. auto res = cli->Get("/");
  27552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27553. EXPECT_EQ(0, s.proxy_hits());
  27554. EXPECT_EQ(1, s.target_hits());
  27555. }
  27556. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27557. ProxyAndTargetServers s;
  27558. auto cli = make_client("Example.COM", s);
  27559. cli->set_no_proxy({"EXAMPLE.com"});
  27560. auto res = cli->Get("/");
  27561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27562. EXPECT_EQ(0, s.proxy_hits());
  27563. EXPECT_EQ(1, s.target_hits());
  27564. }
  27565. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27566. ProxyAndTargetServers s;
  27567. auto cli = make_client("example.com.", s);
  27568. cli->set_no_proxy({"example.com"});
  27569. auto res = cli->Get("/");
  27570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27571. EXPECT_EQ(0, s.proxy_hits());
  27572. EXPECT_EQ(1, s.target_hits());
  27573. }
  27574. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27575. // Trailing dots must be normalized on BOTH sides — host and entry.
  27576. // An implementation that only strips the host-side trailing dot would
  27577. // fail to match host "example.com" against entry "example.com." because
  27578. // a literal substring search would compare 11 chars against 12.
  27579. ProxyAndTargetServers s;
  27580. auto cli = make_client("example.com", s);
  27581. cli->set_no_proxy({"example.com."});
  27582. auto res = cli->Get("/");
  27583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27584. EXPECT_EQ(0, s.proxy_hits());
  27585. EXPECT_EQ(1, s.target_hits());
  27586. }
  27587. TEST(NoProxyTest, WildcardBypassesEverything) {
  27588. ProxyAndTargetServers s;
  27589. auto cli = make_client("anything.invalid.test", s);
  27590. cli->set_no_proxy({"*"});
  27591. auto res = cli->Get("/");
  27592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27593. EXPECT_EQ(0, s.proxy_hits());
  27594. EXPECT_EQ(1, s.target_hits());
  27595. }
  27596. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27597. ProxyAndTargetServers s;
  27598. Client cli("127.0.0.1", s.target_port());
  27599. cli.set_proxy("127.0.0.1", s.proxy_port());
  27600. cli.set_no_proxy({"127.0.0.1"});
  27601. auto res = cli.Get("/");
  27602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27603. EXPECT_EQ(0, s.proxy_hits());
  27604. EXPECT_EQ(1, s.target_hits());
  27605. }
  27606. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27607. ProxyAndTargetServers s;
  27608. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27609. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27610. cli.set_proxy("127.0.0.1", s.proxy_port());
  27611. cli.set_no_proxy({"::1"});
  27612. auto res = cli.Get("/");
  27613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27614. EXPECT_EQ(0, s.proxy_hits());
  27615. EXPECT_EQ(1, s.target_hits());
  27616. }
  27617. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27618. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27619. // must still be recognized as IPv6 for CIDR matching. Implementations
  27620. // that detect IPv6 only when the host begins with '[' would parse the
  27621. // host as a hostname and miss the match.
  27622. ProxyAndTargetServers s;
  27623. Client cli("fe80::1", s.target_port());
  27624. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27625. cli.set_proxy("127.0.0.1", s.proxy_port());
  27626. cli.set_no_proxy({"fe80::/10"});
  27627. auto res = cli.Get("/");
  27628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27629. EXPECT_EQ(0, s.proxy_hits());
  27630. EXPECT_EQ(1, s.target_hits());
  27631. }
  27632. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27633. ProxyAndTargetServers s;
  27634. Client cli("::1", s.target_port());
  27635. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27636. cli.set_proxy("127.0.0.1", s.proxy_port());
  27637. cli.set_no_proxy({"[::1]"});
  27638. auto res = cli.Get("/");
  27639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27640. EXPECT_EQ(0, s.proxy_hits());
  27641. EXPECT_EQ(1, s.target_hits());
  27642. }
  27643. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27644. ProxyAndTargetServers s;
  27645. Client cli("fe80::1", s.target_port());
  27646. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27647. cli.set_proxy("127.0.0.1", s.proxy_port());
  27648. cli.set_no_proxy({"[fe80::]/10"});
  27649. auto res = cli.Get("/");
  27650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27651. EXPECT_EQ(0, s.proxy_hits());
  27652. EXPECT_EQ(1, s.target_hits());
  27653. }
  27654. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27655. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27656. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27657. // tricks via address-family conversion.
  27658. ProxyAndTargetServers s;
  27659. Client cli("::ffff:127.0.0.1", s.target_port());
  27660. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27661. cli.set_proxy("127.0.0.1", s.proxy_port());
  27662. cli.set_no_proxy({"127.0.0.1"});
  27663. auto res = cli.Get("/");
  27664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27665. EXPECT_GE(s.proxy_hits(), 1);
  27666. EXPECT_EQ(0, s.target_hits());
  27667. }
  27668. TEST(NoProxyTest, IPv4CidrMatch) {
  27669. ProxyAndTargetServers s;
  27670. Client cli("127.0.0.1", s.target_port());
  27671. cli.set_proxy("127.0.0.1", s.proxy_port());
  27672. cli.set_no_proxy({"127.0.0.0/8"});
  27673. auto res = cli.Get("/");
  27674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27675. EXPECT_EQ(0, s.proxy_hits());
  27676. EXPECT_EQ(1, s.target_hits());
  27677. }
  27678. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27679. ProxyAndTargetServers s;
  27680. Client cli("127.0.0.1", s.target_port());
  27681. cli.set_proxy("127.0.0.1", s.proxy_port());
  27682. cli.set_no_proxy({"10.0.0.0/8"});
  27683. auto res = cli.Get("/");
  27684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27685. EXPECT_GE(s.proxy_hits(), 1);
  27686. EXPECT_EQ(0, s.target_hits());
  27687. }
  27688. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27689. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27690. // IPv4 target matches.
  27691. ProxyAndTargetServers s;
  27692. Client cli("127.0.0.1", s.target_port());
  27693. cli.set_proxy("127.0.0.1", s.proxy_port());
  27694. cli.set_no_proxy({"0.0.0.0/0"});
  27695. auto res = cli.Get("/");
  27696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27697. EXPECT_EQ(0, s.proxy_hits());
  27698. EXPECT_EQ(1, s.target_hits());
  27699. }
  27700. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27701. ProxyAndTargetServers s;
  27702. Client cli("127.0.0.1", s.target_port());
  27703. cli.set_proxy("127.0.0.1", s.proxy_port());
  27704. cli.set_no_proxy({"127.0.0.1"});
  27705. auto res = cli.Get("/");
  27706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27707. EXPECT_EQ(0, s.proxy_hits());
  27708. EXPECT_EQ(1, s.target_hits());
  27709. }
  27710. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27711. ProxyAndTargetServers s;
  27712. Client cli("127.0.0.1", s.target_port());
  27713. cli.set_proxy("127.0.0.1", s.proxy_port());
  27714. cli.set_no_proxy({"127.0.0.0/33"});
  27715. auto res = cli.Get("/");
  27716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27717. EXPECT_GE(s.proxy_hits(), 1);
  27718. EXPECT_EQ(0, s.target_hits());
  27719. }
  27720. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27721. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27722. ProxyAndTargetServers s;
  27723. Client cli("127.0.0.1", s.target_port());
  27724. cli.set_proxy("127.0.0.1", s.proxy_port());
  27725. cli.set_no_proxy({"127.0.0.1/"});
  27726. auto res = cli.Get("/");
  27727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27728. EXPECT_GE(s.proxy_hits(), 1);
  27729. EXPECT_EQ(0, s.target_hits());
  27730. }
  27731. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27732. ProxyAndTargetServers s;
  27733. auto cli = make_client("internal.corp", s);
  27734. cli->set_proxy_basic_auth("u", "p");
  27735. cli->set_no_proxy({"internal.corp"});
  27736. auto res = cli->Get("/");
  27737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27738. EXPECT_EQ(1, s.target_hits());
  27739. EXPECT_EQ(0, s.proxy_hits());
  27740. EXPECT_FALSE(s.last_had_proxy_authz())
  27741. << "Proxy-Authorization must not be sent direct to the target";
  27742. }
  27743. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27744. ProxyAndTargetServers s;
  27745. auto cli = make_client("public.example", s);
  27746. cli->set_proxy_basic_auth("u", "p");
  27747. cli->set_no_proxy({"internal.corp"}); // does not match
  27748. auto res = cli->Get("/");
  27749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27750. EXPECT_GE(s.proxy_hits(), 1);
  27751. EXPECT_TRUE(s.last_had_proxy_authz());
  27752. }
  27753. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27754. std::atomic<int> hits{0};
  27755. std::atomic<int> hits_with_authz{0};
  27756. no_proxy_test::ScopedServer proxy_mock;
  27757. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27758. hits++;
  27759. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27760. if (req.target.find("/redir") != std::string::npos) {
  27761. res.set_redirect("http://other.example/landed");
  27762. } else {
  27763. res.set_content("via-proxy", "text/plain");
  27764. }
  27765. });
  27766. proxy_mock.listen();
  27767. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27768. hits = 0;
  27769. hits_with_authz = 0;
  27770. Client cli("public.example", 80);
  27771. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27772. cli.set_proxy_basic_auth(c.first, c.second);
  27773. cli.set_follow_location(true);
  27774. // The redirect to another host goes through the proxy as well
  27775. auto res = cli.Get("/redir");
  27776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27777. EXPECT_EQ(2, hits.load());
  27778. EXPECT_EQ(2, hits_with_authz.load());
  27779. }
  27780. }
  27781. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27782. ProxyAndTargetServers s;
  27783. auto cli = make_client("anything.test", s);
  27784. auto res = cli->Get("/");
  27785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27786. EXPECT_GE(s.proxy_hits(), 1);
  27787. EXPECT_EQ(0, s.target_hits());
  27788. }
  27789. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27790. ProxyAndTargetServers s;
  27791. auto cli = make_client("example.com", s);
  27792. cli->set_no_proxy({"example.com:8080"});
  27793. auto res = cli->Get("/");
  27794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27795. EXPECT_GE(s.proxy_hits(), 1);
  27796. EXPECT_EQ(0, s.target_hits());
  27797. }
  27798. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27799. ProxyAndTargetServers s;
  27800. auto cli = make_client("anything.test", s);
  27801. cli->set_no_proxy({"", " ", "\t"});
  27802. auto res = cli->Get("/");
  27803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27804. EXPECT_GE(s.proxy_hits(), 1);
  27805. EXPECT_EQ(0, s.target_hits());
  27806. }
  27807. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27808. // An entry with leading/trailing whitespace must still match — env-style
  27809. // values are commonly pasted with stray spaces and an implementation
  27810. // that feeds the raw token directly to inet_pton would fail to match
  27811. // valid CIDRs because of the spaces.
  27812. ProxyAndTargetServers s;
  27813. Client cli("127.0.0.1", s.target_port());
  27814. cli.set_proxy("127.0.0.1", s.proxy_port());
  27815. cli.set_no_proxy({" 127.0.0.0/8 "});
  27816. auto res = cli.Get("/");
  27817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27818. EXPECT_EQ(0, s.proxy_hits());
  27819. EXPECT_EQ(1, s.target_hits());
  27820. }
  27821. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27822. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27823. // go direct and must NOT carry Proxy-Authorization.
  27824. std::atomic<int> proxy_hits{0};
  27825. std::atomic<int> target_hits{0};
  27826. std::atomic<bool> target_saw_authz{false};
  27827. no_proxy_test::ScopedServer proxy_mock, target;
  27828. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27829. proxy_hits++;
  27830. res.status = 302;
  27831. res.set_header("Location", "http://127.0.0.1:" +
  27832. std::to_string(target.port()) + "/landed");
  27833. });
  27834. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27835. target_hits++;
  27836. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27837. res.set_content("direct", "text/plain");
  27838. });
  27839. proxy_mock.listen();
  27840. target.listen();
  27841. Client cli("public.example", target.port());
  27842. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27843. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27844. cli.set_proxy_basic_auth("u", "p");
  27845. cli.set_no_proxy({"127.0.0.1"});
  27846. cli.set_follow_location(true);
  27847. auto res = cli.Get("/redir");
  27848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27849. EXPECT_GE(proxy_hits.load(), 1);
  27850. EXPECT_GE(target_hits.load(), 1);
  27851. EXPECT_FALSE(target_saw_authz.load());
  27852. }
  27853. #ifdef CPPHTTPLIB_SSL_ENABLED
  27854. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27855. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27856. // proxy creds would be sent to the (possibly hostile) origin.
  27857. std::atomic<int> target_hits{0};
  27858. std::atomic<bool> target_saw_proxy_authz{false};
  27859. no_proxy_test::ScopedServer target;
  27860. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27861. target_hits++;
  27862. if (req.has_header("Proxy-Authorization")) {
  27863. target_saw_proxy_authz = true;
  27864. }
  27865. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27866. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27867. "nonce=\"abc\", algorithm=MD5");
  27868. });
  27869. target.listen();
  27870. // The proxy address is set to the target's port: the bypass MUST kick in;
  27871. // if it doesn't, the test still routes "via proxy" to the same server and
  27872. // the Proxy-Authorization assertion below catches the leak.
  27873. Client cli("evil.example", target.port());
  27874. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27875. cli.set_proxy("127.0.0.1", target.port());
  27876. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27877. cli.set_no_proxy({"evil.example"});
  27878. auto res = cli.Get("/x");
  27879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27880. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27881. EXPECT_EQ(1, target_hits.load());
  27882. EXPECT_FALSE(target_saw_proxy_authz.load());
  27883. }
  27884. #endif
  27885. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27886. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27887. std::atomic<int> proxy_hits{0};
  27888. std::atomic<int> bypass_hits{0};
  27889. std::atomic<bool> proxy_saw_c_url{false};
  27890. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27891. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27892. proxy_hits++;
  27893. if (req.path.find("/start") != std::string::npos) {
  27894. res.status = 302;
  27895. res.set_header("Location", "http://127.0.0.1:" +
  27896. std::to_string(bypass_server.port()) +
  27897. "/middle");
  27898. return;
  27899. }
  27900. if (req.path.find("/end") != std::string::npos) {
  27901. proxy_saw_c_url = true;
  27902. res.set_content("c-via-proxy", "text/plain");
  27903. return;
  27904. }
  27905. res.set_content("unexpected", "text/plain");
  27906. });
  27907. // public.example's "advertised" port is arbitrary (the request never lands
  27908. // there — it goes through the proxy), but use a dynamic value to stay
  27909. // friendly with sharded parallel runs.
  27910. int public_port = bypass_server.port();
  27911. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27912. bypass_hits++;
  27913. res.status = 302;
  27914. res.set_header("Location", "http://public.example:" +
  27915. std::to_string(public_port) + "/end");
  27916. });
  27917. proxy_mock.listen();
  27918. bypass_server.listen();
  27919. Client cli("public.example", public_port);
  27920. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27921. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27922. cli.set_no_proxy({"127.0.0.1"});
  27923. cli.set_follow_location(true);
  27924. auto res = cli.Get("/start");
  27925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27926. EXPECT_EQ(StatusCode::OK_200, res->status);
  27927. EXPECT_EQ("c-via-proxy", res->body);
  27928. EXPECT_GE(proxy_hits.load(), 2);
  27929. EXPECT_GE(bypass_hits.load(), 1);
  27930. EXPECT_TRUE(proxy_saw_c_url.load());
  27931. }
  27932. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27933. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27934. // request reconnects to the correct endpoint.
  27935. std::atomic<int> proxy_hits{0};
  27936. std::atomic<int> target_hits{0};
  27937. no_proxy_test::ScopedServer proxy_mock, target;
  27938. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27939. proxy_hits++;
  27940. res.set_content("via-proxy", "text/plain");
  27941. });
  27942. target.svr().Get(".*", [&](const Request &, Response &res) {
  27943. target_hits++;
  27944. res.set_content("direct", "text/plain");
  27945. });
  27946. proxy_mock.listen();
  27947. target.listen();
  27948. Client cli("public.example", target.port());
  27949. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27950. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27951. cli.set_keep_alive(true);
  27952. auto res1 = cli.Get("/a");
  27953. ASSERT_TRUE(res1);
  27954. EXPECT_EQ("via-proxy", res1->body);
  27955. EXPECT_EQ(1, proxy_hits.load());
  27956. EXPECT_EQ(0, target_hits.load());
  27957. cli.set_no_proxy({"public.example"});
  27958. auto res2 = cli.Get("/b");
  27959. ASSERT_TRUE(res2);
  27960. EXPECT_EQ("direct", res2->body);
  27961. EXPECT_EQ(1, proxy_hits.load());
  27962. EXPECT_EQ(1, target_hits.load());
  27963. }
  27964. // Forward declarations (see the base64_encode note).
  27965. namespace httplib {
  27966. namespace detail {
  27967. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27968. int shutdown_socket(socket_t sock) noexcept;
  27969. } // namespace detail
  27970. } // namespace httplib
  27971. namespace proxy_tunnel_test {
  27972. const char *const kTunnelEstablished =
  27973. "HTTP/1.1 200 Connection established\r\n\r\n";
  27974. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27975. using ConnectReply = std::function<std::string(const std::string &head)>;
  27976. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27977. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27978. class ScopedConnectProxy {
  27979. public:
  27980. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27981. : forward_port_(forward_port), reply_(std::move(reply)) {
  27982. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27983. if (listen_sock_ == INVALID_SOCKET) { return; }
  27984. auto a = loopback(0);
  27985. auto addr = reinterpret_cast<sockaddr *>(&a);
  27986. socklen_t alen = sizeof(a);
  27987. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27988. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27989. ::listen(listen_sock_, 4) != 0) {
  27990. return;
  27991. }
  27992. port_ = ntohs(a.sin_port);
  27993. th_ = std::thread([this] { run(); });
  27994. }
  27995. ~ScopedConnectProxy() {
  27996. if (th_.joinable()) {
  27997. stop_ = true;
  27998. auto wake = connect_to(port_);
  27999. th_.join();
  28000. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28001. }
  28002. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28003. }
  28004. int port() const { return port_; }
  28005. int connect_hits() const { return connect_hits_.load(); }
  28006. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28007. std::string connect_request() const {
  28008. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28009. return connect_request_;
  28010. }
  28011. private:
  28012. static sockaddr_in loopback(int port) {
  28013. sockaddr_in a{};
  28014. a.sin_family = AF_INET;
  28015. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28016. a.sin_port = htons(static_cast<unsigned short>(port));
  28017. return a;
  28018. }
  28019. static socket_t connect_to(int port) {
  28020. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28021. if (sock == INVALID_SOCKET) { return sock; }
  28022. auto a = loopback(port);
  28023. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28024. detail::close_socket(sock);
  28025. return INVALID_SOCKET;
  28026. }
  28027. return sock;
  28028. }
  28029. static bool send_all(socket_t sock, const char *data, size_t size) {
  28030. while (size > 0) {
  28031. auto n = detail::send_socket(sock, data, size, 0);
  28032. if (n <= 0) { return false; }
  28033. data += n;
  28034. size -= static_cast<size_t>(n);
  28035. }
  28036. return true;
  28037. }
  28038. void run() {
  28039. for (;;) {
  28040. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28041. if (stop_) {
  28042. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28043. return;
  28044. }
  28045. if (client == INVALID_SOCKET) { continue; }
  28046. serve(client);
  28047. detail::close_socket(client);
  28048. }
  28049. }
  28050. void serve(socket_t client) {
  28051. std::string head;
  28052. char buf[2048];
  28053. while (head.find("\r\n\r\n") == std::string::npos) {
  28054. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28055. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28056. if (n <= 0) { return; }
  28057. head.append(buf, static_cast<size_t>(n));
  28058. }
  28059. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28060. connect_hits_++;
  28061. {
  28062. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28063. connect_request_ = head;
  28064. }
  28065. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28066. if (!send_all(client, res.data(), res.size()) ||
  28067. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28068. return;
  28069. }
  28070. auto origin = connect_to(forward_port_);
  28071. if (origin == INVALID_SOCKET) { return; }
  28072. // When either side stops, shut both down so the other pump returns too.
  28073. auto pump = [&](socket_t from, socket_t to) {
  28074. char b[8192];
  28075. for (;;) {
  28076. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28077. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28078. }
  28079. detail::shutdown_socket(client);
  28080. detail::shutdown_socket(origin);
  28081. };
  28082. std::thread up([&] { pump(client, origin); });
  28083. pump(origin, client);
  28084. up.join();
  28085. detail::close_socket(origin);
  28086. }
  28087. int forward_port_;
  28088. ConnectReply reply_;
  28089. socket_t listen_sock_ = INVALID_SOCKET;
  28090. int port_ = 0;
  28091. std::thread th_;
  28092. std::atomic<bool> stop_{false};
  28093. std::atomic<int> connect_hits_{0};
  28094. mutable std::mutex connect_request_mutex_;
  28095. std::string connect_request_;
  28096. };
  28097. } // namespace proxy_tunnel_test
  28098. #ifdef CPPHTTPLIB_SSL_ENABLED
  28099. namespace proxy_tunnel_test {
  28100. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28101. class ScopedSSLServer {
  28102. public:
  28103. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28104. port_ = svr_.bind_to_any_port("127.0.0.1");
  28105. }
  28106. ~ScopedSSLServer() {
  28107. svr_.stop();
  28108. if (th_.joinable()) { th_.join(); }
  28109. }
  28110. SSLServer &svr() { return svr_; }
  28111. int port() const { return port_; }
  28112. void listen() {
  28113. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28114. svr_.wait_until_ready();
  28115. }
  28116. private:
  28117. SSLServer svr_;
  28118. std::thread th_;
  28119. int port_ = 0;
  28120. };
  28121. // Sends one request through the CONNECT proxy to the TLS origin with a
  28122. // credential configured for each hop, and checks that each credential reaches
  28123. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28124. // origin's (every header in origin_headers) on the tunnelled request.
  28125. void CredentialsStayWithTheirHop(
  28126. const std::function<void(SSLClient &)> &set_credentials,
  28127. const std::string &scheme,
  28128. const std::vector<std::string> &origin_headers = {"Authorization"},
  28129. bool stream = false) {
  28130. std::atomic<int> origin_hits{0};
  28131. std::atomic<bool> origin_saw_proxy_authz{false};
  28132. std::atomic<bool> origin_saw_headers{false};
  28133. ScopedSSLServer origin;
  28134. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28135. origin_hits++;
  28136. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28137. origin_saw_headers =
  28138. std::all_of(origin_headers.begin(), origin_headers.end(),
  28139. [&](const std::string &h) { return req.has_header(h); });
  28140. res.set_content("ok", "text/plain");
  28141. });
  28142. origin.listen();
  28143. ScopedConnectProxy proxy(origin.port());
  28144. ASSERT_NE(0, proxy.port());
  28145. // Pinned to 127.0.0.1 for the same reason as the test below.
  28146. SSLClient cli("127.0.0.1", origin.port());
  28147. cli.enable_server_certificate_verification(false);
  28148. cli.set_proxy("127.0.0.1", proxy.port());
  28149. set_credentials(cli);
  28150. if (stream) {
  28151. auto handle = cli.open_stream("GET", "/x");
  28152. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28153. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28154. } else {
  28155. auto res = cli.Get("/x");
  28156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28157. EXPECT_EQ(StatusCode::OK_200, res->status);
  28158. }
  28159. EXPECT_EQ(1, origin_hits.load());
  28160. EXPECT_EQ(1, proxy.connect_hits());
  28161. EXPECT_TRUE(origin_saw_headers.load());
  28162. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28163. << "Proxy-Authorization must not be sent inside the tunnel";
  28164. auto connect_req = proxy.connect_request();
  28165. EXPECT_NE(std::string::npos,
  28166. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28167. for (const auto &h : origin_headers) {
  28168. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28169. << h << " must not be sent to the proxy on CONNECT";
  28170. }
  28171. }
  28172. } // namespace proxy_tunnel_test
  28173. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28174. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28175. [](SSLClient &cli) {
  28176. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28177. cli.set_basic_auth("origin-user", "origin-pass");
  28178. },
  28179. "Basic");
  28180. }
  28181. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28182. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28183. [](SSLClient &cli) {
  28184. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28185. cli.set_basic_auth("origin-user", "origin-pass");
  28186. },
  28187. "Basic", {"Authorization"}, true);
  28188. }
  28189. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28190. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28191. [](SSLClient &cli) {
  28192. cli.set_proxy_bearer_token_auth("proxy-token");
  28193. cli.set_bearer_token_auth("origin-token");
  28194. },
  28195. "Bearer");
  28196. }
  28197. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28198. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28199. [](SSLClient &cli) {
  28200. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28201. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28202. {"Cookie", "sid=origin-session"},
  28203. {"X-Api-Key", "origin-key"}});
  28204. },
  28205. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28206. }
  28207. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28208. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28209. // retry; otherwise proxy creds would be sent to the origin.
  28210. std::atomic<int> origin_hits{0};
  28211. std::atomic<bool> origin_saw_proxy_authz{false};
  28212. proxy_tunnel_test::ScopedSSLServer origin;
  28213. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28214. origin_hits++;
  28215. if (req.has_header("Proxy-Authorization")) {
  28216. origin_saw_proxy_authz = true;
  28217. }
  28218. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28219. res.set_header("Proxy-Authenticate",
  28220. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28221. "algorithm=MD5");
  28222. });
  28223. origin.listen();
  28224. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28225. ASSERT_NE(0, proxy.port());
  28226. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28227. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28228. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28229. // and answer with its own status, making this test flaky.
  28230. SSLClient cli("127.0.0.1", origin.port());
  28231. cli.enable_server_certificate_verification(false);
  28232. cli.set_proxy("127.0.0.1", proxy.port());
  28233. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28234. auto res = cli.Get("/x");
  28235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28236. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28237. EXPECT_EQ(1, origin_hits.load());
  28238. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28239. EXPECT_EQ(1, proxy.connect_hits());
  28240. }
  28241. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28242. std::string origin_sni;
  28243. std::string origin_host;
  28244. proxy_tunnel_test::ScopedSSLServer origin;
  28245. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28246. origin_sni = req.sni();
  28247. origin_host = req.get_header_value("Host");
  28248. res.set_content("ok", "text/plain");
  28249. });
  28250. origin.listen();
  28251. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28252. ASSERT_NE(0, proxy.port());
  28253. SSLClient cli("origin.example", origin.port());
  28254. cli.enable_server_certificate_verification(false);
  28255. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28256. cli.set_proxy("127.0.0.1", proxy.port());
  28257. auto res = cli.Get("/x");
  28258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28259. EXPECT_EQ(StatusCode::OK_200, res->status);
  28260. auto port = std::to_string(origin.port());
  28261. auto target = "127.0.0.1:" + port;
  28262. auto connect_req = proxy.connect_request();
  28263. EXPECT_EQ(1, proxy.connect_hits());
  28264. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28265. EXPECT_NE(std::string::npos,
  28266. connect_req.find("\r\nHost: " + target + "\r\n"));
  28267. EXPECT_EQ("origin.example", origin_sni);
  28268. EXPECT_EQ("origin.example:" + port, origin_host);
  28269. }
  28270. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28271. proxy_tunnel_test::ScopedSSLServer origin;
  28272. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28273. res.set_content("ok", "text/plain");
  28274. });
  28275. origin.listen();
  28276. proxy_tunnel_test::ScopedConnectProxy proxy(
  28277. origin.port(), [](const std::string &head) -> std::string {
  28278. if (head.find(
  28279. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28280. std::string::npos) {
  28281. return proxy_tunnel_test::kTunnelEstablished;
  28282. }
  28283. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28284. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28285. "nonce=\"abc\", algorithm=MD5\r\n"
  28286. "Content-Length: 0\r\n\r\n";
  28287. });
  28288. ASSERT_NE(0, proxy.port());
  28289. SSLClient cli("origin.example", origin.port());
  28290. cli.enable_server_certificate_verification(false);
  28291. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28292. cli.set_proxy("127.0.0.1", proxy.port());
  28293. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28294. auto res = cli.Get("/x");
  28295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28296. EXPECT_EQ(StatusCode::OK_200, res->status);
  28297. // The retried CONNECT is the one the proxy saw last.
  28298. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28299. auto connect_req = proxy.connect_request();
  28300. EXPECT_EQ(2, proxy.connect_hits());
  28301. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28302. EXPECT_NE(std::string::npos,
  28303. connect_req.find("\r\nHost: " + target + "\r\n"));
  28304. }
  28305. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28306. proxy_tunnel_test::ScopedSSLServer origin;
  28307. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28308. res.set_content("ok", "text/plain");
  28309. });
  28310. origin.listen();
  28311. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28312. ASSERT_NE(0, proxy.port());
  28313. SSLClient cli("origin.example", origin.port());
  28314. cli.enable_server_certificate_verification(false);
  28315. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28316. cli.set_proxy("127.0.0.1", proxy.port());
  28317. auto res = cli.Get("/x");
  28318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28319. EXPECT_EQ(StatusCode::OK_200, res->status);
  28320. auto target = "origin.example:" + std::to_string(origin.port());
  28321. auto connect_req = proxy.connect_request();
  28322. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28323. EXPECT_NE(std::string::npos,
  28324. connect_req.find("\r\nHost: " + target + "\r\n"));
  28325. }
  28326. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28327. proxy_tunnel_test::ScopedSSLServer origin;
  28328. auto port = std::to_string(origin.port());
  28329. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28330. res.set_redirect("https://next.example:" + port + "/y");
  28331. });
  28332. origin.svr().Get("/y", [](const Request &, Response &res) {
  28333. res.set_content("ok", "text/plain");
  28334. });
  28335. origin.listen();
  28336. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28337. ASSERT_NE(0, proxy.port());
  28338. SSLClient cli("origin.example", origin.port());
  28339. cli.enable_server_certificate_verification(false);
  28340. cli.set_tunnel_hostname_addr_map(
  28341. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28342. cli.set_proxy("127.0.0.1", proxy.port());
  28343. cli.set_follow_location(true);
  28344. auto res = cli.Get("/x");
  28345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28346. EXPECT_EQ("ok", res->body);
  28347. // The last CONNECT is the redirect client's.
  28348. ASSERT_EQ(2, proxy.connect_hits());
  28349. auto target = "127.0.0.1:" + port;
  28350. auto connect_req = proxy.connect_request();
  28351. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28352. EXPECT_NE(std::string::npos,
  28353. connect_req.find("\r\nHost: " + target + "\r\n"));
  28354. }
  28355. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28356. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28357. std::atomic<int> origin_hits{0};
  28358. proxy_tunnel_test::ScopedSSLServer origin;
  28359. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28360. origin_hits++;
  28361. res.set_content("ok", "text/plain");
  28362. });
  28363. origin.listen();
  28364. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28365. ASSERT_NE(0, proxy.port());
  28366. SSLClient cli("127.0.0.1", origin.port());
  28367. cli.enable_server_certificate_verification(false);
  28368. cli.set_proxy("127.0.0.1", proxy.port());
  28369. cli.set_keep_alive(true);
  28370. cli.set_session_verifier(
  28371. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28372. auto res = cli.Get("/x");
  28373. EXPECT_FALSE(res);
  28374. ASSERT_FALSE(cli.is_socket_open());
  28375. res = cli.Get("/x");
  28376. EXPECT_FALSE(res);
  28377. EXPECT_EQ(2, proxy.connect_hits());
  28378. auto handle = cli.open_stream("GET", "/x");
  28379. EXPECT_FALSE(handle.is_valid());
  28380. EXPECT_EQ(3, proxy.connect_hits());
  28381. EXPECT_EQ(0, origin_hits.load());
  28382. }
  28383. #endif
  28384. namespace proxy_tunnel_test {
  28385. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28386. // anything else gets a 407 with `challenge`.
  28387. ConnectReply require_proxy_auth(const std::string &expected,
  28388. const std::string &challenge) {
  28389. return [=](const std::string &head) -> std::string {
  28390. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28391. std::string::npos) {
  28392. return kTunnelEstablished;
  28393. }
  28394. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28395. "Proxy-Authenticate: " +
  28396. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28397. };
  28398. }
  28399. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28400. // request, then echoes.
  28401. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28402. ws.send(
  28403. "authorization:" + req.get_header_value("Authorization") +
  28404. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28405. std::string msg;
  28406. while (ws.read(msg)) {
  28407. ws.send(msg);
  28408. }
  28409. }
  28410. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28411. class ScopedWebSocketOrigin {
  28412. public:
  28413. ScopedWebSocketOrigin() {
  28414. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28415. server_.listen();
  28416. }
  28417. int port() const { return server_.port(); }
  28418. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28419. std::string url() const {
  28420. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28421. }
  28422. private:
  28423. no_proxy_test::ScopedServer server_;
  28424. };
  28425. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28426. // passed as a constructor header, and checks that each reaches only its hop.
  28427. void WebSocketCredentialsStayWithTheirHop(
  28428. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28429. const std::string &proxy_authz, const std::string &origin_authz) {
  28430. ScopedWebSocketOrigin origin;
  28431. ScopedConnectProxy proxy(
  28432. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28433. ASSERT_NE(0, proxy.port());
  28434. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28435. client.set_proxy("127.0.0.1", proxy.port());
  28436. set_proxy_credentials(client);
  28437. auto res = client.connect();
  28438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28439. std::string msg;
  28440. ASSERT_TRUE(client.read(msg));
  28441. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28442. client.close();
  28443. EXPECT_EQ(1, proxy.connect_hits());
  28444. EXPECT_EQ(std::string::npos,
  28445. proxy.connect_request().find("\r\nAuthorization: "))
  28446. << "origin credentials must not be sent to the proxy";
  28447. }
  28448. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28449. void WebSocketSetterCredentialsStayWithTheirHop(
  28450. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28451. const std::string &proxy_authz, const std::string &origin_authz) {
  28452. ScopedWebSocketOrigin origin;
  28453. ScopedConnectProxy proxy(
  28454. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28455. ASSERT_NE(0, proxy.port());
  28456. ws::WebSocketClient client(origin.url());
  28457. client.set_proxy("127.0.0.1", proxy.port());
  28458. set_credentials(client);
  28459. auto res = client.connect();
  28460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28461. std::string msg;
  28462. ASSERT_TRUE(client.read(msg));
  28463. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28464. client.close();
  28465. EXPECT_EQ(1, proxy.connect_hits());
  28466. EXPECT_EQ(std::string::npos,
  28467. proxy.connect_request().find("\r\nAuthorization: "))
  28468. << "origin credentials must not be sent to the proxy";
  28469. }
  28470. } // namespace proxy_tunnel_test
  28471. namespace {
  28472. // Connects `client` and returns the Authorization header its upgrade
  28473. // request carried, or "<failed>" when the connection could not be opened.
  28474. std::string websocket_authorization(ws::WebSocketClient &client) {
  28475. if (!client.connect()) { return "<failed>"; }
  28476. std::string msg;
  28477. if (!client.read(msg)) { return "<failed>"; }
  28478. client.close();
  28479. auto prefix = std::string("authorization:");
  28480. auto end = msg.find("|proxy-authorization:");
  28481. return msg.substr(prefix.size(), end - prefix.size());
  28482. }
  28483. } // namespace
  28484. TEST(WebSocketClientAuthTest, BasicAuth) {
  28485. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28486. ws::WebSocketClient client(origin.url());
  28487. client.set_basic_auth("user", "pass");
  28488. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28489. websocket_authorization(client));
  28490. }
  28491. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28492. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28493. ws::WebSocketClient client(origin.url());
  28494. client.set_basic_auth("user", "");
  28495. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28496. websocket_authorization(client));
  28497. }
  28498. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28499. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28500. ws::WebSocketClient client(origin.url());
  28501. client.set_bearer_token_auth("token123");
  28502. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28503. }
  28504. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28505. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28506. ws::WebSocketClient client(origin.url());
  28507. client.set_bearer_token_auth("token123");
  28508. client.set_basic_auth("user", "pass");
  28509. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28510. websocket_authorization(client));
  28511. }
  28512. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28513. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28514. ws::WebSocketClient client(origin.url(),
  28515. {{"Authorization", "Bearer from-header"}});
  28516. client.set_bearer_token_auth("from-setter");
  28517. client.set_basic_auth("user", "pass");
  28518. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28519. }
  28520. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28521. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28522. ws::WebSocketClient client(origin.url());
  28523. EXPECT_EQ("", websocket_authorization(client));
  28524. client.set_bearer_token_auth("first");
  28525. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28526. client.set_bearer_token_auth("second");
  28527. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28528. client.set_bearer_token_auth("");
  28529. EXPECT_EQ("", websocket_authorization(client));
  28530. }
  28531. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28532. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28533. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28534. ASSERT_NE(0, proxy.port());
  28535. ws::WebSocketClient client(origin.url());
  28536. client.set_proxy("127.0.0.1", proxy.port());
  28537. auto res = client.connect();
  28538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28539. std::string msg;
  28540. ASSERT_TRUE(client.read(msg));
  28541. ASSERT_TRUE(client.send("hello"));
  28542. ASSERT_TRUE(client.read(msg));
  28543. EXPECT_EQ("hello", msg);
  28544. client.close();
  28545. EXPECT_EQ(1, proxy.connect_hits());
  28546. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28547. auto connect_req = proxy.connect_request();
  28548. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28549. EXPECT_NE(std::string::npos,
  28550. connect_req.find("\r\nHost: " + target + "\r\n"));
  28551. }
  28552. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28553. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28554. [](ws::WebSocketClient &cli) {
  28555. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28556. },
  28557. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28558. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28559. }
  28560. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28561. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28562. [](ws::WebSocketClient &cli) {
  28563. cli.set_proxy_bearer_token_auth("proxy-token");
  28564. },
  28565. "Bearer proxy-token", "Bearer origin-token");
  28566. }
  28567. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28568. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28569. [](ws::WebSocketClient &cli) {
  28570. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28571. cli.set_basic_auth("origin-user", "origin-pass");
  28572. },
  28573. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28574. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28575. }
  28576. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28577. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28578. [](ws::WebSocketClient &cli) {
  28579. cli.set_proxy_bearer_token_auth("proxy-token");
  28580. cli.set_bearer_token_auth("origin-token");
  28581. },
  28582. "Bearer proxy-token", "Bearer origin-token");
  28583. }
  28584. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28585. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28586. proxy_tunnel_test::ScopedConnectProxy proxy(
  28587. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28588. "Basic " + detail::base64_encode("proxy-user:"),
  28589. "Basic realm=\"proxy\""));
  28590. ASSERT_NE(0, proxy.port());
  28591. ws::WebSocketClient client(origin.url());
  28592. client.set_proxy("127.0.0.1", proxy.port());
  28593. client.set_proxy_basic_auth("proxy-user", "");
  28594. auto res = client.connect();
  28595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28596. client.close();
  28597. EXPECT_EQ(1, proxy.connect_hits());
  28598. }
  28599. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28600. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28601. proxy_tunnel_test::ScopedConnectProxy proxy(
  28602. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28603. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28604. ASSERT_NE(0, proxy.port());
  28605. ws::WebSocketClient client(origin.url());
  28606. client.set_proxy("127.0.0.1", proxy.port());
  28607. auto res = client.connect();
  28608. EXPECT_FALSE(res);
  28609. EXPECT_EQ(Error::ProxyConnection, res.error());
  28610. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28611. EXPECT_EQ("Basic realm=\"proxy\"",
  28612. res.get_header_value("Proxy-Authenticate"));
  28613. EXPECT_FALSE(client.is_open());
  28614. }
  28615. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28616. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28617. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28618. ASSERT_NE(0, proxy.port());
  28619. ws::WebSocketClient client(origin.url());
  28620. client.set_proxy("127.0.0.1", proxy.port());
  28621. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28622. client.set_no_proxy({"127.0.0.1"});
  28623. auto res = client.connect();
  28624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28625. std::string msg;
  28626. ASSERT_TRUE(client.read(msg));
  28627. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28628. << "proxy credentials must not reach a bypassed origin";
  28629. client.close();
  28630. EXPECT_EQ(0, proxy.connect_hits());
  28631. }
  28632. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28633. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28634. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28635. ASSERT_NE(0, proxy.port());
  28636. ws::WebSocketClient client(origin.url());
  28637. client.set_proxy("127.0.0.1", proxy.port());
  28638. ASSERT_TRUE(client.connect());
  28639. ASSERT_TRUE(client.connect());
  28640. client.close();
  28641. EXPECT_EQ(2, proxy.connect_hits());
  28642. }
  28643. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28644. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28645. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28646. ASSERT_NE(0, proxy.port());
  28647. auto port = std::to_string(origin.port());
  28648. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28649. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28650. client.set_proxy("127.0.0.1", proxy.port());
  28651. auto res = client.connect();
  28652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28653. std::string msg;
  28654. ASSERT_TRUE(client.read(msg));
  28655. client.close();
  28656. EXPECT_EQ(1, proxy.connect_hits());
  28657. auto target = "127.0.0.1:" + port;
  28658. auto connect_req = proxy.connect_request();
  28659. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28660. EXPECT_NE(std::string::npos,
  28661. connect_req.find("\r\nHost: " + target + "\r\n"));
  28662. }
  28663. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28664. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28665. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28666. ASSERT_NE(0, proxy.port());
  28667. auto port = std::to_string(origin.port());
  28668. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28669. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28670. client.set_proxy("127.0.0.1", proxy.port());
  28671. auto res = client.connect();
  28672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28673. client.close();
  28674. auto target = "origin.example:" + port;
  28675. auto connect_req = proxy.connect_request();
  28676. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28677. EXPECT_NE(std::string::npos,
  28678. connect_req.find("\r\nHost: " + target + "\r\n"));
  28679. }
  28680. #ifdef CPPHTTPLIB_SSL_ENABLED
  28681. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28682. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28683. proxy_tunnel_test::ScopedConnectProxy proxy(
  28684. origin.port(), [](const std::string &head) -> std::string {
  28685. if (head.find(
  28686. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28687. std::string::npos) {
  28688. return proxy_tunnel_test::kTunnelEstablished;
  28689. }
  28690. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28691. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28692. "nonce=\"abc\", algorithm=MD5\r\n"
  28693. "Content-Length: 0\r\n\r\n";
  28694. });
  28695. ASSERT_NE(0, proxy.port());
  28696. ws::WebSocketClient client(origin.url());
  28697. client.set_proxy("127.0.0.1", proxy.port());
  28698. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28699. auto res = client.connect();
  28700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28701. std::string msg;
  28702. ASSERT_TRUE(client.read(msg));
  28703. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28704. client.close();
  28705. EXPECT_EQ(2, proxy.connect_hits());
  28706. }
  28707. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28708. proxy_tunnel_test::ScopedSSLServer origin;
  28709. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28710. origin.listen();
  28711. proxy_tunnel_test::ScopedConnectProxy proxy(
  28712. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28713. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28714. ASSERT_NE(0, proxy.port());
  28715. ws::WebSocketClient client(
  28716. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28717. client.enable_server_certificate_verification(false);
  28718. client.set_proxy("127.0.0.1", proxy.port());
  28719. client.set_proxy_bearer_token_auth("proxy-token");
  28720. auto res = client.connect();
  28721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28722. std::string msg;
  28723. ASSERT_TRUE(client.read(msg));
  28724. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28725. << "Proxy-Authorization must not be sent inside the tunnel";
  28726. client.close();
  28727. EXPECT_EQ(1, proxy.connect_hits());
  28728. }
  28729. #endif
  28730. // ---------------------------------------------------------------------------
  28731. // Poller
  28732. // ---------------------------------------------------------------------------
  28733. namespace poller_test {
  28734. struct PollerBackend {
  28735. const char *name;
  28736. std::unique_ptr<detail::Poller> (*create)();
  28737. };
  28738. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28739. *os << backend.name;
  28740. }
  28741. // Every backend runs the same contract tests. A new one is added here only.
  28742. std::vector<PollerBackend> poller_backends() {
  28743. return {
  28744. {"poll", &detail::PollPoller::create},
  28745. #ifdef __linux__
  28746. {"epoll", &detail::EpollPoller::create},
  28747. #endif
  28748. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28749. {"kqueue", &detail::KqueuePoller::create},
  28750. #endif
  28751. };
  28752. }
  28753. // A descriptor whose readability the test controls.
  28754. struct TestSocketPair {
  28755. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28756. TestSocketPair() { detail::create_socket_pair(fd); }
  28757. ~TestSocketPair() {
  28758. for (auto s : fd) {
  28759. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28760. }
  28761. }
  28762. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28763. socket_t reader() const { return fd[0]; }
  28764. void make_readable() {
  28765. const char c = 1;
  28766. detail::send_socket(fd[1], &c, 1, 0);
  28767. }
  28768. void close_writer() {
  28769. detail::close_socket(fd[1]);
  28770. fd[1] = INVALID_SOCKET;
  28771. }
  28772. };
  28773. using Tokens = std::vector<detail::Poller::Token>;
  28774. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28775. protected:
  28776. void SetUp() override {
  28777. poller_ = GetParam().create();
  28778. ASSERT_TRUE(poller_ != nullptr);
  28779. }
  28780. Tokens wait_for(int timeout_ms) {
  28781. Tokens ready;
  28782. poller_->wait(timeout_ms, ready);
  28783. std::sort(ready.begin(), ready.end());
  28784. return ready;
  28785. }
  28786. std::unique_ptr<detail::Poller> poller_;
  28787. };
  28788. } // namespace poller_test
  28789. using poller_test::PollerTest;
  28790. using poller_test::TestSocketPair;
  28791. using poller_test::Tokens;
  28792. INSTANTIATE_TEST_SUITE_P(
  28793. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28794. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28795. return std::string(p.param.name);
  28796. });
  28797. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28798. TestSocketPair sp;
  28799. ASSERT_TRUE(sp.ok());
  28800. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28801. EXPECT_EQ(Tokens{}, wait_for(0));
  28802. sp.make_readable();
  28803. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28804. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28805. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28806. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28807. }
  28808. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28809. TestSocketPair sp;
  28810. ASSERT_TRUE(sp.ok());
  28811. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28812. poller_->disarm(sp.reader());
  28813. poller_->disarm(sp.reader()); // disarming twice is harmless
  28814. sp.make_readable();
  28815. EXPECT_EQ(Tokens{}, wait_for(0));
  28816. }
  28817. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28818. TestSocketPair sp;
  28819. ASSERT_TRUE(sp.ok());
  28820. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28821. auto start = std::chrono::steady_clock::now();
  28822. EXPECT_EQ(Tokens{}, wait_for(30));
  28823. auto elapsed = std::chrono::steady_clock::now() - start;
  28824. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28825. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28826. }
  28827. TEST_P(PollerTest, NegativeTimeoutWaitsUntilReady) {
  28828. TestSocketPair sp;
  28829. ASSERT_TRUE(sp.ok());
  28830. ASSERT_TRUE(poller_->arm(sp.reader(), 3));
  28831. std::thread writer([&] {
  28832. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  28833. sp.make_readable();
  28834. });
  28835. auto ready = wait_for(-1);
  28836. writer.join();
  28837. EXPECT_EQ(Tokens{3}, ready);
  28838. }
  28839. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28840. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28841. for (detail::Poller::Token i = 0; i < 8; i++) {
  28842. sps.emplace_back(new TestSocketPair());
  28843. ASSERT_TRUE(sps.back()->ok());
  28844. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28845. }
  28846. sps[0]->make_readable();
  28847. sps[3]->make_readable();
  28848. sps[7]->make_readable();
  28849. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28850. // The others are still armed, the delivered ones are not.
  28851. sps[1]->make_readable();
  28852. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28853. EXPECT_EQ(Tokens{}, wait_for(0));
  28854. }
  28855. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28856. TestSocketPair s0, s1, s2;
  28857. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28858. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28859. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28860. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28861. // A delivery may move another entry inside the poller.
  28862. s0.make_readable();
  28863. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28864. // The entries left must still be found by descriptor.
  28865. poller_->disarm(s2.reader());
  28866. s1.make_readable();
  28867. s2.make_readable();
  28868. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28869. }
  28870. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  28871. TestSocketPair sp;
  28872. ASSERT_TRUE(sp.ok());
  28873. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  28874. sp.close_writer();
  28875. EXPECT_EQ(Tokens{5}, wait_for(1000));
  28876. char c;
  28877. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  28878. }
  28879. TEST_P(PollerTest, WakeEndsABlockedWait) {
  28880. std::thread waker([&] {
  28881. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  28882. poller_->wake();
  28883. });
  28884. Tokens ready;
  28885. auto start = std::chrono::steady_clock::now();
  28886. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  28887. waker.join();
  28888. EXPECT_TRUE(ready.empty());
  28889. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  28890. }
  28891. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  28892. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  28893. Tokens ready;
  28894. EXPECT_TRUE(poller_->wait(1000, ready));
  28895. }
  28896. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  28897. for (int i = 0; i < 1000; i++) {
  28898. poller_->wake();
  28899. }
  28900. Tokens ready;
  28901. EXPECT_TRUE(poller_->wait(0, ready));
  28902. EXPECT_FALSE(poller_->wait(0, ready));
  28903. poller_->wake();
  28904. EXPECT_TRUE(poller_->wait(0, ready));
  28905. }
  28906. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  28907. // Two threads publish changes and wake() after each, as a reactor's workers
  28908. // do. Every change must be seen without a wait() timing out. A lost wake()
  28909. // needs an unlucky interleaving, hence the rounds.
  28910. for (int round = 0; round < 5; round++) {
  28911. SCOPED_TRACE(round);
  28912. const int per_thread = 20000;
  28913. std::atomic<int> posted{0};
  28914. auto post = [&] {
  28915. for (int i = 0; i < per_thread; i++) {
  28916. posted++;
  28917. poller_->wake();
  28918. }
  28919. };
  28920. std::thread t1(post), t2(post);
  28921. auto lost = false;
  28922. Tokens ready;
  28923. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  28924. if (!poller_->wait(1000, ready)) {
  28925. lost = true;
  28926. break;
  28927. }
  28928. }
  28929. t1.join();
  28930. t2.join();
  28931. ASSERT_FALSE(lost);
  28932. }
  28933. }
  28934. TEST(PollerFactoryTest, MakePollerWorks) {
  28935. auto poller = detail::make_poller();
  28936. ASSERT_TRUE(poller != nullptr);
  28937. poller->wake();
  28938. std::vector<detail::Poller::Token> ready;
  28939. EXPECT_TRUE(poller->wait(1000, ready));
  28940. }
  28941. TEST(PollTimeoutTest, LastsUntilTheDeadline) {
  28942. using namespace std::chrono;
  28943. const auto now = steady_clock::now();
  28944. auto timeout = [&](steady_clock::time_point deadline) {
  28945. return detail::poll_timeout_until(deadline, now);
  28946. };
  28947. EXPECT_EQ(-1, timeout((steady_clock::time_point::max)()));
  28948. EXPECT_EQ(0, timeout(now - milliseconds(5)));
  28949. EXPECT_EQ(1, timeout(now + nanoseconds(1)));
  28950. EXPECT_EQ(1, timeout(now + milliseconds(1)));
  28951. EXPECT_EQ(2, timeout(now + microseconds(1001)));
  28952. EXPECT_EQ((std::numeric_limits<int>::max)(), timeout(now + hours(1000)));
  28953. }
  28954. // ---------------------------------------------------------------------------
  28955. // Keep-alive parking
  28956. // ---------------------------------------------------------------------------
  28957. namespace parking_test {
  28958. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  28959. // runs once the port is bound and listening, before the server accepts.
  28960. struct RunningServer {
  28961. explicit RunningServer(
  28962. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  28963. : svr_(svr) {
  28964. port = svr_.bind_to_any_port("127.0.0.1");
  28965. if (before_listen) { before_listen(port); }
  28966. thread = std::thread([this] { svr_.listen_after_bind(); });
  28967. svr_.wait_until_ready();
  28968. }
  28969. ~RunningServer() {
  28970. svr_.stop();
  28971. if (thread.joinable()) { thread.join(); }
  28972. }
  28973. Server &svr_;
  28974. int port = 0;
  28975. std::thread thread;
  28976. };
  28977. struct Sockets {
  28978. std::vector<socket_t> socks;
  28979. ~Sockets() {
  28980. for (auto s : socks) {
  28981. detail::close_socket(s);
  28982. }
  28983. }
  28984. socket_t connect(int port) {
  28985. auto error = Error::Success;
  28986. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  28987. false, false, nullptr, 2, 0, 2, 0, 2,
  28988. 0, std::string(), error);
  28989. if (s != INVALID_SOCKET) { socks.push_back(s); }
  28990. return s;
  28991. }
  28992. };
  28993. std::chrono::steady_clock::time_point in_ms(int ms) {
  28994. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  28995. }
  28996. bool readable_by(socket_t sock,
  28997. std::chrono::steady_clock::time_point deadline) {
  28998. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  28999. deadline - std::chrono::steady_clock::now())
  29000. .count();
  29001. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29002. }
  29003. bool send_get(socket_t sock, const std::string &path = "/") {
  29004. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29005. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29006. static_cast<ssize_t>(req.size());
  29007. }
  29008. // Reads one response whose body is "ok".
  29009. bool receives_ok(socket_t sock, int timeout_ms) {
  29010. auto deadline = in_ms(timeout_ms);
  29011. std::string buf;
  29012. while (readable_by(sock, deadline)) {
  29013. char tmp[1024];
  29014. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29015. if (n <= 0) { return false; }
  29016. buf.append(tmp, static_cast<size_t>(n));
  29017. auto end = buf.find("\r\n\r\n");
  29018. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29019. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29020. buf.compare(end + 4, 2, "ok") == 0;
  29021. }
  29022. }
  29023. return false;
  29024. }
  29025. bool get_ok(socket_t sock, int timeout_ms) {
  29026. return send_get(sock) && receives_ok(sock, timeout_ms);
  29027. }
  29028. // Whether the server closes `sock` by `deadline`.
  29029. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29030. char c;
  29031. return readable_by(sock, deadline) &&
  29032. detail::read_socket(sock, &c, 1, 0) <= 0;
  29033. }
  29034. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29035. auto deadline = in_ms(timeout_ms);
  29036. while (!cond()) {
  29037. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29038. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29039. }
  29040. return true;
  29041. }
  29042. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29043. svr.new_task_queue = std::move(new_task_queue);
  29044. svr.set_keep_alive_parking(true);
  29045. svr.Get("/", [](const Request &, Response &res) {
  29046. res.set_content("ok", "text/plain");
  29047. });
  29048. }
  29049. std::function<TaskQueue *(void)> threads(size_t n) {
  29050. return [n] { return new ThreadPool(n); };
  29051. }
  29052. // Counts what the event loop managed to queue, so that a test can wait for it.
  29053. class CountingTaskQueue final : public TaskQueue {
  29054. public:
  29055. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29056. std::atomic<int> &full)
  29057. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29058. bool enqueue(std::function<void()> fn) override {
  29059. auto queued = pool_.enqueue([this, fn]() {
  29060. fn();
  29061. // Holds the worker back from taking the next job.
  29062. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29063. });
  29064. (queued ? ok_ : full_)++;
  29065. return queued;
  29066. }
  29067. void shutdown() override { pool_.shutdown(); }
  29068. std::atomic<int> pause_after_ms{0};
  29069. private:
  29070. ThreadPool pool_;
  29071. std::atomic<int> &ok_;
  29072. std::atomic<int> &full_;
  29073. };
  29074. // Holds handlers until it opens, or for 3 seconds at most.
  29075. class Gate {
  29076. public:
  29077. void wait() {
  29078. std::unique_lock<std::mutex> lock(m_);
  29079. entered_++;
  29080. cv_.notify_all();
  29081. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29082. }
  29083. void open() {
  29084. std::lock_guard<std::mutex> guard(m_);
  29085. open_ = true;
  29086. cv_.notify_all();
  29087. }
  29088. int entered() {
  29089. std::lock_guard<std::mutex> guard(m_);
  29090. return entered_;
  29091. }
  29092. private:
  29093. std::mutex m_;
  29094. std::condition_variable cv_;
  29095. bool open_ = false;
  29096. int entered_ = 0;
  29097. };
  29098. } // namespace parking_test
  29099. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29100. using namespace parking_test;
  29101. Server svr;
  29102. serve_ok(svr, threads(1));
  29103. RunningServer running(svr);
  29104. Sockets socks;
  29105. // One kept-alive connection that has been served, and many that have not
  29106. // sent anything yet. None of them may keep the only worker.
  29107. auto served = socks.connect(running.port);
  29108. ASSERT_TRUE(get_ok(served, 2000));
  29109. for (int i = 0; i < 49; i++) {
  29110. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29111. }
  29112. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29113. EXPECT_TRUE(get_ok(served, 1000));
  29114. }
  29115. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29116. using namespace parking_test;
  29117. Server svr;
  29118. serve_ok(svr, threads(1));
  29119. svr.set_keep_alive_timeout(1);
  29120. RunningServer running(svr);
  29121. Sockets socks;
  29122. for (int i = 0; i < 3; i++) {
  29123. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29124. }
  29125. // One worker waiting on each in turn would take about 3 seconds.
  29126. auto deadline = in_ms(2000);
  29127. for (auto s : socks.socks) {
  29128. EXPECT_TRUE(sees_eof(s, deadline));
  29129. }
  29130. }
  29131. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29132. using namespace parking_test;
  29133. std::atomic<int> queued{0}, full{0};
  29134. Server svr;
  29135. // One worker and room for one queued task.
  29136. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29137. Gate gate;
  29138. svr.Get("/block", [&](const Request &, Response &res) {
  29139. gate.wait();
  29140. res.set_content("ok", "text/plain");
  29141. });
  29142. RunningServer running(svr);
  29143. // Before the server stops, so that a failed run does not wait for the
  29144. // handler's timeout.
  29145. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29146. Sockets socks;
  29147. auto a = socks.connect(running.port);
  29148. ASSERT_TRUE(get_ok(a, 2000));
  29149. // B keeps the only worker busy.
  29150. auto b = socks.connect(running.port);
  29151. ASSERT_TRUE(send_get(b, "/block"));
  29152. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29153. // A new connection C fills the queue.
  29154. auto c = socks.connect(running.port);
  29155. ASSERT_TRUE(send_get(c));
  29156. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29157. // A's next request finds the queue full, but A has been served before, so it
  29158. // waits instead of being cut off.
  29159. ASSERT_TRUE(send_get(a));
  29160. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29161. gate.open();
  29162. EXPECT_TRUE(receives_ok(b, 2000));
  29163. EXPECT_TRUE(receives_ok(c, 2000));
  29164. EXPECT_TRUE(receives_ok(a, 2000));
  29165. }
  29166. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29167. using namespace parking_test;
  29168. std::atomic<int> queued{0}, full{0};
  29169. CountingTaskQueue *queue = nullptr;
  29170. Server svr;
  29171. // Two workers and room for one queued task.
  29172. serve_ok(svr,
  29173. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29174. Gate first, second;
  29175. svr.Get("/first", [&](const Request &, Response &res) {
  29176. first.wait();
  29177. res.set_content("ok", "text/plain");
  29178. });
  29179. svr.Get("/second", [&](const Request &, Response &res) {
  29180. second.wait();
  29181. res.set_content("ok", "text/plain");
  29182. });
  29183. RunningServer running(svr);
  29184. auto open_gates = detail::scope_exit([&] {
  29185. first.open();
  29186. second.open();
  29187. });
  29188. Sockets socks;
  29189. auto a = socks.connect(running.port);
  29190. ASSERT_TRUE(get_ok(a, 2000));
  29191. // B and D take both workers, and C fills the queue. One at a time: the
  29192. // queue has room for one job only until a worker takes it.
  29193. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29194. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29195. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29196. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29197. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29198. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29199. // A's next request waits in the backlog.
  29200. ASSERT_TRUE(send_get(a));
  29201. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29202. // B's worker finishes, then takes C off the queue only later, which makes
  29203. // room for A.
  29204. queue->pause_after_ms = 200;
  29205. first.open();
  29206. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29207. queue->pause_after_ms = 0;
  29208. second.open();
  29209. EXPECT_TRUE(receives_ok(a, 2000));
  29210. }
  29211. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29212. using namespace parking_test;
  29213. Server svr;
  29214. serve_ok(svr, threads(1));
  29215. svr.set_keep_alive_timeout(0);
  29216. // The request is on the socket before the server accepts the connection,
  29217. // so it does not race the 10 ms floor. Without the floor the connection is
  29218. // closed unread.
  29219. Sockets socks;
  29220. auto sock = INVALID_SOCKET;
  29221. RunningServer running(svr, [&](int port) {
  29222. sock = socks.connect(port);
  29223. send_get(sock);
  29224. });
  29225. EXPECT_TRUE(receives_ok(sock, 1000));
  29226. }
  29227. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29228. using namespace parking_test;
  29229. for (int round = 0; round < 5; round++) {
  29230. SCOPED_TRACE(round);
  29231. Server svr;
  29232. serve_ok(svr, threads(2));
  29233. RunningServer running(svr);
  29234. Sockets socks;
  29235. for (int i = 0; i < 20; i++) {
  29236. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29237. }
  29238. auto start = std::chrono::steady_clock::now();
  29239. svr.stop();
  29240. running.thread.join();
  29241. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29242. std::chrono::milliseconds(500));
  29243. auto deadline = in_ms(1000);
  29244. for (auto s : socks.socks) {
  29245. EXPECT_TRUE(sees_eof(s, deadline));
  29246. }
  29247. }
  29248. }
  29249. #ifdef CPPHTTPLIB_SSL_ENABLED
  29250. namespace parking_test {
  29251. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29252. // that has opened a connection ahead of time. Freeing the session sends no
  29253. // close_notify, so the connection stays quiet.
  29254. bool handshake_only(socket_t sock) {
  29255. auto ctx = tls::create_client_context();
  29256. tls::set_verify_client(ctx, false);
  29257. auto session = tls::create_session(ctx, sock);
  29258. auto se = detail::scope_exit([&] {
  29259. tls::free_session(session);
  29260. tls::free_context(ctx);
  29261. });
  29262. tls::TlsError err;
  29263. return session &&
  29264. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29265. }
  29266. Client tls_client(int port) {
  29267. Client cli("https://127.0.0.1:" + std::to_string(port));
  29268. cli.enable_server_certificate_verification(false);
  29269. cli.set_keep_alive(true);
  29270. cli.set_connection_timeout(1);
  29271. cli.set_read_timeout(1);
  29272. return cli;
  29273. }
  29274. bool tls_get_ok(Client &cli) {
  29275. auto res = cli.Get("/");
  29276. return res && res->body == "ok";
  29277. }
  29278. } // namespace parking_test
  29279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29280. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29281. struct {
  29282. unsigned long version;
  29283. bool safe;
  29284. } cases[] = {
  29285. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29286. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29287. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29288. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29289. };
  29290. for (const auto &c : cases) {
  29291. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29292. << std::hex << c.version;
  29293. }
  29294. }
  29295. #endif
  29296. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29297. using namespace parking_test;
  29298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29299. ASSERT_TRUE(svr.is_valid());
  29300. serve_ok(svr, threads(1));
  29301. svr.set_read_timeout(1); // so that a failing run does not take long
  29302. RunningServer running(svr);
  29303. Sockets socks;
  29304. // One served connection, some that have not started their handshake, and
  29305. // one that has finished it and gone quiet. None may keep the only worker.
  29306. auto served = tls_client(running.port);
  29307. ASSERT_TRUE(tls_get_ok(served));
  29308. for (int i = 0; i < 10; i++) {
  29309. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29310. }
  29311. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29312. auto other = tls_client(running.port);
  29313. EXPECT_TRUE(tls_get_ok(other));
  29314. EXPECT_TRUE(tls_get_ok(served));
  29315. }
  29316. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29317. using namespace parking_test;
  29318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29319. ASSERT_TRUE(svr.is_valid());
  29320. serve_ok(svr, threads(1));
  29321. RunningServer running(svr);
  29322. Sockets socks;
  29323. auto plain = socks.connect(running.port);
  29324. ASSERT_TRUE(send_get(plain));
  29325. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29326. EXPECT_NE(0, svr.ssl_last_error());
  29327. }
  29328. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29329. using namespace parking_test;
  29330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29331. ASSERT_TRUE(svr.is_valid());
  29332. serve_ok(svr, threads(2));
  29333. RunningServer running(svr);
  29334. std::vector<Client> clients;
  29335. for (int i = 0; i < 5; i++) {
  29336. clients.push_back(tls_client(running.port));
  29337. ASSERT_TRUE(tls_get_ok(clients.back()));
  29338. }
  29339. auto start = std::chrono::steady_clock::now();
  29340. svr.stop();
  29341. running.thread.join();
  29342. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29343. std::chrono::milliseconds(500));
  29344. }
  29345. #endif